Programming Fundamentals

Variables and Data Types

3 min read
Focus: PROGRAMMING-FUNDAMENTALS

TL;DR — Quick Summary

  • Use const by 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 null returns '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, NaN
  • string — text: 'hello', "world", `template ${literal}`
  • booleantrue or false
  • null — intentional absence of a value (you set it)
  • undefined — variable declared but not assigned (automatic)
  • bigint — integers larger than 2⁵³: 9007199254740991n
  • symbol — unique identifiers, used in advanced patterns
  • object — 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

Variable Declaration and Data Types
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 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'
Type Coercion — When JavaScript Surprises You
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 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

1

Declare variables at the top of their scope and initialise them immediately — this prevents accidental undefined reads and makes code easier to follow.

2

Use Number.isFinite() and Number.isNaN() instead of the global versions — they don't coerce types first, making them more reliable.

3

Template literals (`Hello ${name}`) are almost always better than string concatenation — they're more readable and support multi-line strings.

Common Developer Pitfalls

!
Using var instead of const/letvar is function-scoped, hoisted, and allows redeclaration, which causes hard-to-find bugs.
!
Confusing null and undefinednull is intentional absence you set; undefined is what JavaScript assigns when no value exists.
!
Using == instead of === — loose equality coerces types silently: 0 == false is true, which is almost never what you want.
!
Assuming 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

1
Declare variables for a user profile — name (string), age (number), email (string), isVerified (boolean), lastLogin (null) — log each with its typeof.
2

Build a shopping cart: store itemPrice, quantity, taxRate as consts. Calculate subtotal, tax, and total using let. Format the output with template literals.

3
Experiment with type coercion: predict the output of '10' + 5, '10' - 5, true + 1, null + 1 — then run the code and compare.
4
Try to reassign a const variable, observe the TypeError, then do the same with a const object's property — notice the difference.

Real-World Practice Scenarios

Login system: Store username (string), password (string), rememberMe (boolean), loginAttempts (number), isLocked (boolean). Calculate whether the account should lock after 5 attempts.
Product listing: Store title, price, rating, inStock, categoryId. Calculate discounted price and build a display string with template literals.
Game state: Store playerName, score, level, isGameOver, health. Update score and level with let, keep player name with const.
Weather dashboard: Store temperature (number), humidity (number), condition (string), isRaining (boolean). Display a formatted weather summary.

Deepen Your Knowledge