</>SyntaxPilot
Notes › JavaScript › Episode 2

JavaScript Variables (let, const, var) and Data Types

▶ Watch the videoTry the code in the compilerAll JavaScript notes

These are the notes for JavaScript episode 2. You will learn why programs need variables, how let, const and var differ, JavaScript's naming rules, the seven primitive data types with typeof, the difference between undefined and null, and the silent bugs that catch beginners: big numbers, decimals and dynamic typing. Every example runs as-is in the SyntaxPilot compiler (language: JavaScript, Node.js).

The problem: one value typed everywhere

Ramesh bhaiya runs a chai stall in Pune. One chai costs ₹15, and his program prints a bill per table:

// Ramesh bhaiya's bills
console.log("Table 1: 2 chai = " + 15 * 2);
console.log("Table 2: 1 chai = " + 15 * 1);
console.log("Table 3: 3 chai = " + 15 * 3);
Table 1: 2 chai = 30
Table 2: 1 chai = 15
Table 3: 3 chai = 45

Chai goes up to ₹20. We change tables 1 and 2, and forget table 3:

Table 1: 2 chai = 40
Table 2: 1 chai = 20
Table 3: 3 chai = 45

No error, wrong bill. One value (the price) lived in three places, and every change meant finding every copy.

The fix: store the value once, give it a name, and use the name everywhere. That named box is a variable.

Variables: a labelled jar

In the kitchen In JavaScript Name for it
Stick a label "price" on a jar let price declare: make a named box
Put 15 inside = 15 assign: put a value in
"Hand me the price jar" price * 2 use the name to get the value
Swap 15 for 20 price = 20 reassign: change it once
// Ramesh bhaiya's bills
let price = 20;
console.log("Table 1: 2 chai = " + price * 2);
console.log("Table 2: 1 chai = " + price * 1);
console.log("Table 3: 3 chai = " + price * 3);
Table 1: 2 chai = 40
Table 2: 1 chai = 20
Table 3: 3 chai = 60

Anatomy

Piece In let price = 15; Meaning
Keyword let "make a new variable" (a keyword is a word reserved by JavaScript)
Name price the label (an identifier)
= assignment put the value on the right into the box (not "is equal to")
Value 15 what's inside

Changing a variable: reassign, don't redeclare

let price = 15;
console.log("Morning: " + price);
price = 20;
console.log("Evening: " + price);
Morning: 15
Evening: 20

Use let once. Declaring the same name again is an error:

let price = 15;
let price = 20;
console.log(price);
SyntaxError: Identifier 'price' has already been declared

const: values that must never change

GST on chai is 5%. Two hundred lines later, a helper writes gst = 12 by mistake:

let gst = 5;
let bill = 100;
// ...200 lines later, a helper writes:
gst = 12;
console.log("Bill: " + (bill + bill * gst / 100));
Bill: 112

The customer should pay 105. With const (a constant: assigned once, never reassigned), the stray line fails loudly:

const gst = 5;
let bill = 100;
// ...200 lines later, a helper writes:
gst = 12;
console.log("Bill: " + (bill + bill * gst / 100));
main.js:4
gst = 12;
    ^

TypeError: Assignment to constant variable.

A const must get its value immediately:

const x;
SyntaxError: Missing initializer in const declaration
Jar Keyword Can the contents change?
Pencil label, open jar let yes, reassign any time
Sealed jar, permanent marker const no, assigned once

A loud error is better than a silent wrong answer.

var: the old way (avoid it)

Before 2015, var was the only keyword. let and const (2015, ES6) fixed its problems.

Declared twice, no error:

var price = 15;
// ...much later, by mistake:
var price = 20;
console.log(price);
20

Used before it exists, no error:

console.log(total);
var total = 100;
undefined

JavaScript prepares var variables before running the code (hoisting, covered in the scope episode), so you get undefined instead of an error. With let:

console.log(total);
let total = 100;
ReferenceError: Cannot access 'total' before initialization

Initialization means giving a variable its first value.

Which one to use

  1. const by default: most values never change.
  2. let when the value must change (a total, a counter).
  3. var: never in new code; just recognise it in old code.

Naming rules

Rule Bad Real error
Can't start with a digit let 2price = 15; SyntaxError: Invalid or unexpected token
No spaces let first name = "Aarav"; SyntaxError: Unexpected identifier 'name'
No keywords let class = 5; SyntaxError: Unexpected token 'class'
Case sensitive console.log(Price); (declared price) ReferenceError: Price is not defined

Names may use letters, digits (not first), _ and $. Use camelCase for multi-word names: firstName, chaiPrice, isOpen. Fixed settings are often written in capitals: const GST = 5;.

let firstName = "Aarav";
let chaiPrice = 15;
let isOpen = true;
console.log(firstName, chaiPrice, isOpen);
Aarav 15 true

Data types and typeof

A data type is the kind of value. typeof tells you a value's type.

Kitchen Type Values
Weighing scale number 15, 15.5, -3 (whole numbers and decimals)
A written note string "masala chai"
A light switch boolean true, false
console.log(typeof 15);
console.log(typeof 15.5);
console.log(typeof "chai");
console.log(typeof true);
number
number
string
boolean

undefined vs null

On a train Type Meaning
Seat booked, no passenger name yet undefined declared, never given a value
Meal: "None", ticked on purpose null empty, on purpose
let seat;
console.log(seat, typeof seat);
let preference = null;
console.log(preference, typeof preference);
undefined undefined
null object

typeof null is "object": a bug from JavaScript's first version (1995), kept so old websites don't break. null is still its own type.

BigInt: huge whole numbers

A number holds whole numbers exactly only up to 9007199254740991 (Number.MAX_SAFE_INTEGER). Beyond that it rounds, silently:

console.log(9007199254740993);
console.log(9007199254740993n);
console.log(typeof 10n);
9007199254740992
9007199254740993n
bigint

Add n to make a BigInt: exact whole numbers of any size.

The seven primitive types

number, string, boolean, undefined, null, bigint, symbol (unique labels; rarely needed early). Everything else (arrays, objects, functions) is an object, covered later.

A decimal surprise

console.log(0.1 + 0.2);
console.log((10 + 20) / 100);
0.30000000000000004
0.3

Computers store decimals in binary, and 0.1 can't be stored exactly (true in almost every language). For money, count in whole paise and divide by 100 only when printing.

Dynamic typing

let box = 5;
console.log(box, typeof box);
box = "five";
console.log(box, typeof box);
5 number
five string

The type belongs to the value, not the variable (dynamic typing). Flexible, but nothing stops a wrong kind of value. TypeScript (later in the course) adds that check.

Common mistakes (and the real error messages)

You wrote What Node.js says Why Fix
const gst = 5; gst = 12; TypeError: Assignment to constant variable. const can't be reassigned let if it must change
let price = 15; let price = 20; SyntaxError: Identifier 'price' has already been declared let once, then assign price = 20;
console.log(total); let total = 100; ReferenceError: Cannot access 'total' before initialization used before its line declare first
const x; SyntaxError: Missing initializer in const declaration const needs a value const x = 0;
let 2price = 15; SyntaxError: Invalid or unexpected token digit first price2
var price twice (no error) silently overwritten var allows duplicates use let/const
9007199254740993 (no error) prints …992 beyond safe integers 9007199254740993n

Mini project: a chai stall bill

// Mini project: a chai stall bill
const CHAI = 15;
const SAMOSA = 20;
const GST = 5;
let customer = "Neha";
let chais = 2;
let samosas = 3;
let subtotal = CHAI * chais + SAMOSA * samosas;
let total = subtotal + subtotal * GST / 100;
console.log("Customer: " + customer);
console.log("Subtotal: " + subtotal);
console.log("Total with GST: " + total);
Customer: Neha
Subtotal: 90
Total with GST: 94.5

Practice

  1. Store your name, age, city and whether you're a student in four variables (choose const or let), and print them on one line.
  2. Write a bill for your favourite snack shop with const prices and a const tax rate.
  3. Predict the output: let a; console.log(a); a = null; console.log(a, typeof a);
  4. Why does const PI = 3.14; PI = 3; fail, and what's the exact error?
Solutions and hints
  1. const name = "Aarav"; let age = 21; const city = "Pune"; let isStudent = true; console.log(name, age, city, isStudent);
  2. const SAMOSA = 20; const GST = 5; let qty = 4; let sub = SAMOSA * qty; console.log(sub + sub * GST / 100); prints 84.
  3. undefined, then null object.
  4. Reassigning a const: TypeError: Assignment to constant variable.

Quick quiz

What does this print?

let seat;
console.log(typeof seat, typeof null);
Answer

B. seat was declared but never assigned, so it's undefined. typeof null is "object" (the 1995 bug).

Interview questions

Glossary

Term Meaning Example
Variable a named box that holds a value let price = 15;
Declare create a variable let price
Assign put a value into a variable with = price = 20
Reassign give an existing variable a new value price = 20;
Initialization a variable's first value let x = 0;
Keyword a word reserved by JavaScript let, const, class, if
Identifier the name you give a variable or function chaiPrice
let a variable that can be reassigned let total = 0;
const a variable that can't be reassigned const GST = 5;
var the pre-2015 keyword; allows duplicates and early use var x = 1;
Hoisting JS preparing declarations before running code var gives undefined early
camelCase multi-word names with capitals in the middle firstName
Data type the kind of value number, string, boolean
typeof an operator that returns a value's type as a string typeof 15 → "number"
number whole numbers and decimals 15, 15.5
string text in quotes "chai"
boolean true or false isOpen = true
undefined declared but never assigned let seat;
null empty on purpose let preference = null;
BigInt exact whole numbers of any size 9007199254740993n
symbol a unique label value (advanced) Symbol("id")
Primitive type one of the 7 basic types number, string, …
Dynamic typing a variable can hold any type over time box = 5; box = "five";

Summary

Next episode: operators and type coercion. A form says the age is 18, and 18 + 1 comes out as 181.

← Episode 1What Is JavaScript? Node.js, Your First Program and console.logEpisode 3 →JavaScript Operators, == vs ===, Type Coercion and ??