android-logo

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;  
document.write(x);  


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


<script>  
function demo(){  
    var z=20;  //local variable  
}  
</script> 


Global Variable

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


<script>  
var name= "vishal"; //global variable  

function printname(){  
document.writeln(name);  
}  

printname();

</script>


previous-button
next-button

facebook-logo
twitter-logo
instagram-logo

2020 © All rights reserved.