JavaScript Variable and its Scope

JavaScript Variable
JavaScript Variable

JavaScript Variable

A JavaScript variable is simply a name of storage location which holds some value and can be changed any time. A JavaScript variable must have a unique name. You can assign a value to a JavaScript variable using equal to (=) operator. A variable is also called identifiers.

There are two types of variables in JavaScript : local variable and global variable.

Rules for declaring a JavaScript variable.

  1. Variable name must begin  with a letter (a to z or A to Z), an underscore( _ ), or dollar( $ ) sign.
  2. After first alphabet any number of  digits (0 to 9) can be used, for example A1.
  3. In JavaScript,  variables are case sensitive which means a and A are two different variables.

Valid JavaScript variables

var x = 10;

var _value=”sonoo”;

Invalid JavaScript variables

var  123=30;

var *aa=320;

Declare a Variable without var Keyword

JavaScript allows variable declaration without var keyword. But when You declare a variable without var keyword then must be assigned a value.

Example

x=5;

Note: Although It is Not Recommended to declare a variable without var keyword because it can accidentally overwrite an existing global variable.

Loosely-typed Variables

C# or Java has strongly typed variables, which actually means that  a variable must be declared against a data type, which in turn tells the compiler about the  type of data the variable can hold.

JavaScript variables are loosely-typed which means it does not follow the strict data type rules which says every variable has a data type and every data type is predefined. So in JavaScript it does not require a data type to be declared first. Any type of literal value can be assigned  to a variable without actually naming it e.g. string, integer, float, boolean etc..

Example of Loosely Typed Variables

var one =1;  // numeric value

var one = ‘one’; // string value

var one= 1.1; // decimal value

var one = true; // Boolean value

var one = null; // null value

Example of JavaScript variable

<!DOCTYPE html>
<html>
<head> <title>test </title>
</head>
<body>
<script> 
var x = 10; 
var y = 20; 
var z=x+y; 
document.write(z); 
</script> 
</body>
</html>

Output of the above example

30

Types of Variables in JavaScript

  1. JavaScript Local variable
  2. JavaScript Global variable

JavaScript local variable

A JavaScript local variable is one which is declared inside block or function. It is accessible within the function block only. For example:

<!DOCTYPE html>
<html>
<head> <title>test </title> </head>
<body>
<script>  
function abc(){  
var x=10;//local variable  
}  
</script>  
</body>
</html>

JavaScript Global variable

A JavaScript global variables are the variables declared outside if all blocks or declared with window object. These are accessible from any function. For example:

<!DOCTYPE html>
<html>
<head> <title>test </title> </head>
<body>
<script> 
var data=200;//global variable 
function a(){ 
document.writeln(data); 
} 
function b(){ 
document.writeln(data); 
} 
a();//calling JavaScript function 
b(); 
</script> 
</body>
</html>

Declaring JavaScript global variable within function

You can declare JavaScript global variables inside a function, to do this window object is used. The variables declared with window object can be accessed from anywhere the program. For example:

<!DOCTYPE html>
<html>
<head> <title>test </title>
</head>
<body>
<script> 
function m(){ 
window.value=100;//declaring global variable by window object 
} 
function n(){ 
alert(window.value);//accessing global variable from other function 
}
 m();
 n();
</script> 
 </body>
</html>

Internals of global variable in JavaScript

When a variable is  declared outside a function,  it is internally  added to the window object. You can access it through window object also. For example:

<!DOCTYPE html> 
<html>
<head> <title>test </title>
</head>
<body>
<script>
var value=50;  
function a(){  
alert(window.value);//accessing global variable   
}
</script>
</body>
</html>

Points to Remember :

  1. Variable can store a  value which  can be changed at later part of the program.
  2. Variables can be defined using var Variables defined without var keyword become global variables.
  3. Variables must be initialized before using.
  4. More than one variable can be defined in a single line. e.g. var x = 21, y = 2, z = “three”;
  5. Variables in JavaScript are loosely-typed variables. These variables can store any value of any data type through out it’s life time.

Scope in JavaScript

Scope in JavaScript defines the portion of program from where  variables, objects and functions defined in that program are legally accessible.

There are two types of scope in JavaScript.

  1. Global scope
  2. Local scope

Global Scope

When Variables are  declared outside of all functions is called global variables. The Global variables in JavaScript are accessible and modifiable from any function. Hence global variables have global scope.

Example: Global Variable

<!DOCTYPE html> 
<html>
<head> <title>test </title></head>
<body>
<script>    
var userName = "Bill";    
function modifyUserName() {            
userName = "Steve";        };    
function showUserName() {            
alert(userName);        
};    
alert(userName); // display Bill    
modifyUserName();    
showUserName();// display Steve
</script>
</body>
</html>

The example above shows that , the variable userName is  a global variable because it has been  declared outside of all functions. The modifyUserName() function will modify userName as userName is a global variable and hence can be accessed from  inside any function. Also, showUserName() function will show current value of userName variable. So, Changing the  value of a global variable in any function will reflect the change throughout the program.

Local Scope

Variables that are declared inside a function with var keyword are known as local variables. Local variables cannot be accessed or modified from outside the function declaration. Hence all local variables have Local Scope.

Example: Local Scope

<!DOCTYPE html> 
<html>
<head> <title>test </title></head>
<body>
<script>       
function createUserName() {        
var userName = "Bill";    
}    
function showUserName() {        
alert(userName);    }    
createUserName();    
showUserName(); // throws error: userName is not defined
</script>
</body>
</html>

Now can see here that, userName is local to createUserName() function.So  It cannot be accessed inside  showUserName() function or from any other functions. It will show an  error if an access is made to  a variable which is either  not in the local or global scope.

Some tips..

A local variable and global variable can have same name and if  value of one variable is changed then it will not affect on the value of another variable.

Example: Scope

<!DOCTYPE html> 
<html>
<head> <title>test </title></head>
<body>
<script>
var userName = "Bill";
function ShowUserName(){
var userName = "Steve";     
alert(userName); // "Steve"
}
ShowUserName();
alert(userName); // Bill
</script>
</body>
</html>

JavaScript does not follow block level scope inside { }. In the  example below,  the variables defined inside  if block can be legally accessed from outside if block, inside the function body.

Example: No Block Level Scope

 <!DOCTYPE html> 
<html>
<head> <title>test </title></head>
<body>
<script>
Function NoBlockLevelScope()
{        
if (1 > 0){
   var myVar = 22;    
           }    
alert(myVar);
}
NoBlockLevelScope();
</script>
</body></html>

Points to Remember :

  1. JavaScript has global scope and local scope.
  2. The JavaScript Variables which are  declared and initialized outside of any function are  global variables.
  3. Any Variables which are declared and initialized inside any function is a local variable to that function.
  4. JavaScript Variables which are declared without var keyword even inside any function is changes to  global variable automatically.
  5. Global variables in JavaScript  can be modified and accessed from  any part of the program.
  6. Local variables cannot be accessed outside the function declaration.
  7. Same name can be given to Global variable and local variable.
  8. JavaScript do not follow block level scope inside curly braces.

You may also like: Let us Learn JavaScript from Step By Step

Chapter 2 How To Enable JavaScript in Browsers

To visit the  Official website of JavaScript Click here

0 0 votes
Article Rating
Subscribe
Notify of
guest
6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback
1 year ago

[…] Posts:  JavaScript Variable and its Scope,        How To Enable JavaScript in Browsers,  […]

Tilak
1 year ago

Very nice work

rajeev kumar
rajeev kumar
1 year ago

nice

trackback
1 year ago

[…] Posts:  JavaScript Variable and its Scope,        How To Enable JavaScript in Browsers,  […]

trackback
1 year ago

[…] Posts:  JavaScript Variable and its Scope,        How To Enable JavaScript in Browsers,  […]

Please Subscribe to Stay Connected

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

DigitalSanjiv will use the information you provide on this form to be in touch with you and to provide updates and marketing.
Share via
Copy link
Powered by Social Snap
%d bloggers like this: