Chapter 2 of 12
2.1 Syntax, Variables, & Scopes
JavaScript has three variable declaration keywords: var, let, and const. Understanding their differences requires mastering Scope, Hoisting, and the Temporal Dead Zone (TDZ).
Variable Scopes & TDZjavascript
// 1. Hoisting & TDZ Behavior
console.log(varVar); // undefined (Hoisted & initialized to undefined)
var varVar = 'I am var';
// console.log(letVar); // ReferenceError: Cannot access 'letVar' before initialization
let letVar = 'I am let'; // Un-hoisted declaration phase leaves it in TDZ until this line
// 2. Block Scope vs Function Scope
if (true) {
var blockVar = 'Accessible outside block';
let blockLet = 'Scoped strictly to block';
}
console.log(blockVar); // 'Accessible outside block'
// console.log(blockLet); // ReferenceError: blockLet is not definedTemporal Dead Zone (TDZ)
The TDZ is the period between entering scope and the actual execution of let/const declaration. Accessing a variable in its TDZ throws a ReferenceError.
2.2 Primitive Data Types & Type Conversion
JavaScript features 7 primitive data types (string, number, boolean, null, undefined, symbol, bigint). Primitive values are immutable and passed by value.
Coercion & Type Inspectionjavascript
// Implicit Type Coercion
console.log('5' + 3); // '53' (String concatenation takes precedence with +)
console.log('5' - 3); // 2 (Numeric subtraction forced)
console.log(true + true); // 2 (Booleans converted to 1)
// Robust Type Checking
function getType(val) {
return Object.prototype.toString.call(val).slice(8, -1);
}
console.log(getType([])); // 'Array'
console.log(getType(null)); // 'Null'
console.log(getType(new Date()));// 'Date'2.3 Operators & Modern Expressions
Modern JS provides advanced operators for clean, safe evaluation without verbose conditional checks.
Modern Operatorsjavascript
const user = { profile: { name: 'Alice' } };
// Optional Chaining (?.)
const city = user?.location?.city; // undefined (No TypeError thrown)
// Nullish Coalescing (??) vs Logical OR (||)
const count = 0;
console.log(count || 10); // 10 (Falsy check treats 0 as falsy)
console.log(count ?? 10); // 0 (Nullish check ONLY treats null/undefined as missing!)
// Strict Equality vs Object.is
console.log(NaN === NaN); // false
console.log(Object.is(NaN, NaN));// true
console.log(0 === -0); // true
console.log(Object.is(0, -0)); // false