Here if
document.write(eval("(2 == 2)"));
it prints true
And
document.write(eval("(2 == 2)&(5<10)"));
it prints 1
Why not it always returns true or false.If conditions increases in string it gives 0 or 1.What is the way to get same type of result.
Because & isn't a logical operator, it's a bitwise (numeric) operator. You probably meant &&, the logical AND operator.
Note that there's no reason for using eval in your code examples. (There's almost never any reason to use eval, there's almost always a better alternative — in this case, you don't even need an alternative.) Removing it would have exactly the same result.
It prints 1 because you used the bitwise and operator (&) instead of the logical and operator (&&).
And because JavaScript is loosely typed it will treat the boolean value true as an int value of 1, which you can check by invoking
document.write(eval("(2 == 2)+(5<10)"));
the result will be
2
& is a bitwise operator and returns a number. Try "(2 == 2)&&(5<10)"
Related
Quick and a silly question that got me confused.
What kind of error occurs if I use an assignment statement instead of a comparison statement? I need to check if the value of the counter variable is equal to 5.
The code:
if (counter = 5) { /* ==SOME CODE==*/}
VS
if (counter == 5) { /* ==SOME CODE==*/}
The easiest way to pick-up this problem is to reverse the order of the comparison.
Instead of:
if (someVar == 5)
Use:
if (5 == someVar)
This way, if you mess it up, you'll get an assignment error, since you can't assign a different value to the number 5. You can assign a different value to a number object that happens to hold the number 5, but you can't change the 5 itself. ;)
What kind of error occurs if I use an assignment statement instead of a comparison statement?
In your example i assume that a browser would not throw any errors.
I tested https://validatejavascript.com/ with this code:
let counter = 3;
if (counter = 5) {
alert('Will this ever show or always?');
}
A linter might generate a warning - for exmaple
validatejavascript.com threw: 3:5 error Unexpected assignment within an 'if' statement. (no-cond-assign) and
jshint.com threw: Expected a conditional expression and instead saw an assignment.
And based on your comment:
But I need to check if the value of the counter variable is equal to 5.
A simple assignment operator (=) is used to assign a value to a variable.
What you are looking for are operators for Equality comparisons and sameness
JavaScript provides three different value-comparison operations:
=== - Strict Equality Comparison ("strict equality", "identity", "triple equals")
== - Abstract Equality Comparison ("loose equality", "double equals")
Object.is provides SameValue (new in ES2015).
Which operation you choose depends on what sort of comparison you are
looking to perform. Briefly:
double equals (==) will perform a type conversion
when comparing two things, and will handle NaN, -0, and +0
specially to conform to IEEE 754 (so NaN != NaN, and -0 == +0);
triple equals (===) will do the same comparison as double equals
(including the special handling for NaN, -0, and +0)
but without type conversion; if the types differ, false is returned.
Object.is does no type conversion and no special handling for NaN, -0,
and +0 (giving it the same behavior as === except on those special
numeric values).
Note that the distinction between these all have to do with their
handling of primitives; none of them compares whether the parameters
are conceptually similar in structure. For any non-primitive objects x
and y which have the same structure but are distinct objects
themselves, all of the above forms will evaluate to false.
So I'm reading through this precedence table https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
It says 20 - 1 with 20 being highest precedence.
16 Logical NOT right-to-left ! … So the ! operator has a precedence of 16.
10 Strict Equality … === … So the === operator has a precendence of 10.
This lines
!'hello' === 'goodbye'
How does this get executed/read? By reading it I thought. In steps it goes;
'hello' === 'goodbye' Check then, invert bool value. So If it returns true set it to false.
If i'm reading through the precedence operators table. It looks to me like it does the ! operator first and then ===.
How does it invert a non-bool value beforehand and then do the truthy check? Like how does it work could someone explain?
Thank you!
It looks to me like it does the ! operator first and then ===.
Yes. 16 is a higher number than 10, so ! has a higher precedence than ===, so it is resolved first.
How does it invert a non-bool value beforehand and then do the truthy check?
See the spec for ! which points to ToBoolean which says:
String: Return false if argument is the empty String (its length is zero); otherwise return true.
I am looking at these lines of code from here:
if (callback)
callback(sig || graph);
I have never see vertical "or" bars in a javascript method call. What do they mean? Do they pass the "true" parameter (i.e. sig or graph)? Do they pass the defined parameter? I have never seen that syntax before.
This is the logical OR operator in JS (and most other languages). It is defined in the spec at 11.11. As noted in the spec, expressions on either side will be evaluated first and the logical OR is left-to-right associative. Note that evaluation of the operands follows standard ToBoolean semantics from section 9.2, so [null, undefined, 0, ''] all count as falsy.
Unlike most languages, JS returns the left operand if it is truthy or the right operand otherwise. This behavior has been covered before in a number of SO questions, but is worth noting as most languages simply return true or false. This behavior is often used to provide default values to otherwise undefined variables.
The Logical OR operator (||) is an operator that returns its first or second operand depending on whether the first is truthy. A "truthy" value means anything other than 0, undefined, null, "", or false.
This operator uses short-circuiting, meaning if the first expression is truthy, then the second expression is not evaluated and the first operand is returned immediately. This is akin to the Logical AND operator (&&), which does the opposite: if the first operand is falsey, it returns it, otherwise it returns the second expression.
It means 'or' (http://www.w3schools.com/js/js_comparisons.asp) So if(sig OR graph)
BE CAREFUL you can 'short circuit' your code using this.
example :
If (foo || foo2)
if foo is true, then JavaScript wont even test foo2 at all, it just skips it.
It passes whichever evaluates as true, or sig if both are true.
The double pipe (||) represents OR in JS. In simple words, either this or that is True. It requires any of the sides true to get a True result.
For example:
var x = 8;
var y = 'c';
x >= 8 || y === 'a'
The left side of the double pipe returns True where the right side is False. Thus, the result is True.
The operator || means OR.
If either sig or graph are true or not null variables, callback function will receive a true argument.
If you evaluate 1|0,2|0 in JavaScript, you'll get 2.
If you evaluate 1|0+','+2|0, you'll get 1.
I cannot make sense of this.
The binary bitwise operators (including |) bind less tightly than the addition operator +. Thus
1|0+','+2|0
is really
1|(0+','+2)|0
which is
1|('0,2')|0
which is
1|0|0
which is 1. (The string "0,2" is converted to an integer; as a number it's NaN, but because NaN is a floating-point concept it turns into 0 when forced to be an integer.)
edit — as to the first expression, 1|0,2|0, that involves the JavaScript comma operator. The comma operator allows a list of separate, essentially independent (other than through side-effects) expressions to be "glued together" into something the parser will recognize as a single expression. When evaluated, each expression will be computed as it normally would be, but the value of the overall expression is just the value of the last one in the list. Thus, 1|0,2|0 will first cause 1|0 to be evaluated, but that result is thrown away and the overall value is just that of 2|0.
The comma operator is common to many languages that derive their expression syntax from C. (For all I know, C got it from somewhere else; it's hardly a revolutionary concept.) Because such languages allow for an expression — just one expression — to appear in several interesting grammatical situations, and because expressions can (and often do) have side effects, it's sometimes handy to be able to jam several separate expressions into a spot where the language really wants only one. That said, there are often cleaner and better ways to do things. In JavaScript, I would personally prefer to use an immediately-invoked function. It's more typing and probably a little worse for performance reasons, but I think it's a lot cleaner because it allows for an isolated namespace for temporary variables and more involved logic.
You need to look at an operator precedence table to make sense of this.
The expression 1|0,2|0 has bitwise-or at a higher precedence than the comma operator, so it's equivalent to (1|0), (2|0). The comma operator evaluates both operands and returns the second one, so you get the value of (2|0). That value is 2.
The expression 1|0+','+2|0 has addition at a higher precedence than bitwise-or, so it's equivalent to 1|(0+','+2)|0. The result of 0+','+2 is "0,2", which is not numerical, so it evaluates to NaN in numerical operations. It is coerced to 0 in bitwise-or, so that leaves 1|0|0, and the result of that is 1.
From MDN:
The comma operator evaluates both of its operands (from left to right)
and returns the value of the second operand.
Thus, in 1|0,2|0, first the two expressions 1|0 and 2|0 are evaluated from left to right and then the result of the last expression (2|0) is returned. 1|0 === 1 and 2|0 === 2, so the result of the last expression is 2 and that's returned.
In 1|0+','+2|0, the comma appears in a string literal which is concatenated with 0 and 2. The whole thing is evaluated as followed:
( 1 | ( (0+',')+2 ) ) | 0
( 1 | ( '0,'+2 ) ) ) | 0 (number + string = string concatenation)
( 1 | '0,2' ) | 0 (string + number = string concatenation)
( 1 | NaN ) | 0 (bitwise OR needs number operands. 0,2 fails to be converted, giving NaN instead)
1 | 0 (bitwise OR only deals with integers, so the floating-point NaN is cast to 0)
1
I always thought that an if statement essentially compared it's argument similar to == true. However the following experiment in Firebug confirmed my worst fears—after writing Javascript for 15 years I still have no clue WTF is going on:
>>> " " == true
false
>>> if(" ") console.log("wtf")
wtf
My worldview is in shambles here. I could run some experiments to learn more, but even then I would be losing sleep for fear of browser quirks. Is this in a spec somewhere? Is it consistent cross-browser? Will I ever master javascript?
"If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers; if either operand is a string, the other one is converted to a string."
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Comparison_Operators
So the first one does:
Number(" ")==Number(true)
While the second one is evaluated like this:
if(Boolean(" ")==true) console.log("wtf")
I am guessing that it is the first part that is a problem, not the second.
It probably does some weird casting (most likely, true is cast to a string instead of " " being cast to a boolean value.
What does FireBug return for Boolean(" ") ?
JavaScript can be quirky with things like this. Note that JavaScript has == but also ===. I would have thought that
" " == true
would be true, but
" " === true
would be false. The === operator doesn't do conversions; it checks if the value and the type on both sides of the operator are the same. The == does convert 'truthy' values to true and 'falsy' values to false.
This might be the answer - from JavaScript Comparison Operators (Mozilla documentation):
Equal (==)
If the two operands are not of the same type, JavaScript converts the operands then applies strict comparison. If either operand is a number or a boolean, the operands are converted to numbers; if either operand is a string, the other one is converted to a string
Highly recommended: Douglas Crockford on JavaScript.
Answer: aTruthyValue and true are not the same.
The semantic of the if statement is easy:
if(aTruthyValue) {
doThis
} else {
doThat
}
Now it's just the definition of what a truthy value is. A truthy value is, unfortunately, not something that is simply "== true" or "=== true".
ECMA-262 1.5
Setion 9.2 explains what values are truthy and which are not.
I recommend using === whenever possible, if only to avoid having existential crises.