JavaScript Variables

Variables are used to hold information such as values or expressions. When declaring a JavaScript variable, there are some guidelines to follow (also known as identifiers).

  • Name must start with a letter ( A to Z or a to z), dollar( $ ) or underscore( _ )sign.
  • Variables in JavaScript are case sensitive, so v and V are two separate variables.

Lets take an example

var name = "Vishal";

// or
var name;
name = "Vishal";

Lets see another variable

var x = 2;  

Local Variable

A local variable in JavaScript is declared within a block or function. It can only be accessed from within the function or block. For example

function demo(){  
    var z=20;  //local variable  

Global Variable

You can access global JavaScript variables from any function. Variables are declared outside the function. For example

var name= "vishal"; //global variable  

function printname(){