JSJavaScript · Lesson 2 of 14

Variables & Types

JavaScript has three ways to declare variables: var, let, and const. One is old and troublesome, one is modern, and one is modern and immutable. Spot the pattern.

Use const for values that don't change. Use let for values that do. Avoid var — it has confusing scoping rules and function-level scope instead of block scope. Pretend it doesn't exist.

JavaScript
// const — cannot be reassigned
const PI = 3.14159;
const name = "Alice";

// let — can be reassigned
let age = 30;
age = 31;  // fine

// JavaScript's primitive types
const integer = 42;
const float = 3.14;           // both are 'number' type
const text = "hello";
const template = `Hello, ${name}`;
const flag = true;
const nothing = null;         // intentional absence of value
const notDefined = undefined; // uninitialized

// Check types with typeof
console.log(typeof 42);          // "number"
console.log(typeof "hello");     // "string"
console.log(typeof true);        // "boolean"
console.log(typeof undefined);   // "undefined"
console.log(typeof null);        // "object"  ← famous bug, kept for compatibility

JavaScript is weakly typed, which means it will automatically convert types when comparing values. This is the source of many surprises. Use === (triple equals) for comparison — it checks type AND value.

JavaScript
// == does type coercion (avoid)
console.log(1 == "1");    // true  ← surprising
console.log(0 == false);  // true  ← also surprising

// === checks type AND value (use this)
console.log(1 === "1");   // false ← correct
console.log(0 === false); // false ← correct

// Type conversion
const num = Number("42");     // 42
const str = String(42);       // "42"
const bool = Boolean(0);      // false
const bool2 = Boolean("hi");  // true

// Falsy values in JS: false, 0, "", null, undefined, NaN
// Everything else is truthy
if ("") console.log("won't print");  // empty string is falsy
if ("a") console.log("will print");  // non-empty string is truthy
⚠ Warning
NaN (Not a Number) is the result of invalid math operations like Number("cat") or 0/0. Weirdly, typeof NaN is "number". And NaN !== NaN. Use Number.isNaN() to check for it.