Module 4 : Javascript Variables and Constants.
1. Introduction to Variables and Constants
What is a Variable?
A variable is a container used to store data values in programming. In JavaScript, variables can hold different data types (strings, numbers, objects, arrays, etc.) and can be changed (mutable).
javascript
code
let name = "John"; name = "Doe"; // value changed
What is a Constant?
A constant is a variable whose value cannot be changed after it is set. Constants are immutable.
javascript
code
const PI = 3.14159; // PI = 3.14; // Error: Assignment to constant variable
2. Declaring Variables in JavaScript
JavaScript has three keywords to declare variables:
Keyword
Scope
Reassignable
Hoisting
Use Case
var
Function-scoped
Yes
Yes (initializes as undefined)
Legacy code
let
Block-scoped
Yes
No
Modern variable declaration
const
Block-scoped
No
No
Declare constants
2.1 var – Function Scoped
javascript
code
function testVar() { var x = 1; if (true) { var x = 2; console.log(x); // 2 } console.log(x); // 2 } testVar();
✅ var does not have block scope. Avoid using var in modern JS.
2.2 let – Block Scoped
javascript
code
function testLet() { let x = 1; if (true) { let x = 2; console.log(x); // 2 } console.log(x); // 1 } testLet();
✅ Use let when you need a mutable variable with block scope.
2.3 const – Constant Declaration
javascript
code
const name = "Alice"; // name = "Bob"; // Error
✅ Use const by default unless you plan to reassign the variable.
3. Scope in JavaScript
Global Scope
Declared outside any block or function. Accessible from anywhere.
Function Scope
Accessible only within the function it’s declared in. var is function scoped.
Block Scope
Accessible only within {} block. Applies to let and const.
4. Hoisting in JavaScript
Variables declared with var are hoisted but initialized as undefined.
javascript
code
console.log(a); // undefined var a = 10;
Variables declared with let and const are hoisted but not initialized.
javascript
code
console.log(b); // ReferenceError let b = 10;
5. Variable Naming Rules and Conventions
Must begin with a letter, underscore _, or dollar sign $.
Cannot use reserved JavaScript keywords (let, class, etc.)
Use camelCase for naming: userAge, productPrice
Constants are often written in UPPER_SNAKE_CASE: MAX_LIMIT
6. Examples
Example 1: Using let and const
javascript
code
function calculateArea(radius) { const PI = 3.14; let area = PI * radius * radius; return area; } console.log(calculateArea(5)); // 78.5
Example 2: Mutable and Immutable Variables
javascript
code
let score = 10; score = 20; // OK const game = "chess"; // game = "football"; // Error
Example 3: Array and Object with const
javascript
code
const user = { name: "Alice", age: 25 }; user.age = 26; // Allowed (object is mutable)
const does not make objects immutable — just prevents reassignment of the variable name.
7. Practices
Use const by default for all variables.
Use let only if you plan to reassign the variable.
Avoid var unless maintaining legacy code.
Keep variable scope as small as possible.
Use meaningful variable names.
8. Exercises with Explanations
Exercise 1: Identify Output
javascript
code
var a = 10; function test() { var a = 20; console.log(a); } test(); console.log(a);
Expected Output:
code
20
10
Explanation: var inside the function is local to the function.
Exercise 2: Predict Error
javascript
code
const x = 10; x = 20;
Expected Result:
Error: Assignment to constant variable.
Exercise 3: Scope Check
javascript
code
let x = 5; if (true) { let x = 10; console.log(x); // ? } console.log(x); // ?
Expected Output:
code
10
5
Explanation: Each x exists in a different block scope.
Exercise 4: Fix the Error
javascript
code
function getData() { if (true) { var value = "Success"; } return value; } console.log(getData());
Fix using let:
javascript
code
function getData() { let value; if (true) { value = "Success"; } return value; }
9. Advanced (Optional)
Temporal Dead Zone (TDZ)
Accessing let or const before they are declared throws a ReferenceError.
javascript
code
console.log(a); // ReferenceError let a = 5;
between entering the block and variable declaration is called the Temporal Dead Zone.
10. Summary
Feature
var
let
const
Scope
Function
Block
Block
Hoisting
Yes (with undefined)
Yes (no init)
Yes (no init)
Reassignable
Yes
Yes
No
Use Case
Legacy
Mutable vars
Immutable refs
11. Start with a visual analogy (e.g., containers for storing values).
Live-code examples using browser console or JSFiddle.
Use interactive quizzes (e.g., “What is the output?”).
Compare and contrast var, let, and const with color-coded examples.
Use debugging tools to show hoisting and scope behavior.
Include code challenges and review solutions together.
Use analogies like:
const is like a sealed envelope (can't change recipient).
let is like a whiteboard (can erase and rewrite).
var is like an old floppy disk (works but outdated).
12. Research and Industry Insight
Modern JavaScript (ES6+) recommends using let and const for better code readability, maintainability, and scope control.
Frameworks like React, Vue, Angular encourage const for immutability (important for state management).
Linting tools like ESLint flag inappropriate use of var.
Code style guides (e.g., Airbnb's JavaScript Style Guide) discourage var entirely.
No comments:
Post a Comment