0
0
Javascriptprogramming~15 mins

Variable declaration using var in Javascript - Deep Dive

Choose your learning style9 modes available
Overview - Variable declaration using var
What is it?
In JavaScript, 'var' is a keyword used to declare variables. Variables declared with 'var' can hold data values like numbers, text, or objects. Unlike newer keywords, 'var' has function scope, meaning it is visible throughout the function it is declared in. It was the original way to create variables before newer keywords like 'let' and 'const' were introduced.
Why it matters
Understanding 'var' is important because many existing JavaScript codes use it, and it behaves differently from newer variable declarations. Without knowing 'var', you might write code that behaves unexpectedly, especially with variable scope and hoisting. If 'var' didn't exist, older JavaScript programs would not work, and learning it helps you read and maintain legacy code safely.
Where it fits
Before learning 'var', you should understand what variables are and basic JavaScript syntax. After mastering 'var', you can learn about 'let' and 'const', which are newer ways to declare variables with clearer rules. This topic fits early in your JavaScript journey, right after basic programming concepts.
Mental Model
Core Idea
'var' declares a variable that is visible throughout its entire function, regardless of where it appears inside that function.
Think of it like...
Imagine a room where a light switch controls the whole room's light. No matter where you flip the switch inside the room, the light affects the entire room. 'var' is like that switch: once declared anywhere in a function, the variable is accessible everywhere in that function.
Function Scope with var:

┌─────────────────────────────┐
│        Function Start        │
│                             │
│   var x;  <--- Declaration   │
│                             │
│   if (true) {               │
│     x = 5;  <--- Assignment  │
│   }                         │
│                             │
│   console.log(x);  <--- Access│
│                             │
└─────────────────────────────┘

Note: 'x' is accessible anywhere inside the function.
Build-Up - 6 Steps
1
FoundationDeclaring variables with var
🤔
Concept: Learn how to create a variable using 'var' and assign a value.
var message = 'Hello'; console.log(message); // prints 'Hello' Here, 'var' creates a variable named 'message' and stores the text 'Hello' inside it.
Result
Hello
Understanding how to declare variables is the first step to storing and using data in your program.
2
Foundationvar variables have function scope
🤔
Concept: 'var' variables are visible throughout the entire function they are declared in, not just inside blocks like if or loops.
function test() { if (true) { var x = 10; } console.log(x); // prints 10 } test(); Even though 'x' is declared inside the if block, it is accessible anywhere inside the function 'test'.
Result
10
Knowing that 'var' ignores block boundaries prevents confusion about where variables can be used.
3
Intermediatevar variables are hoisted
🤔Before reading on: do you think a 'var' variable can be used before its declaration line? Commit to yes or no.
Concept: 'var' declarations are moved to the top of their function before code runs, a behavior called hoisting.
console.log(a); // prints undefined var a = 5; This happens because JavaScript treats it like: var a; console.log(a); a = 5;
Result
undefined
Understanding hoisting helps avoid bugs where variables seem to exist before they are declared.
4
Intermediatevar allows redeclaration without error
🤔Before reading on: do you think redeclaring a 'var' variable causes an error? Commit to yes or no.
Concept: You can declare the same variable multiple times with 'var' without errors, which can overwrite values silently.
var count = 1; var count = 2; console.log(count); // prints 2 This can cause unexpected bugs if you accidentally redeclare variables.
Result
2
Knowing that 'var' allows silent redeclaration helps you write safer code by avoiding accidental overwrites.
5
Advancedvar scope differs from let and const
🤔Before reading on: do you think 'var' and 'let' have the same scope rules? Commit to yes or no.
Concept: 'var' has function scope, while 'let' and 'const' have block scope, meaning they are limited to the nearest curly braces {}.
if (true) { var x = 1; let y = 2; } console.log(x); // prints 1 console.log(y); // ReferenceError: y is not defined This shows 'var' leaks outside blocks, but 'let' does not.
Result
1 ReferenceError
Understanding scope differences explains why 'var' can cause bugs in block-level code.
6
Expertvar hoisting only lifts declarations, not assignments
🤔Before reading on: does hoisting move both declaration and assignment of 'var' variables? Commit to yes or no.
Concept: Only the declaration part of 'var' is hoisted, not the assignment, which stays where it is in the code.
console.log(a); // undefined var a = 10; Is treated as: var a; console.log(a); // undefined a = 10; So the value 10 is assigned after the log, not before.
Result
undefined
Knowing this prevents confusion about why variables are undefined before assignment despite hoisting.
Under the Hood
'var' declarations are processed during the JavaScript engine's compile phase. The engine scans the function for all 'var' declarations and moves them to the top of the function scope, creating the variable with an initial value of undefined. Assignments remain in place and happen during execution. This is why variables declared with 'var' exist throughout the function, even before their line of declaration.
Why designed this way?
'var' was designed in early JavaScript when block scope was not supported, simplifying variable handling by using function scope. This design made the language easier to implement but caused confusion later. Alternatives like 'let' and 'const' were introduced to provide clearer, block-level scoping and prevent common bugs.
JavaScript Function Execution with var:

┌───────────────────────────────┐
│ Compile Phase:                │
│  ┌─────────────────────────┐│
│  │ Find all 'var' declarations│
│  │ Move declarations to top  │
│  │ Initialize as undefined   │
│  └─────────────────────────┘│
│                               │
│ Execution Phase:              │
│  ┌─────────────────────────┐│
│  │ Run code top to bottom    │
│  │ Assign values when reached│
│  └─────────────────────────┘│
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does 'var' create block-scoped variables like 'let'? Commit to yes or no.
Common Belief:Many believe 'var' variables are limited to the block they are declared in, like inside if or for blocks.
Tap to reveal reality
Reality:'var' variables are function-scoped, not block-scoped, so they are accessible anywhere inside the function regardless of blocks.
Why it matters:Assuming block scope causes bugs where variables unexpectedly overwrite or leak outside blocks, leading to hard-to-find errors.
Quick: Does hoisting move both declaration and assignment of 'var' variables? Commit to yes or no.
Common Belief:Some think hoisting moves the entire variable declaration and its assigned value to the top.
Tap to reveal reality
Reality:Only the declaration is hoisted; the assignment stays where it is, so variables are undefined before assignment.
Why it matters:Misunderstanding this leads to confusion when variables are undefined before their assignment line, causing bugs.
Quick: Does redeclaring a 'var' variable cause an error? Commit to yes or no.
Common Belief:Many believe redeclaring a variable with 'var' will cause an error or warning.
Tap to reveal reality
Reality:'var' allows redeclaration without errors, which can silently overwrite variables.
Why it matters:This can cause unexpected behavior if variables are accidentally redeclared, making debugging difficult.
Quick: Is 'var' the best choice for new JavaScript code? Commit to yes or no.
Common Belief:Some think 'var' is the recommended way to declare variables in modern JavaScript.
Tap to reveal reality
Reality:Modern JavaScript prefers 'let' and 'const' for clearer scope and safer code; 'var' is mostly for legacy support.
Why it matters:Using 'var' in new code can introduce subtle bugs and reduce code clarity.
Expert Zone
1
'var' declarations are hoisted to the top of their function scope, but if declared outside any function, they become global variables attached to the global object (like window in browsers).
2
In non-strict mode, 'var' variables can be redeclared and overwritten silently, but in strict mode, some behaviors change, though redeclaration is still allowed.
3
Because 'var' ignores block scope, it can cause bugs in loops when closures capture the same variable, leading to unexpected results.
When NOT to use
'var' should be avoided in modern JavaScript code because it lacks block scope and can cause hoisting confusion. Instead, use 'let' for variables that change and 'const' for constants. Use 'var' only when maintaining or reading legacy code.
Production Patterns
In production, 'var' is mostly found in older codebases or libraries. Modern patterns use 'let' and 'const' for clearer scope and immutability. When working with legacy code, understanding 'var' helps safely refactor or integrate new code.
Connections
let and const variable declarations
'let' and 'const' build on and improve the concept of variable declaration by adding block scope and immutability.
Knowing how 'var' works clarifies why 'let' and 'const' were introduced to fix scoping and redeclaration issues.
Function scope vs block scope
'var' uses function scope, while many modern languages and JavaScript's newer keywords use block scope.
Understanding 'var' highlights the difference between function and block scope, a key concept in programming languages.
Variable hoisting in programming languages
Hoisting is a concept where declarations are moved before execution; 'var' is a classic example in JavaScript.
Recognizing hoisting in 'var' helps understand similar behaviors in other languages or environments that separate declaration and execution phases.
Common Pitfalls
#1Using 'var' inside a block expecting block scope
Wrong approach:if (true) { var x = 5; } console.log(x); // expecting error or undefined
Correct approach:if (true) { let x = 5; } console.log(x); // ReferenceError: x is not defined
Root cause:Misunderstanding that 'var' ignores block scope and is function-scoped, leading to variables leaking outside blocks.
#2Using a 'var' variable before assignment expecting its value
Wrong approach:console.log(a); // expecting 5 var a = 5;
Correct approach:var a = 5; console.log(a); // prints 5
Root cause:Not realizing that only the declaration is hoisted, so the variable is undefined before assignment.
#3Redeclaring a 'var' variable accidentally overwrites it
Wrong approach:var count = 1; var count = 2; console.log(count); // expecting 1
Correct approach:let count = 1; count = 2; console.log(count); // prints 2, no redeclaration
Root cause:Assuming redeclaration causes error, but 'var' allows it silently, causing unexpected overwrites.
Key Takeaways
'var' declares variables with function scope, meaning they are accessible anywhere inside the function they are declared in.
'var' declarations are hoisted to the top of their function, but only the declaration, not the assignment.
'var' allows redeclaration without errors, which can lead to silent bugs if not careful.
Modern JavaScript prefers 'let' and 'const' for clearer, block-scoped variables and safer code.
Understanding 'var' is essential for reading and maintaining legacy JavaScript code.