/  Technology   /  JavaScript variables
js1

JavaScript variables

 

What are JavaScript Variables?

JavaScript variables can be considered as containers which stores a particular value or name for a particular block of memory.

In JavaScript we can assign variables with any of these 3 keywords var, let, const.

In JavaScript any data-types can be assigned to variables. If you assign a number to a variable then the type of the variable will be number. Likewise we can assign string, object, and array.

JavaScript variables has standardised naming conventions while declaring the variables:

  1. Don’t use the JavaScript language keywords such as If, for, else-if, true, false, while, function etc.
  2. Do not start with a digit 0, 1, 2,…9.
  3. Do not use special characters (%, S, &) inside the name.
  4. Start with an alphabet or followed by an alphabet or digits or underscore.
  5. Can use uppercase or lowercase alphabets.

Valid Variable Names with Examples:

  • var Sum;
  • var first_name;
  • var testCase_1;

Invalid Variable Names with Examples:

  • var 1st_sum;
  • var function;
  • var last$name;

 

Leave a comment

Javascript-Variables

 

A JavaScript variable is simply known as the storage location. There are two types of variables in local variable and global variable.

There are some rules while declaring a JavaScript variable (known as identifiers).

  • The name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
  • After the first letter, we can use the digits 0 to 9.
  • JavaScript variables are case sensitive( x and X are different variables).

 

Example :

 

<html>
<body>
<script>  
var x = 10; 
var y = 70; 
var z=x+y; 
document.write(z); 
</script> 
</body>
</html>

 

OUTPUT:

 

80

 

local variable :

 

It is declared inside block or function. It is accessible within the function or block only.

 

<script> 
function abc(){ 
var x=10;//local variable 
} 
</script>

 

OR

 

<script> 
If(10<13){ 
var y=20;//JavaScript local variable 
} 
</script>

 

global variable:

 

It is accessible from any function. A variable i.e. declared outside the function or declared with a window object is known as a global variable.

 

Example:

 

<html>
<body>
<script> 
var data=500;//gloabal variable 
function a(){ 
document.writeln(data); 
} 
function b(){ 
document.writeln(data); 
} 
a();//calling JavaScript function
b();

</script> 
</body>
</html>

 

OUTPUT:

 

500 500