What does an exclamation mark before a function do?
Example:
return !loadDynamicBlock();
A ! negates an expression.
In your example, if loadDynamicBlock() returned true, the function calling it would return false, and vice-versa: !true == false
It can also be used to create actual booleans from JavaScript's ideas of truthy and falsy.
var a = 5;
!!(a - 5) === false;
!!(a + 5) === true;
The ! in Javascript inverts a boolean expression.
Related
I've been working on learning JS, and I can't seem to figure out why my boolean values keep coming back either always true or always false.
So I believe I understand the basics of the truthy/falsy situation in JS, but I can't seem to get it right. I know that there are data type issues, (can't make different data types do different things).
function lastCharacter(char1, char2) {
if (char1[-1] === '' && char2[-1] === '') {
return true;
} else {
return false;
}
}
console.log(lastCharacter('apple', 'pumpkine'));
Or
function lastCharacter(char1, char2) {
if (char1[-1] === char2[-1]) {
return true;
} else {
return false;
}
}
console.log(lastCharacter('apple', 'pumpkina'));
Define a function lastCharacter that accepts two strings as arguments.
lastCharacter should return true if both strings end with the same character.
Otherwise, lastCharacter should return false.
They either return always true or always false. Can anyone help me?
You need a different method for getting the last character of a string, preferably with String#slice and a negative value for getting the last one. Then compare and return the result.
function lastCharacter(string1, string2) {
return string1.slice(-1) === string2.slice(-1);
}
console.log(lastCharacter('apple', 'pumpkine'));
A comparison between taking the last character of an empty string by using an index -1 which returns undefined and slice, which returns an empty string.
var x = '';
console.log('#' + x.slice(-1) + '#');
console.log('#' + x[x.length -1] + '#');
You can use slice
function lastCharacter(char1, char2) {
return char1.slice(-1) === char2.slice(-1)
}
console.log(lastCharacter('apple', 'pumpkina'));
console.log(lastCharacter('apple', 'snake'));
Or you can just access the last index
function lastCharacter(char1, char2) {
return char1[char1.length-1] === char2[char2.length-1]
}
console.log(lastCharacter('apple', 'pumpkina'));
console.log(lastCharacter('apple', 'snake'));
There are no negative array indexes in JavaScript, instead of char1[-1] you have to use char1[char1.length - 1].
Accessing one of a strings characters (e.g. "abc[1]) will always have a length of 1, it will never be equal to "". Your second function makes more sense.
Also
if(condition) { return true; } else { return false; }
is equal to
return condition;
The notation [-1] does not implicitly mean "one character from the end of the string" in JavaScript. You can use str[str.length - 1]. (If you expect possible empty source strings, you'd want to check for that too to avoid ending up with exactly the same problem.)
Instead of an if/else that returns either true or false, just return the results of the logical expression:
return char1[char1.length - 1] === '' && char2[char2.length - 1] === '';
Both the === comparisons return either true or false anyway, so the overall expression value has to be one of those. In general however if you want to make absolutely sure that you end up with a boolean, you can prefix an expression with !! to force the standard JavaScript "truthy-falsy" evaluation:
return !!(expression);
Is it valid to use an if clause with .hasClass()?
Example:
if ($(this).hasClass("class")){
this will happen
}
Or
if ($(this).hasClass("class") == true){
this will happen
}
Looking at the source itself of hasClass, we can see that only a boolean can be returned
function (selector) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for (; i < l; i++) {
if (this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf(className) >= 0) {
return true;
}
}
return false;
}
Therefore, checking without comparing is valid
if ($(this).hasClass("class")){
It is valid to use an if statement with any expression. The if statement is a control flow statement that either jumps over the immediate block (or single statement) or executes it, depending on the value of the expression inside the statement. Any value will be coerced to Boolean using standard coercion rules.
The == comparison operator evaluates to a Boolean that's true if both both operands are equal (using this algorithm), and false otherwise. A comparison of any value to true is redundant, since if it is true, or is convertible to true, the expression would also be true, and will be false for any other value
In the case of .hasClass(), the return value is already a Boolean so no coercion is required.
So, Yes it's valid, there's no difference between the statements, and you can (and should) use the first.
Many of us have seen / use the following:
var t=!0; (t will equal true)
var t=!1; (t will equal false)
How safe is this method of evaluating true / false?
I see google use this all the time.
Will these ALWAYS return a boolean true / false?
Thanks.
Yes:
11.4.9 Logical NOT Operator ( ! )
The production UnaryExpression : ! UnaryExpression is evaluated as
follows:
Let expr be the result of evaluating UnaryExpression.
Let oldValue be ToBoolean(GetValue(expr)).
If oldValue is true, return false.
Return true.
Source: http://es5.github.com/x11.html#x11.4.9
Yes, they'll always return true and false.
More specifically, !x will return true for any "falsey" value (undefined, "", etc) and conversely return false for any "truthy" value.
A more common idiom is !!x which converts any "falsey" value to strictly false and any "truthy" value to strictly true - in other words it's like a "type cast" to a boolean.
I was examining the src of underscore.js and discovered this:
_.isRegExp = function(obj) {
return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
};
Why was "!!" used? Should it be read as NOT-NOT or is there some esoteric JS nuance going on here?
It is just an obtuse way to cast the result to a boolean.
Yes, it's NOT-NOT. It is commonly used idiom to convert a value to a boolean of equivalent truthiness.
JavaScript understands 0.0, '', null, undefined and false as falsy, and any other value (including, obviously, true) as truthy. This idiom converts all the former ones into boolean false, and all the latter ones into boolean true.
In this particular case,
a && b
will return b if both a and b are truthy;
!!(a && b)
will return true if both a and b are truthy.
The && operator returns either false or the last value in the expression:
("a" && "b") == "b"
The || operator returns the first value that evaluates to true
("a" || "b") == "a"
The ! operator returns a boolean
!"a" == false
So if you want to convert a variable to a boolean you can use !!
var myVar = "a"
!!myVar == true
myVar = undefined
!!myVar == false
etc.
It is just two ! operators next to each other. But a double-negation is pointless unless you are using !! like an operator to convert to Boolean type.
It will convert anything to true or false...
This question already has answers here:
How can I convert a string to boolean in JavaScript?
(102 answers)
Closed 5 years ago.
How to convert a string to Boolean ?
I tried using the constructor Boolean("false"), but it's always true.
I would use a simple string comparison here, as far as I know there is no built in function for what you want to do (unless you want to resort to eval... which you don't).
var myBool = myString == "true";
I would like to answer this to improve upon the accepted answer.
To improve performance, and in real world cases where form inputs might be passing values like 'true', or 'false', this method will produce the best results.
function stringToBool(val) {
return (val + '').toLowerCase() === 'true';
}
JSPerf
you can also use JSON.parse() function
JSON.parse("true") returns true (Boolean)
JSON.parse("false") return false (Boolean)
Actually you don't get the meaning of Boolean method.It always return true if the variable is not null or empty.
var variable = some value;
Boolean(variable);
If my variable have some value then it will
return true
else
return false
You can't use Boolean as you think.
trick string to boolean conversion in javascript. e.g.
var bool= "true";
console.log(bool==true) //false
var bool_con = JSON.parse(bool);
console.log(bool_con==true) //true
I am still amazed how people vote blindly for solutions that won't work, like:
var myBool = myString == "true";
The above is so BUGGY!!!
Not convinced? Just try myString = true (I mean the boolean true). What is the evaluation now? Opps: false!
Alternative
var myString=X; // X={true|false|"true"|"false"|"whatever"}
myString=String(myString)=='true';
console.log(myString); // plug any value into X and check me!
will always evaluate right!
Depends on what you see as false in a string.
Empty string, the word false, 0, should all those be false or is only empty false or only the word false.
You probably need to buid your own method to test the string and return true or false to be 100 % sure that it does what you need.
I believe the following code will do the work.
function isBoolean(foo) {
if((foo + "") == 'true' || (foo + "") == 'false') {
foo = (foo + "") == 'true';
} else {
console.log("The variable does not have a boolean value.");
return;
}
return foo;
}
Explaining the code:
foo + ""
converts the variable 'foo' to a string so if it is already boolean the function will not return an invalid result.
(foo + "") == 'true'
This comparison will return true only if 'foo' is equal to 'true' or true (string or boolean). Note that it is case-sensitive so 'True' or any other variation will result in false.
(foo + "") == 'true' || (foo + "") == 'false'
Similarly, the sentence above will result in true only if the variable 'foo' is equal to 'true', true, 'false' or false. So any other value like 'test' will return false and then it will not run the code inside the 'if' statement. This makes sure that only boolean values (string or not) will be considered.
In the 3rd line, the value of 'foo' is finally "converted" to boolean.
These lines give the following output:
Boolean(1).toString(); // true
Boolean(0).toString(); // false
Unfortunately, I didn't find function something like Boolean.ParseBool('true') which returns true as Boolean type like in C#.
So workaround is
var setActive = 'true';
setActive = setActive == "true";
if(setActive)
// statements
else
// statements.
javascript:var string="false";alert(Boolean(string)?'FAIL':'WIN')
will not work because any non-empty string is true
javascript:var string="false";alert(string!=false.toString()?'FAIL':'WIN')
works because compared with string represenation
See this question for reference:
How can I convert a string to boolean in JavaScript?
There are a few ways:
// Watch case sensitivity!
var boolVal = (string == "true");
or
var boolVal = Boolean("false");
or
String.prototype.bool = function() {
return (/^true$/i).test(this);
};
alert("true".bool());
You can try this:
var myBoolean = Boolean.parse(boolString);