This question already has answers here:
Is it safe to assume strict comparison in a JavaScript switch statement?
(3 answers)
Closed 8 years ago.
Does the Javascript switch statement compare strictly or by type-converting?
I can't believe it was faster to ask this question than it was to just try this:
var v = "1";
switch (v) {
case 1:
alert ("No");
break;
default:
alert ("Yes");
}
In answer to your question, it's ===.
It only uses strict comparison. In particular, it never falls back to type coercion even when no strict matches are found — it will immediately skip to the default clause, if any. From MDN:
The program first looks for a case clause whose expression evaluates to the same value as the input expression (using strict comparison, ===) and then transfers control to that clause, executing the associated statements. If no matching case clause is found, the program looks for the optional default clause...
According to MDN
it uses strict comparison.
The program first looks for a case clause whose expression evaluates to the same value as the input expression (using strict comparison, ===) and then transfers control to that clause, executing the associated statements.
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.
Which expression inside if statement will be evaluated faster?
var test = true;
if( test == true ) {...}
OR
var test = true;
if( test ) {...}
Only got info about The Abstract Equality Comparison Algorithm and The Strict Equality Comparison Algorithm
Wanted to know more about how Truthy/Falsy values are evaluated.
Any help is appreciated.
Thanks
The second example might be a bit faster (but since JS is today usually first compiled into a bytecode and only then evaluated, it's probable the generated bytecode will be the same in both cases).
It all starts with The if statement. Its first step (and the only step that will differ in your examples) is to evaluate the expression within parentheses. In the second example, the expression is immediately evaluated to itself (true). In the first example, The Abstract Equality Comparison Algorithm, as you mentioned, will be used. It will make a few steps and return true from step 1.e.
In practice, I doubt the difference will be measurable.
This question already has answers here:
Object.is vs ===
(6 answers)
Closed 5 years ago.
We know what the difference between == and === is - basically, === prevents Javascript engine to convert one of the parameter for making both parameters of the same type. But now, in ES6, came a new operator - Object.is which is a bit confusing (or maybe === is now confusing..)
From Mozila website (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness) we can see the difference:
Sameness Comparisons:
x y == === Object.is
+0 -0 true true false
NaN NaN false false true
So, for me, looks like Object.is is even more strict in comparing parameters, if so, question raises - how unstrict was === (called "Strict Equality") :)
From the article you linked:
When to use Object.is versus triple equals
Aside from the way it treats NaN, generally, the only time Object.is's special behavior towards zeros is likely to be of interest is in the pursuit of certain meta-programming schemes, especially regarding property descriptors when it is desirable for your work to mirror some of the characteristics of Object.defineProperty. If your use case does not require this, it is suggested to avoid Object.is and use === instead. Even if your requirements involve having comparisons between two NaN values evaluate to true, generally it is easier to special-case the NaN checks (using the isNaN method available from previous versions of ECMAScript) than it is to work out how surrounding computations might affect the sign of any zeros you encounter in your comparison.
Via MDN:
This is also not the same as being equal according to the === operator. The === operator (and the == operator as well) treats the number values -0 and +0 as equal and treats Number.NaN as not equal to NaN.
This question already has answers here:
Question mark and colon in JavaScript
(8 answers)
Closed 8 years ago.
So I used an online JavaScript optimizer and it did something strange to my IF statements that is new to me.
{1===a?window.addEventListener("scroll",turnOff):0===a&&window.removeEventListener("scroll",turnoff)}
What in the world is this? Help me to understand the parts of it please.
The three equal signs are a representation of strict comparison operators. Unlike the usual double equal signs, using === compares both the type and value of the expressions being compared. Both the type and value must be equal for the statement to evaluate to true.
The ? and : are shorthand versions of the if statement. When 1===a is true, the statement after the question mark is evaluated. Otherwise, the statement after the colon is evaluated. This shorthand version of the if statement is known as a Conditional (or Ternary) operator.
It is a Conditional (Ternary) operator.
You can read more about ternary operators at the developer Mozilla docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
It is structured like this:
condition ? code if true : code if false
The ? Operator is used just as an if.
if(a){
b;
} else {
c;
}
is equal to
a ? b : c;
It's called a ternary operator. It compares the condition
if a === 1
and returns the first result if the condition is true:
window.addEventListener("scroll",turnOff)
and the second if false:
0===a&&window.removeEventListener("scroll",turnoff)
This line of code does two things, sets a equal to 0 and removes an event listener.
See this tutorial
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.