DEV Community

Cover image for Var in JavaScript
Rakshambika
Rakshambika

Posted on

Var in JavaScript

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Output:

Science
Enter fullscreen mode Exit fullscreen mode

Re-Declaring the var variable is possible.

<script>
var subject="Maths";
var subject="Science"
console.log(subject);
</script>
Enter fullscreen mode Exit fullscreen mode

Output:

Science
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Output:

Undefined
Enter fullscreen mode Exit fullscreen mode

Excited to continue learning and building with JavaScript!

Top comments (0)