var in javascript

variable declaration in javascript (var)

var is used to declare variable, it is not mandatory to declare using var keyword.

We strongly recommend you to declare the variable using var keyword.

Syntax
var variable_name=value;

Local variable in javascript

Local variable can only be accessed within the function.

In the below example, when your press "Click me 2" button, it produce "Uncaught ReferenceError: a is not defined" error, since variable a is not declared inside the function (fun_name2). So the alert box won't appear.

Example

Try Yourself

Global variable in javascript

Global variable are declared outside the function and it can be accessed anywhere in the web page.

Example

Try Yourself

Disadvantage while not using var keyword in javascript

We are strongly recommended to use var keyword while declaring variables.

If you not use var keyword the variable will be automatically considered as a global variable.

Example

Try Yourself