JavaScript Notes
Learn JavaScript variables from scratch: how to declare with var, let, const; naming rules; how values are stored in memory; scope basics; and common beginner mistakes.
Variables are the most fundamental concept in programming. Every piece of data your program works with — a user's name, their score, a list of items — lives in a variable. This guide will take you from zero understanding to confidently declaring, naming, and using variables in JavaScript.
Real World Analogy
Imagine you're organizing a classroom:
- Variable name = the label on a drawer (
studentName,totalMarks,isPresent) - Variable value = what's inside the drawer (
"Rahul",95,true) const= a drawer that's locked after filling — you can read it but not replace the contents with something elselet= a drawer that's unlocked — you can replace the contents anytimevar= an old-style drawer with confusing label placement rules — best avoided in modern work
How to Declare a Variable
Using const (Preferred — use by default)
const courseName = "JavaScript Master Course";
const year = 2026;
const isPublished = true;
console.log(courseName);
console.log(year);
console.log(isPublished);JavaScript Master Course 2026 true
Using let (For values that change)
let score = 0;
console.log("Initial score:", score);
score = 50; // reassignment
console.log("After first update:", score);
score += 25; // increment
console.log("Final score:", score);Initial score: 0 After first update: 50 Final score: 75
Using var (Legacy — avoid in new code)
var oldStyleVariable = "I'm from the old days";
console.log(oldStyleVariable);I'm from the old days
How Variables Are Stored in Memory
Understanding the memory model helps you avoid a whole category of bugs.
// Primitives: copy by VALUE
let a = 10;
let b = a; // b is a COPY of 10
b = 99;
console.log(a); // 10 — a is unchanged!
console.log(b); // 99
// Objects: copy by REFERENCE
const obj1 = { score: 100 };
const obj2 = obj1; // obj2 holds the SAME reference
obj2.score = 999;
console.log(obj1.score); // 999 — obj1 IS affected!10 99 999
Variable Naming Rules
JavaScript has strict rules about what names are valid for variables:
✅ Valid Naming Rules
Rule 1: Must start with a letter, underscore _, or dollar sign $
✅ name, _private, $element, user1
Rule 2: After the first character, can include letters, digits, _, $
✅ firstName, score2, _id, $price
Rule 3: Case-sensitive — 'name' and 'Name' are DIFFERENT variables
✅ let name = "lower";
let Name = "upper"; // completely different variable!
Rule 4: Cannot be a JavaScript keyword
❌ let, const, var, if, return, for, function...// ✅ Valid variable names
let firstName = "Rahul";
let _privateData = 42;
let $elementRef = document.body;
let totalAmount2024 = 9999;
// ❌ Invalid — would cause SyntaxError
// let 2fast = "too fast"; // starts with digit
// let my-name = "dash"; // contains hyphen
// let let = "keyword"; // reserved keyword
// let my name = "space"; // contains spaceVariable Naming Conventions (Best Practices)
These aren't enforced by JavaScript, but they are universal professional conventions:
// Variables — camelCase
const userName = "Priya";
let currentScore = 0;
let isLoggedIn = true;
// Constants — SCREAMING_SNAKE_CASE
const MAX_RETRIES = 3;
const API_BASE_URL = "https://api.example.com";
const TAX_RATE = 0.18;
// Classes — PascalCase
class StudentProfile {
constructor(name) {
this.name = name;
}
}
console.log(userName, currentScore, MAX_RETRIES);Priya 0 3
Declaring Multiple Variables
1 2 3 10 20 30 Priya Sharma
Variable Declaration vs Initialization vs Assignment
let score; ← Declaration only (score = undefined)
│
score = 100; ← Assignment (first time setting a value)
│
score = 200; ← Reassignment (changing the value)
const PI = 3.14; ← Declaration + Initialization in one line (required for const!)// Declaration without initialization
let studentName;
console.log(studentName); // undefined — declared but no value yet
// Initialize later
studentName = "Anjali";
console.log(studentName); // "Anjali"
// const MUST be initialized at declaration
const PASSING_MARKS = 40;
// const OTHER_CONST; // ❌ SyntaxError: Missing initializer in const declarationundefined Anjali
Scope — Where Variables Live
const globalVar = "I'm global — accessible everywhere";
function myFunction() {
const localVar = "I'm local to myFunction";
console.log(globalVar); // ✅ can access global from inside function
console.log(localVar); // ✅
if (true) {
const blockVar = "I'm block-scoped";
console.log(blockVar); // ✅
}
// console.log(blockVar); // ❌ ReferenceError — out of block scope
}
myFunction();
console.log(globalVar); // ✅
// console.log(localVar); // ❌ ReferenceError — out of function scopeI'm global — accessible everywhere I'm local to myFunction I'm block-scoped I'm global — accessible everywhere
Using Variables in Real Examples
Example 1: Shopping Cart Total
const itemPrice = 599;
const quantity = 3;
const discountPercent = 10;
const subtotal = itemPrice * quantity;
const discount = (subtotal * discountPercent) / 100;
const total = subtotal - discount;
console.log("Subtotal: ₹" + subtotal);
console.log("Discount: ₹" + discount);
console.log("Total: ₹" + total);Subtotal: ₹1797 Discount: ₹179.7 Total: ₹1617.3
Example 2: User Profile
const firstName = "Ananya";
const lastName = "Krishnan";
let age = 21;
let isVerified = false;
const fullName = firstName + " " + lastName;
age += 1; // birthday!
isVerified = true;
console.log(`Name: ${fullName}`);
console.log(`Age: ${age}`);
console.log(`Verified: ${isVerified}`);Name: Ananya Krishnan Age: 22 Verified: true
Common Mistakes
❌ Mistake 1: Using a variable before declaring it (with let/const)
// ❌ ReferenceError — using before declaration
console.log(username); // ReferenceError: Cannot access 'username' before initialization
let username = "Ravi";// ✅ CORRECT — declare before use
let username = "Ravi";
console.log(username); // "Ravi"❌ Mistake 2: Trying to reassign a const variable
const PI = 3.14159;
// PI = 3; // ❌ TypeError: Assignment to constant variable// ✅ Use let if you need to reassign
let radius = 5;
radius = 10; // fine!❌ Mistake 3: Confusing undefined with an error
let result;
console.log(result); // undefined — NOT an error!undefined
undefined is a valid value meaning "declared but not yet assigned." It's not a crash.
❌ Mistake 4: Using poor variable names
// ❌ BAD — meaningless names
let a = 29;
let b = true;
let c = "ananya.k@gmail.com";// ✅ GOOD — descriptive names
let userAge = 29;
let isSubscribed = true;
let userEmail = "ananya.k@gmail.com";Good variable names make code self-documenting. You shouldn't need comments to explain what each variable holds.
❌ Mistake 5: Modifying a const array/object thinking it will error
['HTML', 'CSS', 'JavaScript']
Key Takeaways
- A variable is a named container that holds a value in memory
- Use
constfor values that won't be reassigned,letfor values that will change - Variable names must start with a letter,
_, or$and are case-sensitive - Use camelCase for variable names (
totalPrice), SCREAMING_SNAKE_CASE for constants (MAX_SIZE) - Primitives are stored by value in the stack; objects by reference in the heap
- Declare variables before using them (with
let/const) to avoidReferenceError constprevents reassignment, not mutation — you can still modify object/array contents
Interview Questions & Answers
Q1. What is a variable in JavaScript and how do you declare one?
Answer: A variable is a named binding that stores a value in memory. In modern JavaScript, you declare variables using const (for values that won't be reassigned) or let (for values that will change). var is the older keyword — it works but has scope and hoisting quirks best avoided in new code.
const name = "Priya"; // immutable binding
let score = 0; // can be reassignedQ2. What are the rules for naming variables in JavaScript?
Answer: JavaScript identifiers must:
- Start with a letter (a-z, A-Z), underscore
_, or dollar sign$ - Contain only letters, digits (0-9),
_, or$after the first character - Not be a reserved keyword (
let,if,return, etc.) - Be case-sensitive (
nameandNameare different variables)
Q3. What is the difference between declaring and initializing a variable?
Answer: Declaration creates the variable: let score; — score exists but holds undefined. Initialization (or assignment) gives it a first value: score = 100;. You can do both in one line: let score = 100;. const requires initialization at declaration — const x; is a SyntaxError.
Q4. Why does changing a property on a const object not cause an error?
Answer: const only prevents reassignment of the variable itself — it doesn't prevent mutation of the value. For objects and arrays, the variable holds a memory address (reference). const locks that address, but the object at that address can still be freely modified (adding/removing/updating properties). To make an object truly immutable, use Object.freeze().
Q5. What is scope in JavaScript?
Answer: Scope determines the visibility and accessibility of a variable — where in your code that variable can be read or modified. Main scope types: global (accessible everywhere), function (accessible only inside the function), and block (accessible only inside the { } block — for let and const). Variables can access their own scope and any outer (parent) scopes.
Q6. What happens when you declare a variable without var, let, or const?
Answer: In sloppy mode, assigning to an undeclared variable (e.g., x = 5;) creates an implicit global variable — a dangerous practice that pollutes the global scope. In strict mode ("use strict"), it throws a ReferenceError: x is not defined. Always declare variables explicitly.
Q7. What is the difference between global and local variables?
Answer: A global variable is declared outside any function or block — it's accessible from anywhere in your code. A local variable (function-scoped with var, or block-scoped with let/const) is only accessible within the function or block where it was declared. Local variables are preferred to avoid naming conflicts and unintended modifications.
Q8. What does it mean when a variable's value is undefined?
Answer: undefined means the variable has been declared but not yet assigned a value. It's a valid JavaScript value (not an error). JavaScript automatically sets variables to undefined before you assign them: let x; → x is undefined. You should not manually assign undefined to a variable — use null to signal "intentionally empty".
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Variables Complete Guide – Declaration, Naming Rules & Memory Model for Beginners.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, basics, variables, javascript variables complete guide – declaration, naming rules & memory model for beginners
Related JavaScript Master Course Topics