Var:
- The var keyword was used in all JavaScript code before 2015.
- While it was the only way to declare variables in older versions of JavaScript.
- Variables declared with var have Function Scope.
Using var, we can declare the variable and initialize it later.
<script>
var subject;
</script>
But, accessing the variable before initialization shows Undefined.
What is Undefined?
- undefined is a special value in JavaScript that means a variable has been declared, but no value has been assigned to it yet.
Re-initializing a value for var variable is possible.
<script>
var subject="Maths";
subject="Science"
console.log(subject);
</script>
Output:
Science
Re-Declaring the var variable is possible.
<script>
var subject="Maths";
var subject="Science"
console.log(subject);
</script>
Output:
Science
Hoisting in var:
Hoisting means JavaScript moves the declaration of a variable to the top of its scope before executing the code.
When a variable is declared using var, only the declaration is hoisted, not the value assignment.
<script>
console.log(a);
var a = 10;
</script>
Output:
Undefined
Excited to continue learning and building with JavaScript!

Top comments (0)