Variables and Data Types (let, const, var)
Variables are storage containers that hold information in memory for your program to calculate, update, and display.
What is it?
In modern JavaScript, variables are declared using `let` and `const`. Older code used `var`. JavaScript is dynamically typed, meaning variables can hold different data types without explicit type declarations.
Why is it used?
Used to store user inputs, API response data, counters, cart totals, and application state.
Detailed Explanation
Declaring Variables:
• `const`: Block-scoped. Cannot be reassigned. Use `const` by default for all variables unless you know their value will change.
• `let`: Block-scoped. Can be reassigned later. Use for loop counters and changing state.
• `var`: Function-scoped, hoisted. Outdated—avoid using `var` in modern JS!
JavaScript Data Types:
1. Primitives (stored by value):
• `String`: Text in quotes (`"Hello"`, `'World'`, `` `Template` ``)
• `Number`: Integers and floats (`42`, `3.1415`)
• `Boolean`: `true` or `false`
• `Undefined`: Variable declared but not assigned a value
• `Null`: Intentional absence of any value
• `BigInt` & `Symbol`
2. Reference Types (stored by reference):
• `Object`, `Array`, `Function`
Syntax Structure
Syntax Blueprint
const instituteName = "IGM Computers"; // Constant
let enrolledStudents = 150; // Reassignable
enrolledStudents += 1;
console.log(typeof instituteName); // "string"
Code Example
JAVASCRIPT Code
// Course Enrollment Record
const courseName = "KLiC Advanced Python";
const tuitionFee = 2500;
const isCertificationIncluded = true;
let currentBatchStudents = 18;
// Updating mutable variable
currentBatchStudents = currentBatchStudents + 1;
console.log("Course:", courseName, typeof courseName);
console.log("Tuition:", tuitionFee, typeof tuitionFee);
console.log("Certified:", isCertificationIncluded, typeof isCertificationIncluded);
console.log("Updated Students:", currentBatchStudents);
Explanation of the Code
• `const` prevents accidental reassignment of `courseName` or `tuitionFee`.
• `let` allows `currentBatchStudents` to increment when a new student signs up.
• `typeof` reveals the runtime primitive type.
Expected Output
Course: KLiC Advanced Python string
Tuition: 2500 number
Certified: true boolean
Updated Students: 19
Real-World Application
Used across every web app to manage state—from shopping cart item counts to authentication tokens.
Common Mistakes to Avoid
• Trying to reassign a `const` variable (`const x = 5; x = 10;` throws `TypeError: Assignment to constant variable`).
• Using legacy `var`, which leaks out of `if` and `for` blocks due to function scoping.
Quick Practice Challenge
Declare a `const` for your birth year and a `let` for your current age. Calculate your age in 5 years and log it.
Key Takeaways
• Prefer `const` by default; only use `let` when reassignment is required.
• Never use legacy `var` in modern ES6+ code.
• JavaScript primitives include String, Number, Boolean, Undefined, and Null.