Javascript Variable

A JavaScript variable is a named container used to store data values. Variables allow you to store information that can be referenced and manipulated within your program.

JavaScript variable Syntax


(typeOfVariable) variableName = variableValue

Define a variable:- in the below example, variableName name assigned value John


var name="John";

Using a variable:- Now, You can use variable name in the file.


 console.log(name); //John

Note:- If you did not define the variable type then it will work as like var variable,


name="John";
console.log(name); //John

There are two types of JavaScript variable
1) local variable
2) Global variable

1) Local variable:- A variables declared in a function, become LOCAL variable to the function. Local variables have Function scope: They can only be accessed from within the function.


function user() {
  var name = "John";
  console.log(name);
}
	    
user();
console.log(name);  

Note:- When we call console.log(name) after the function user() call then output will be blank.

2) Global Variables:- A variable declared outside a function, becomes GLOBAL variable. A global variable has global scope: All scripts and functions on a web page can access it.


var name = "John";

function myFunction() {

  console.log(name)  
}