Accidentally Using the Assignment Operator
This if statement returns false (as expected) because x is not equal to 10:
This if statement returns true (maybe not as expected), because 10 is true:
This if statement returns false (maybe not as expected), because 0 is false:
An assignment always returns the value of the assignment.
Expecting Loose Comparison
In regular comparison, data type does not matter. This if statement returns true:
In strict comparison, data type does matter. This if statement returns false:
It is a common mistake to forget that switch statements use strict comparison:
This case switch will display an alert:
This case switch will not display an alert:
Confusing Addition & Concatenation
Addition is about adding numbers.
Concatenation is about adding strings.
Because of this, adding a number as a number will produce a different result from adding a number as a string:
When adding two variables, it can be difficult to anticipate the result:
To solve the problem above, it helps to multiply and divide:
But, breaking a statement in the middle of a string will not work:
You must use a "backslash" if you must break a statement in a string:
Because of a misplaced semicolon, this code block will execute regardless of the value of x:
Breaking a Return Statement
Because of this, these two examples will return the same result:
Because of this, example 3 will also return the same result:
But, what will happen if you break the return statement in two lines like this:
The function will return undefined!
If a statement is incomplete like:
But since this statement is complete:
Never break a return statement.
Accessing Arrays with Named Indexes
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
After the automatic redefinition, array methods and properties will produce undefined or incorrect results:
Ending an Array Definition with a Comma
Correct:points = [40, 100, 1, 5, 25, 10];
Ending an Object Definition with a Comma
Undefined is Not Null
To be null, an object has to be defined, otherwise it will be undefined.
If you want to test if an object exists, this will throw an error if the object is undefined:
Because of this, you must test typeof() first:
Expecting Block Level Scope