8 data types
7 primitives + 1 reference.
- Primitives (by value):
number,string,boolean,undefined,null,symbol,bigint. - Reference:
object— includes arrays, functions, dates, regex, Map, Set. - Primitives are immutable and compared by value; objects are mutable and compared by reference.
typeof null === "object"(historical bug);typeof []is also"object"— useArray.isArray().
Type coercion rules
Implicit conversion when operators disagree.
+with any string → string concatenation wins."5" + 3 + 2 === "532".-,*,/,%,**coerce to number."5" - 3 === 2.- Numeric conversions to remember:
true → 1,false → 0,null → 0,undefined → NaN,"" → 0. - Unary
+is the short form ofNumber():+"5" === 5,+"abc" === NaN.
== vs === (and ??)
Always use strict.
==coerces types before comparing;===requires type + value match.null == undefinedis true, but neither equals anything else with==.NaNis the only value not equal to itself — useNumber.isNaN()orObject.is().??returns the right side only fornull/undefined;||triggers on any falsy value.
8 falsy values (memorize!)
Everything else is truthy.
false,0,-0,0n,"",null,undefined,NaN— that’s the whole list.- Common truthy traps:
"0","false",[],{}," "(space),-1,Infinity. new Boolean(false)is truthy because it’s an object — never usenew Boolean/String/Number.!!valueis the idiomatic way to coerce to a real boolean.
The famous quirks
What interviewers love to ask.
[] == ![]→true.![]isfalse, then[]→""→0,false→0,0 == 0.null >= 0istruebutnull == 0isfalse(different comparison algorithms)."2" > "12"istrue(string lexicographic), but"2" > 12isfalse(numeric).0.1 + 0.2 !== 0.3— IEEE 754 floating-point precision.
Logical operators return operands
Not booleans.
||returns the first truthy value (or the last value if all are falsy).&&returns the first falsy value (or the last value if all are truthy).0 || 42 === 42;"hello" && "world" === "world".- Objects used as keys become the string
"[object Object]"— all object keys collide!
Comments
Comments are disabled in this environment. Set
PUBLIC_GISCUS_REPO,PUBLIC_GISCUS_REPO_ID, andPUBLIC_GISCUS_CATEGORY_IDto enable.