Topic 02 / 15

Variables & Types — let, const, and Coercion

~9 min read  //  JavaScript Series  //  Coding India

let, const — and Why Not var

const channel = "Coding India";   // can't be reassigned — your default
let views = 1000;                 // can be reassigned
views += 500;

channel = "Other";                // TypeError

Rule: use const by default, let when you must reassign, var never. var is function-scoped and hoisted in confusing ways; let/const are block-scoped like every other modern language.

Note: const means the binding is fixed, not the value — a const array can still be mutated:

const tags = ["js"];
tags.push("css");        // fine — same array, new contents
tags = [];               // TypeError — can't rebind

The Types

typeof "hello"       // 'string'
typeof 42            // 'number'  — one number type, always float64
typeof 10n           // 'bigint'
typeof true          // 'boolean'
typeof undefined     // 'undefined' — declared but no value
typeof Symbol()      // 'symbol'
typeof null          // 'object'  — a 25-year-old bug, memorise it
typeof {}            // 'object'
typeof []            // 'object'  — arrays are objects too
typeof console.log   // 'function'

undefined means “never assigned”; null means “intentionally empty”. You assign null; the language gives you undefined.

Numbers

7 / 2          // 3.5 — no integer division
7 % 2          // 1
2 ** 10        // 1024
0.1 + 0.2      // 0.30000000000000004 — IEEE floats, same as Python
Number("42")   // 42
Number("abc")  // NaN — "not a number", and NaN !== NaN
Number.isNaN(Number("abc"))   // true — the safe check

== vs === — Always Triple

== coerces types before comparing, with rules nobody fully remembers. === compares value and type:

1 == "1"        // true  — string coerced to number
0 == false      // true
null == undefined  // true

1 === "1"       // false
0 === false     // false

Always use === and !==. The single acceptable == is x == null, which checks null-or-undefined in one go.

Truthiness

Falsy values: false, 0, -0, "", null, undefined, NaN. Everything else is truthy — including "0", [] and {} (unlike Python!):

if ([]) console.log("runs!");      // empty array is truthy
if ([].length) console.log("no");  // check length instead

Template Literals

const name = "Ravi", score = 82;
console.log(`${name} scored ${score}/100`);   // backticks + ${}
const html = `
  <li>${name}</li>
`;                                            // multiline works too