Learnitweb

var in JavaScript

1. Introduction

var allows you to declare a globally-scoped or function-scoped variable. You can initialize a var variable when you declare it but it is optional.

var x;

You can declare and initialize the variable in the same statement.

var x = 5;

You can do declare and initialize two variables in the same line.

var x = 1, y = 2;

You can assign same value to the variables in a single statement.

var x, y = x = 'hello';

2. var with respect to global context

When you declare a var variable, it gets added to the window. You can try the following in the browser console:

var x = 5;

console.log(x); // output is 5

console.log(window.x); // output is 5

In the global context, a var variable is added as a non-configurable property of the global object and it can not be deleted using the delete.

'use strict';
var x = 5;
globalThis.hasOwnProperty('x'); // true
delete globalThis.x; // TypeError in strict mode. Fails silently if not in strict mode.
delete x;  // SyntaxError in strict mode. Fails silently if not in strict mode.

3. You can redeclare a var

It is possible to redeclare a var variable in your code.

var x = 5;
var x = 6;
console.log(x); // output is 6

4. var is global and can be overridden unintentionally

In the following code, x is unintentionally changed in the if block.

var x = 5;

if (true) {
  var x = 2;

  console.log(x); //output: 2
}

console.log(x); //output: 2

5. var variable is hoisted

Hoisting in JavaScript refers to the process in which the JavaScript engine appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code.

console.log("name is " + name);
var name;
//Output is: name is undefined

6. Loosely-typed Variables

JavaScript is a dynamically typed language. You can assign any value to a var variable. You are not required to declare its type. You can assign a different value of different type to a var variable in your code.

var x = 1;  // numeric value

x = 'hello'; // string value 

7. Conclusion

In this quick tutorial, we discussed var variable. Using var could lead to unwanted errors and requires care. Due to the is block-scoped variables are suggested to use. Due to this reason let was introduced. We’ll discuss let in upcoming tutorials.