JavaScript Fundamentals : Type Conversions :

Implicit String Conversion Rules: alert() and similar functions convert everything to string : alert(123) // Shows “123”

String + anything = string (concatenation) :

"Hello" + 123 // "Hello123"
"Age: " + 25 // "Age: 25"
"" + true // "true"
"" + null // "null"

Numeric Conversion - Simple explanation:

What it does: Turns any value into a number

Implicit Numeric Conversion Rules:

1. Math operators (except +) convert everything to numbers

"6" / "2" // 3 (strings become numbers)
"10" - "5" // 5
"8" * "2" // 16
"20" % "3" // 2

2. Comparison operators convert to numbers

"10" > "5" // true (becomes 10 > 5)
"2" == 2 // true

Conversion Rules (what becomes what):

javascript

// Easy ones
Number(true) // 1
Number(false) // 0
Number(null) // 0
Number(undefined) // NaN
 
// Strings
Number("123") // 123
Number("   123   ") // 123 (trims whitespace)
Number("") // 0 (empty string = 0)
Number("   ") // 0 (only spaces = 0)
 
// Invalid strings
Number("123abc") // NaN (invalid)
Number("abc") // NaN (invalid)

Interview gotchas:

javascript

// These trip people up
Number("") // 0 (not NaN!)
Number("   ") // 0 (spaces become 0)
Number(null) // 0 (not NaN!)
Number(undefined) // NaN
 
// + is special - does concatenation if string present
"5" + 3 // "53" (string concatenation)
"5" - 3 // 2 (numeric conversion)

Bottom line: All math operators convert to numbers, except + which does string concatenation if any string is involved.

The Simple Rule:

FALSY (become false): Only 6 values

javascript

Boolean(false) // false
Boolean(0) // false  
Boolean("") // false (empty string)
Boolean(null) // false
Boolean(undefined) // false
Boolean(NaN) // false

TRUTHY (become true): Everything else

javascript

Boolean(1) // true
Boolean(-1) // true
Boolean("hello") // true
Boolean("0") // true (non-empty string!)
Boolean(" ") // true (space is non-empty!)
Boolean([]) // true (empty array is truthy!)
Boolean({}) // true (empty object is truthy!)

Interview gotchas:

javascript

// These trip people up
Boolean("0") // true (string "0" is truthy!)
Boolean(" ") // true (space is truthy!)
Boolean([]) // true (empty array is truthy!)
Boolean({}) // true (empty object is truthy!)

Bottom line: Only 6 values are falsy (false, 0, "", null, undefined, NaN). Everything else is truthy!