Variables and Data Types
TL;DR — Quick Summary
- Use
constby default — it prevents accidental reassignment and signals intent. - JavaScript has 7 primitive types: number, string, boolean, null, undefined, bigint, symbol.
- Always use
===(strict equality) —==does type coercion and causes subtle bugs. typeof nullreturns'object'— a famous JavaScript quirk, not a feature.
Lesson Overview
Variables are named containers that store data values. Think of a variable as a labeled box where you keep information. Every variable has a name (identifier), a value, and a type that tells the computer how to interpret the data.
For example, in a social media app: userName would be a string (text), userAge would be a number, and isVerified would be a boolean (true/false). Choosing the right type for your data matters — it affects memory usage, the operations you can perform, and the bugs you'll encounter.
In JavaScript specifically, variables are declared with three keywords: const (can't be reassigned), let (can be reassigned), and var (legacy — avoid in modern code).
Conceptual Deep Dive
JavaScript has seven primitive types and one complex type:
number— integers and decimals:42,3.14,-7,Infinity,NaNstring— text:'hello',"world",`template ${literal}`boolean—trueorfalsenull— intentional absence of a value (you set it)undefined— variable declared but not assigned (automatic)bigint— integers larger than 2⁵³:9007199254740991nsymbol— unique identifiers, used in advanced patternsobject— the complex type: arrays, objects, functions, null (quirk)
The typeof operator tells you a value's type at runtime. Key quirk: typeof null returns 'object' — a historical bug in JavaScript that can never be fixed without breaking the web.
Implementation Lab
// const: can't reassign — use by default
const productName = 'Laptop Pro'Pro';
const price = 999.99;
const inStock = true;
const noValue = null;
// let: can reassign — use when value changes
let quantity = 1;
let cartTotal = 0;
quantity = 3; // ✅ let can be reassigned
cartTotal = price * quantity; // 2999.97
// productName = 'Phone'; // ❌ TypeError: Assignment to constant variableTypeError: Assignment to constant variable
// typeof: check the type of any value
console.log(typeof productName); // 'string'
console.log(typeof price); // 'number'
console.log(typeof inStock); // 'boolean'
console.log(typeof noValue); // 'object' ← famous JS quirkJS quirk
console.log(typeof undefined); // 'undefined'
console.log(typeof 42n); // 'bigint'
// Template literals: embed variables in strings
const receipt = `${quantity}x ${productName} = $${cartTotal.toFixed(2)}`}x ${productName} = $${cartTotal.toFixed(2)}`;
console.log(receipt); // '3x Laptop Pro = $2999.97'Pro = $2999.97'// JavaScript automatically converts types — called type coercion
// This causes unexpected results if you don't know the rulesif you don't know the rules
// String + Number = String concatenationNumber = String concatenation
console.log('5' + 3); // '53' (not 8!)(not 8!)
console.log('5' - 3); // 2 (subtraction converts to number)(subtraction converts to number)
console.log('5' * '2'); // 10 (multiplication converts both)(multiplication converts both)
// Loose equality (==) coerces types — avoid this(==) coerces types — avoid this
console.log(5 == '5'); // true (coerces '5' to 5)(coerces '5' to 5)
console.log(0 == false); // true (coerces false to 0)(coerces false to 0)
console.log(null == undefined); // true
// Strict equality (===) checks type AND value — always use this(===) checks type AND value — always use this
console.log(5 === '5'); // false (different types)(different types)
console.log(0 === false); // false
// Explicit conversion — be intentional
console.log(Number('42')); // 42
console.log(String(99)); // '99'
console.log(Boolean(0)); // false
console.log(Boolean('hello')); // true
console.log(parseInt('42px')); // 42 (stops at non-numeric)(stops at non-numeric)Pro Tips — Senior Dev Insights
Declare variables at the top of their scope and initialise them immediately — this prevents accidental undefined reads and makes code easier to follow.
Use Number.isFinite() and Number.isNaN() instead of the global versions — they don't coerce types first, making them more reliable.
Template literals (`Hello ${name}`) are almost always better than string concatenation — they're more readable and support multi-line strings.
Common Developer Pitfalls
var instead of const/let — var is function-scoped, hoisted, and allows redeclaration, which causes hard-to-find bugs.null and undefined — null is intentional absence you set; undefined is what JavaScript assigns when no value exists.== instead of === — loose equality coerces types silently: 0 == false is true, which is almost never what you want.const makes objects immutable — const prevents reassigning the variable, but the object's properties can still be mutated.Interview Mastery
const and let are block-scoped (limited to the { } block they're declared in). var is function-scoped and hoisted to the top of its function — this causes surprising behaviour. const prevents reassignment of the binding (but not mutation of objects/arrays). let allows reassignment. Best practice: use const by default for everything, let when you genuinely need to reassign (loop counters, accumulators), and never use var in modern code.
undefined is JavaScript's default — a variable declared but not assigned is undefined automatically (let x; → x is undefined). null is an intentional assignment meaning 'no value' — you must set it explicitly (let x = null;). undefined comes from JavaScript; null comes from you. Key quirk: typeof null returns 'object' due to a legacy bug. To check for null use strict equality: x === null. For both: x == null (loose) catches both null and undefined.
Type coercion is JavaScript's automatic conversion of one type to another during operations. Classic surprise: '5' + 3 returns '53' (string concatenation) but '5' - 3 returns 2 (numeric subtraction). This inconsistency comes from + being overloaded for both addition and concatenation. Other surprises: [] + [] is '' (empty string), [] + {} is '[object Object]'. The fix: use === for comparisons, use explicit conversion functions (Number(), String()), and understand that + with any string triggers concatenation.
JavaScript is dynamically typed — variables have no fixed type, values do. Type coercion happens automatically in comparisons and operations. Implicit coercion: '5' * 2 → 10. Explicit coercion: Number('5') → 5. Falsy values (0, '', null, undefined, false, NaN) coerce to false in boolean context; everything else is truthy. Always use === to avoid coercion bugs, and use explicit conversion when you need to change types intentionally.
Hands-on Lab Exercises
typeof.Build a shopping cart: store itemPrice, quantity, taxRate as consts. Calculate subtotal, tax, and total using let. Format the output with template literals.
'10' + 5, '10' - 5, true + 1, null + 1 — then run the code and compare.const variable, observe the TypeError, then do the same with a const object's property — notice the difference.Real-World Practice Scenarios
Deepen Your Knowledge
Variables and Data Types
TL;DR — Quick Summary
- Use
constby default — it prevents accidental reassignment and signals intent. - JavaScript has 7 primitive types: number, string, boolean, null, undefined, bigint, symbol.
- Always use
===(strict equality) —==does type coercion and causes subtle bugs. typeof nullreturns'object'— a famous JavaScript quirk, not a feature.
Overview
Variables are named containers that store data values. Think of a variable as a labeled box where you keep information. Every variable has a name (identifier), a value, and a type that tells the computer how to interpret the data.
For example, in a social media app: userName would be a string (text), userAge would be a number, and isVerified would be a boolean (true/false). Choosing the right type for your data matters — it affects memory usage, the operations you can perform, and the bugs you'll encounter.
In JavaScript specifically, variables are declared with three keywords: const (can't be reassigned), let (can be reassigned), and var (legacy — avoid in modern code).
Deep Dive Analysis
<p>JavaScript has <strong>seven primitive types</strong> and one complex type:</p><ul><li><code>number</code> — integers and decimals: <code>42</code>, <code>3.14</code>, <code>-7</code>, <code>Infinity</code>, <code>NaN</code></li><li><code>string</code> — text: <code>'hello'</code>, <code>"world"</code>, <code>`template ${literal}`</code></li><li><code>boolean</code> — <code>true</code> or <code>false</code></li><li><code>null</code> — intentional absence of a value (you set it)</li><li><code>undefined</code> — variable declared but not assigned (automatic)</li><li><code>bigint</code> — integers larger than 2⁵³: <code>9007199254740991n</code></li><li><code>symbol</code> — unique identifiers, used in advanced patterns</li><li><code>object</code> — the complex type: arrays, objects, functions, null (quirk)</li></ul><p>The <code>typeof</code> operator tells you a value's type at runtime. Key quirk: <code>typeof null</code> returns <code>'object'</code> — a historical bug in JavaScript that can never be fixed without breaking the web.</p>
Implementation Reference
// const: can't reassign — use by default
const productName = 'Laptop Pro';
const price = 999.99;
const inStock = true;
const noValue = null;
// let: can reassign — use when value changes
let quantity = 1;
let cartTotal = 0;
quantity = 3; // ✅ let can be reassigned
cartTotal = price * quantity; // 2999.97
// productName = 'Phone'; // ❌ TypeError: Assignment to constant variable
// typeof: check the type of any value
console.log(typeof productName); // 'string'
console.log(typeof price); // 'number'
console.log(typeof inStock); // 'boolean'
console.log(typeof noValue); // 'object' ← famous JS quirk
console.log(typeof undefined); // 'undefined'
console.log(typeof 42n); // 'bigint'
// Template literals: embed variables in strings
const receipt = `${quantity}x ${productName} = $${cartTotal.toFixed(2)}`;
console.log(receipt); // '3x Laptop Pro = $2999.97'// JavaScript automatically converts types — called type coercion
// This causes unexpected results if you don't know the rules
// String + Number = String concatenation
console.log('5' + 3); // '53' (not 8!)
console.log('5' - 3); // 2 (subtraction converts to number)
console.log('5' * '2'); // 10 (multiplication converts both)
// Loose equality (==) coerces types — avoid this
console.log(5 == '5'); // true (coerces '5' to 5)
console.log(0 == false); // true (coerces false to 0)
console.log(null == undefined); // true
// Strict equality (===) checks type AND value — always use this
console.log(5 === '5'); // false (different types)
console.log(0 === false); // false
// Explicit conversion — be intentional
console.log(Number('42')); // 42
console.log(String(99)); // '99'
console.log(Boolean(0)); // false
console.log(Boolean('hello')); // true
console.log(parseInt('42px')); // 42 (stops at non-numeric)Common Pitfalls
- •Using <code>var</code> instead of <code>const</code>/<code>let</code> — <code>var</code> is function-scoped, hoisted, and allows redeclaration, which causes hard-to-find bugs.
- •Confusing <code>null</code> and <code>undefined</code> — <code>null</code> is intentional absence you set; <code>undefined</code> is what JavaScript assigns when no value exists.
- •Using <code>==</code> instead of <code>===</code> — loose equality coerces types silently: <code>0 == false</code> is <code>true</code>, which is almost never what you want.
- •Assuming <code>const</code> makes objects immutable — <code>const</code> prevents reassigning the variable, but the object's properties can still be mutated.
Hands-on Practice
- ✓Declare variables for a user profile — name (string), age (number), email (string), isVerified (boolean), lastLogin (null) — log each with its <code>typeof</code>.
- ✓Build a shopping cart: store itemPrice, quantity, taxRate as consts. Calculate subtotal, tax, and total using let. Format the output with template literals.
- ✓Experiment with type coercion: predict the output of <code>'10' + 5</code>, <code>'10' - 5</code>, <code>true + 1</code>, <code>null + 1</code> — then run the code and compare.
- ✓Try to reassign a <code>const</code> variable, observe the TypeError, then do the same with a const object's property — notice the difference.
Expert Pro Tips
Interview Preparation
Q: What's the difference between const, let, and var? When should you use each?
Master Answer:
const and let are block-scoped (limited to the { } block they're declared in). var is function-scoped and hoisted to the top of its function — this causes surprising behaviour. const prevents reassignment of the binding (but not mutation of objects/arrays). let allows reassignment. Best practice: use const by default for everything, let when you genuinely need to reassign (loop counters, accumulators), and never use var in modern code.
Q: Explain the difference between null and undefined with examples.
Master Answer:
undefined is JavaScript's default — a variable declared but not assigned is undefined automatically (let x; → x is undefined). null is an intentional assignment meaning 'no value' — you must set it explicitly (let x = null;). undefined comes from JavaScript; null comes from you. Key quirk: typeof null returns 'object' due to a legacy bug. To check for null use strict equality: x === null. For both: x == null (loose) catches both null and undefined.
Q: What happens with type coercion? Give an example of a surprising result.
Master Answer:
Type coercion is JavaScript's automatic conversion of one type to another during operations. Classic surprise: '5' + 3 returns '53' (string concatenation) but '5' - 3 returns 2 (numeric subtraction). This inconsistency comes from + being overloaded for both addition and concatenation. Other surprises: [] + [] is '' (empty string), [] + {} is '[object Object]'. The fix: use === for comparisons, use explicit conversion functions (Number(), String()), and understand that + with any string triggers concatenation.
Q: How does JavaScript handle type coercion in variables?
Master Answer:
JavaScript is dynamically typed — variables have no fixed type, values do. Type coercion happens automatically in comparisons and operations. Implicit coercion: '5' * 2 → 10. Explicit coercion: Number('5') → 5. Falsy values (0, '', null, undefined, false, NaN) coerce to false in boolean context; everything else is truthy. Always use === to avoid coercion bugs, and use explicit conversion when you need to change types intentionally.
Simulated Scenarios
Extended Reading
MDN: Variables
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Variables
MDN: JavaScript data types
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
JavaScript.info: Variables
https://javascript.info/variables
© 2026 DevHub Engineering • All Proprietary Rights Reserved
Generated on March 7, 2026 • Ver: 4.0.2
Document Class: Master Education
Confidential Information • Licensed to User