JavaScript Variable


JavaScript variables are containers for storing data information and it is declared with the var keyword.

Variable names must start with a letter and it is case sensitive(x and X are different variables).

Syntax

var <variable-name> = <value>;

Example

<script>
  var x = 10;
  var y = 5;
  console.log('Sum: ',x+y); 
</script>

 

Declare multiple variables in JavaScript

If we want to declare multiple variables in a single line then we can declare multiple variables using a comma sign.

Example

<script>
  var x = 10, y = 5;
  console.log('Sum: ',x+y); 
</script>

Types of variables in javascript

There are two types of variables in javaScript. (1) Local variable and (2) Global Variable

Local variable

A local variable is declared inside a function and is only accessible inside the function.

Example

<script type = "text/javascript">
  function test() {
   var data = "local";    // Declare a local variable
   document.write(data);
  }
  test(); 
</script>

Global variable

A global variable is declared outside a function.

Example

<script type = "text/javascript">
  var data = 30;      // Declare a global variable
  function test() {
    document.write(data);
  }
  test();       
</script>