Unless otherwise specified on a case by case basis, these notes have been taken upon reading Eloquent JavaScript, A Modern Introduction to Programming, second edition, by Marijn Haverbeke, No Starch Press, San Francisco, 2015.
Basic data types
- Numbers (special values: Infinity, -Infinity, NaN)
- Strings
- Booleans (true and false, in lower case)
- Objects
- Functions
- Undefined values: null and undefined. Note that (typeof null) returns "object".
Tricky logical expressions
Convertions to booleans: the values 0, NaN, and "" are converted to false. Everything else is converted to true.
The logical expression (null == undefined) evaluates to true.
(exp1 || epx2) and (exp1 && exp2) evaluate to either exp1 or exp2 (not true or false), so they might not evaluate to boolean values. For example, (false || "hello") evaluates to "hello".
The operators === and !== check whether types and values are equal (i.e. they do not do type coercion before the comparison), whereas == and != do do type coercion.
Other tricky things
Be careful with surprising implicit type coercions, for example:
- 10 * null evaluates to 0 (null is coerced to 0). However, (null == 0) evaluates to false.
- "10" - 1 evaluates to 9 ("10" is coerced to a number).
- "10" + 1 evaluates to "101" (1 coerced to a string).
Uninitialized variables have the value undefined.
Accessing a property that does not exist in an object is not an error, it yields an undefined value.
In a function, a return statement without a value returns undefined.
Calling a function with the wrong number of arguments creates no error. Extra arguments are ignored and missing ones are set to undefined.
Similarly to C, a break statement is needed at the end of each clause in a switch/case statement.
In a block, "let" creates a variable that is local to the block, whereas var does not create a new variable if it already exists in the parent block