Home » javascript » Variables in JavaScript

Variables in JavaScript

A JavaScript variable is simply a name of a storage location. There are two types of variables in JavaScript:

  • Local variable
  • Global variable

There are some rules for declaring a JavaScript variable:

  • Name must begin with a letter (a-z or A-Z), underscore ( _ ), or dollar( $ ).
    • After first letter digits (0-9) can be used to construct a variable name.
    • JavaScript variable names are case sensitive e.g., tea, Tea and TEA are different variables.
    • No reserve word must be used as a variable name.

JavaScript local variable

A local variable is declared inside a block { } or function. It is accessible within the function or the block only. If you try to access it from outside, it will throw you an error.

For example:

JavaScript global variable

A  global variable is accessible from anywhere within the script. A global variable must be declared outside the function or declared with window object is.

Consider the example below:

Variable Declaration and Initialization

JavaScript variable must be declared using the var keyword.

var one = 1;               // variable stores numeric value 1

var two = ‘two’;       // variable named ‘two’ stores string value ‘two’

var three;  // declared a variable named ‘three’ withoutassigning a value

Multiple variables can be declared in a single line:

var one = 1, two = ‘two’, three;

JavaScript also allows variable declaration without the keyword var. In that case, a value must be assigned while declaring a variable.

one = 1;

two = ‘two’;

Managed by MochaHost - Fast & Easy WordPress Hosting