Variables & Data Types

Published by Brayan K

A variable in JavaScript is a named container for storing a data value, declared with let, const, or var, so you can label, reuse, and update information in your program.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Decide which information can change

A packing desk needs a product name and a running quantity. Give those two jobs different declarations: the name is kept for this program, while the quantity is updated as another package arrives. A variable declaration associates a name with a value; later uses of that name read its current value.

const product = "Notebook";
let quantity = 2;
console.log(product);
console.log(quantity);
quantity = quantity + 3;
console.log(quantity);

// ✅ Expected output:
// Notebook
// 2
// 5

Read quantity = quantity + 3 from right to left: calculate with the old quantity, then assign the result to the name on the left. The equals sign performs assignment here. It is not a mathematical claim that the old quantity equals itself plus three.

Use const for a binding you do not intend to reassign and let when reassignment is part of the job. Both make that intention visible at the declaration. Names are case-sensitive and should describe their purpose: quantity is more useful than x when checking a packing error.

A calculated value is a snapshot

let quantity = 2;
const unitPrice = 4;
const firstTotal = quantity * unitPrice;
quantity = 5;
console.log(firstTotal);
console.log(quantity * unitPrice);

// ✅ Expected output:
// 8
// 20

The expression in the declaration is evaluated once when that statement executes. firstTotal stores the resulting number, not a live spreadsheet formula. Updating quantity therefore does not rewrite a previously computed result. Calculate again when you need a new total.

This is a useful debugging question: am I reading the current input, or a result computed from an earlier input? A stale result can be numerically valid and still describe the wrong state. A reusable calculation belongs in a function; Functions develops that step.

Reassignment and mutation are separate operations

const product = "Notebook";
console.log(product);
product = "Pen";

// ✅ Expected output:
// Notebook

// ✅ Expected error:
// TypeError: Assignment to constant variable.

Choose let if changing which value the name refers to is required. Do not remove the declaration keyword merely to get past the error; that can create a different problem with where the name is defined. A const declaration also needs an initial value.

const unitPrice;
console.log(unitPrice);

// ✅ Expected error:
// SyntaxError: Missing initializer in const declaration

However, const does not freeze an object. In this small record, the binding still refers to the same record while its quantity property changes. The dot selects that property. This distinction is why “const means the value can never change” is an unsafe rule.

const parcel = { quantity: 2 };
parcel.quantity = 5;
console.log(parcel.quantity);
console.log(JSON.stringify(parcel));

// ✅ Expected output:
// 5
// {"quantity":5}

This example establishes the boundary of const; Arrays and Objects owns creating and using records in detail. Pure Functions, Immutability & Side Effects owns broader strategies for avoiding mutations.

Values have types; a let binding can receive a different type

let quantity = 5;
console.log(typeof quantity);
quantity = "five";
console.log(typeof quantity);
console.log(typeof true);
console.log(typeof undefined);
console.log(typeof 12n);
console.log(typeof Symbol("parcel"));

// ✅ Expected output:
// number
// string
// boolean
// undefined
// bigint
// symbol

typeof reports a category as a string. It does not convert the value or validate that a value is sensible for your task. Reassigning a string to a name that previously held a number is allowed; it may still be a bug in a quantity calculation.

JavaScript’s primitive categories are string, number, bigint, boolean, undefined, symbol and null. Objects form a separate category and include arrays and functions. Ordinary integer and fractional number literals both have type number; the n suffix creates a bigint. You do not need symbols or bigints for this packing desk, but recognizing their categories prevents “all numbers are the same type” from becoming a rule.

console.log(typeof 4);
console.log(typeof 4.5);
console.log(typeof null);
console.log(typeof {});
console.log(typeof function count() {});

// ✅ Expected output:
// number
// number
// object
// object
// function

typeof null reports object, even though null is a primitive. Do not use that one test to prove a value is a usable object. Functions are objects with call behavior, and typeof gives them the more specific result function.

Unassigned is not the same as undeclared

let trackingCode;
console.log(trackingCode);
trackingCode = "PK-17";
console.log(trackingCode);

// ✅ Expected output:
// undefined
// PK-17

A let declaration without an initializer starts with undefined. That is an actual value you can inspect. By contrast, reading a name that has never been declared fails. Spelling matters even when a similar name already exists.

const trackingCode = "PK-17";
console.log(trackingcode);

// ✅ Expected error:
// ReferenceError: trackingcode is not defined

Keep declarations before their first use in these examples. var, let and const differ in scope and initialization behavior; Scope & var/let/const (TDZ) and Hoisting own those rules. Changing declaration keywords at random is not a reliable repair.

Check the input category before arithmetic

const quantityText = "5";
console.log(typeof quantityText);
console.log(quantityText + 2);
const quantity = Number(quantityText);
console.log(typeof quantity);
console.log(quantity + 2);

// ✅ Expected output:
// string
// 52
// number
// 7

Text from an input is not automatically a number because it contains digits. The plus operator can concatenate text. An explicit conversion makes the intended category visible, but conversion alone is not validation: invalid text may become NaN. Type Coercion (== vs ===) owns conversion rules and their failure cases.

Repair the packing counter

Choose a declaration for the fixed label, choose one for the changing count, and fill in the update. There is one literal hint for each blank.

___ label = "Box"; // 👉 replace ___ with const
___ count = 3; // 👉 replace ___ with let
count = ___; // 👉 replace ___ with count + 2
console.log(label);
console.log(count);

// ✅ Expected output:
// Box
// 5

Keep the original quote and calculate the revised order

Write a program for an order of two notebooks priced at six units each. Store the product and unit price with const, and the quantity with let. Save the first total, update the quantity to four, then print the product, the first total and the newly calculated total on separate lines. The first total must still describe the original order.

const product = "Notebook";
const unitPrice = 6;
let quantity = 2;
const originalTotal = quantity * unitPrice;
quantity = 4;
console.log(product);
console.log(originalTotal);
console.log(quantity * unitPrice);

// ✅ Expected output:
// Notebook
// 12
// 24

If both totals change together in your explanation, trace when each expression was evaluated. If the update throws a TypeError, inspect which binding was declared with const. Those diagnoses point to different lines and different repairs.

Reference: MDN on const bindings and grammar and types.

Practice quiz

What does this complete program print? let count = 2; count = count + 4; console.log(count);

  • 6
  • 2
  • 4
  • 24

Answer: 6. The right side uses the old value, then the binding receives the result.

What does this complete program print? let count = 2; const total = count * 3; count = 5; console.log(total);

  • 15
  • 6
  • 5
  • undefined

Answer: 6. The initializer calculated a number once. Updating count does not recalculate total.

What does this complete program print? const item = { count: 2 }; item.count = 4; console.log(item.count);

  • 2
  • TypeError: Assignment to constant variable.
  • 4
  • undefined

Answer: 4. The record is mutated; the const binding is not reassigned.

What does this complete program print? let label; console.log(label);

  • null
  • ReferenceError: label is not defined
  • ""
  • undefined

Answer: undefined. A declared let binding without an initializer holds undefined.

What does this complete program print? console.log(typeof null); console.log(typeof 7n);

  • object bigint
  • null number
  • object number
  • null bigint

Answer: object bigint. typeof null is the historical object result; the n suffix creates a bigint.

Which error ends this program? const price = 4; price = 6;

  • 6
  • TypeError: Assignment to constant variable.
  • 4
  • ReferenceError: price is not defined

Answer: TypeError: Assignment to constant variable.. Reassigning the const binding raises TypeError. The declaration itself was valid.

Which pair matches the intended use?

  • const for every changing counter, let for fixed labels
  • var for all new code because it prevents mistakes
  • const for a binding kept unchanged, let for planned reassignment
  • let freezes objects, const does not

Answer: const for a binding kept unchanged, let for planned reassignment. The declaration communicates whether the binding is intended to be reassigned; neither keyword freezes objects.

A value arrives as the text "8". What does typeof tell you?

  • Whether eight is a permitted quantity
  • Whether the text came from a trusted user
  • Whether conversion will always succeed
  • Its JavaScript type category, not whether it satisfies your business rules

Answer: Its JavaScript type category, not whether it satisfies your business rules. Type inspection helps diagnosis but is not input validation.

Continue this course

Related lessons