Header add


In this article we will discuss Variable in JavaScript. If you miss our previous article please follow the link Comment in JavaScript.

JavaScript Variable

Variable means anything that can vary. JavaScript includes variables which hold the data value and it can be changed anytime.

JavaScript uses reserved keyword var to declare a variable. A variable must have a unique name. You can assign a value to a variable using equal to (=) operator when you declare it or before using it.

Variables are case sensitive and must start with an alphabet letter or a underscore (_).

Syntax:

var <variable-name>;
var <variable-name> = <value>;



The syntax should like this;

Variable Scope in JavaScript

Scope of a variable is the part of the program from where the variable may directly be accessible.
In JavaScript, there are two types of scopes:

  • Global Scope – Scope outside the outermost function attached to Window.
  • Local Scope – Inside the function being executed.

Let’s look at the code below. We have a global variable defined in first line in global scope. Then we have a local variable defined inside the function fun().

When we execute the function fun(), the output shows that both global as well as local variables are accessible inside the function as we are able to console.log them. This shows that inside the function we have access to both global variables (declared outside the function) and local variables (declared inside the function).Let’s move the console.log statements outside the function and put them just after calling the function.
When we run the application the application is printed as



For online demo please look into below;







  Summary
 In this tutorial we discussed Variable in JavaScript. If have any question related to this topic then give your feedback.


You May Also Like...

Post a Comment

Previous Post Next Post