a
Before diving into execution flow, let’s start with the basics: What are variables in JavaScript?
What is a Variable?
A variable is like a container that holds a value. You can store numbers, text, or other data types inside a variable and use them later in your program.
Think of a variable as a box with a name. You can put something inside, take it out, or even replace it with something else.
🔹 Example
let name = "Alice"; // 'name' is a variable storing the value "Alice"
console.log(name); // Output: Alice
Why Use Variables?
- Store information (e.g., a user’s name, age, score in a game).
- Reuse values instead of writing them multiple times.
- Make your code dynamic (e.g., change values without modifying the entire program).
JavaScript is loosely typed, meaning you don’t need to specify a variable’s type when declaring it.
Example of Dynamic Typing
let myVar = 10; // myVar is a number
console.log(typeof myVar); // Output: number
myVar = "Hello"; // Now myVar is a string
console.log(typeof myVar); // Output: string
Key Point: myVar
starts as a number but changes to a string without any error.
Static vs Dynamic Typing
Feature | Static Typing (e.g., Java, C++) | Dynamic Typing (e.g., JavaScript, Python) |
---|---|---|
Type declaration | Required (int x = 5; ) |
Not required (let x = 5; ) |
Type enforcement | Strict (must match type) | Flexible (can change anytime) |
Error detection | Caught at compile time | Caught at runtime |
Code flexibility | Less flexible | More flexible |
Ways to Declare Variables in JavaScript
JavaScript provides four ways to declare variables:
-
var
– (Old way), avoid using it in modern JavaScript. -
let
– Can be updated but not re-declared in the same scope. -
const
– Once assigned, cannot be changed. - Declaring Variables Without Any Type (not recommended).
1. Using var
(Not Recommended)
var age = 25;
console.log(age); // Output: 25
🔸 Issues with var
:
- Can be re-declared (causing confusion).
- Does not follow block scope.
2. Using let
(Recommended for Changeable Values)
let score = 100;
score = 200; // Allowed
console.log(score); // Output: 200
🔹 Why use let
?
- Allows value updates.
- Follows block scope (variables exist only inside
{}
).
3. Using const
(Recommended for Fixed Values)
const pi = 3.1415;
console.log(pi); // Output: 3.1415
🔹 Rules of const
- Cannot be reassigned (
pi = 3.2;
will cause an error). - Must be initialized immediately (
const x;
is invalid).
Understanding Hoisting
Hoisting is JavaScript’s behavior of moving variable and function declarations to the top before execution.
🔹 Hoisting with var
console.log(num); // Output: undefined
var num = 20;
console.log(num); // Output: 20
var
is hoisted with undefined
.
🔹 Hoisting with let
and const
console.log(city); // ❌ ReferenceError (TDZ)
let city = "New York";
console.log(city); // ✅ Output: "New York"
🚀 let
and const
are hoisted but not initialized, causing a ReferenceError if accessed before declaration.
JavaScript Scope (Where Variables Exist)
Global Scope
Variables declared outside functions are global (accessible anywhere).
let globalvar="I'm Global";
function myFunction() {
console.log(globalvar);
}
myFunction(); // Output: I'm Global
console.log(globalvar); // Output: I'm Global
Local (Function) Scope
Variables declared inside a function are local (only available inside that function).
function myFunction() {
let localVar = "I'm local";
console.log(localVar);
}
myFunction(); // Output: I'm local
console.log(localVar); // ❌ ReferenceError (not accessible outside)
JavaScript Interview Questions (FAQ)
What is the difference between var
, let
, and const
?
Answer: var
is function-scoped and allows redeclaration. let
is block-scoped and allows reassignment but not redeclaration. const
is block-scoped and cannot be reassigned.
What is hoisting in JavaScript?
Answer: Hoisting is JavaScript’s behavior of moving variable and function declarations to the top of their scope before execution.
Why does let
give a ReferenceError but var
gives undefined when accessed before declaration?
Answer: var
is hoisted and initialized as undefined
, but let
stays in the temporal dead zone (TDZ) until declared, causing an error.
Can we update or redeclare const
variables?
Answer: No, const
variables cannot be updated or redeclared.
What happens if you declare a variable without var
, let
, or const
?
Answer: It becomes a global variable automatically, which is bad practice.
function test() {
myVar = 10; // No var, let, or const → Global variable!
}
test();
console.log(myVar); // Output: 10
Conclusion
✅ Use let
for variables that can change.
✅ Use const
for fixed values.
✅ Avoid var
because of hoisting and function scope issues.
✅ Understand execution flow (Creation + Execution phase).
✅ Learn about hoisting to avoid common JavaScript errors.
Mastering these concepts will help you write clean and bug-free JavaScript!
Top comments (3)
Come on guys. Whoever wrote the blog post don't understand how variable and constant works.
"const variables cannot be updated or redeclared" - WTF does this even mean?
Let me teach some English here,
"Variable" - means "something that can be varied / changed"
"Constant" - means "something that doesn't change"
What does "const variables" mean?
"Something that doesn't change, but it can be changed" - really??
Constant and Variables are called "Identifiers".
An identifier whose value can be changed is called a variable.
An identifier whose value cannot be changed is called a constant.
What does "const variables" mean?
"Something that doesn't change, but it can be changed" - really??
First it was never mentioned that const variable can be changed if you know js then you must know that const variable is if once assigned it cannot be updated
Oh, please spare me the lecture on what a const is!
I didn’t stumble into this discussion without knowing JavaScript. My issue is with your careless terminology and misleading explanations.
I still don't know if you understood my original comment or not.
You’re calling it a “const variable”, a term that’s not only contradictory but also laughable.
Do you even realize what you’re saying? A constant by definition doesn’t change. A variable by definition does. So, when you combine the two, it’s like saying “something that doesn’t change but can change.” Seriously, is that the kind of clarity you think helps your audience?
And let me quote your response: “if once assigned it cannot be updated.” Guess what? That’s wrong too. A const binding cannot be reassigned, sure, but if it’s an object or an array, its properties or elements can be changed. So, even your attempt at justifying your explanation is flawed.
Instead of doubling down on this nonsense, why not admit you got it wrong and fix the content? It’s okay to make mistakes, but it’s not okay to mislead your audience and then act like you’re beyond critique.
If you want to educate, do it right. But if you’re going to defend low-effort, sloppy content with half-baked explanations, expect to get called out on it. The internet already has enough misinformation, and we don’t need more of it.