DEV Community

ABISHEK M
ABISHEK M

Posted on

var in JavaScript

var is one of the ways to create a variable in JavaScript. A variable is a place to store a value, like a name or a number.

var is mostly seen in old JavaScript code, written before 2015. Today most people use let and const instead, but it still helps to know var, especially when reading old code.

Creating a Variable

var name = "Abishek";
var age = 22;

console.log(name);
console.log(age);
Enter fullscreen mode Exit fullscreen mode

Here, name stores "Abishek" and age stores 22.

We Can Change the Value

var age = 22;
age = 23;

console.log(age);
Enter fullscreen mode Exit fullscreen mode

The output is 23. The value inside age got updated.

We Can Also Create it Again

We can create the same variable a second time with var, and JavaScript does not give an error.

var name = "Abishek";
var name = "Abi";

console.log(name);
Enter fullscreen mode Exit fullscreen mode

The output is Abi. It just overwrites the old value.

It Works Across the Whole Function

A block is a small part of code inside { }, like an if statement. var does not care about these small blocks, it only cares about the function.

function test() {
  if (true) {
    var x = 10;
  }
  console.log(x); // works fine
}

test();
Enter fullscreen mode Exit fullscreen mode

Even though x was created inside the if part, we can still use it outside the if, as long as we are inside the function.

Hoisting

console.log(x);
var x = 10;
Enter fullscreen mode Exit fullscreen mode

You might expect an error here, but the output is undefined. This is because JavaScript moves the var declaration to the top before running the code. This is called hoisting.

Why var Isn't Used Much Now

Most people use let and const instead of var, because var can cause confusing bugs like accidental redeclaration and hoisting. let is used when the value can change, and const is used when it should not change.

In Short

var was the first way to create variables in JavaScript. It can be changed, redeclared, and it works across the whole function instead of one block. Once you understand var, let and const become easier to learn.

Top comments (0)