JavaScript — Variables
Javascript variable is basically the name of the value and it is used to store the data such as a string of text, numbers, boolean, etc. These stored data can be set, updated, retrieved.
How To Create Javascript Variable
Javascript variable can be created using var keyword followed by name of the variable.
var variableName;To assign value inside the variable,use assignment operator(=) like var varName = value.
General Syntax
var variableName; //variable initialization
var variableName = value;//assigning value to the variableVariable Value :Undefined
A javascript variable that is declared without a value will have an undefined value.
var fruitName;
document.write(fruitName);
//output:undefinedDeclaring Multiple Variables at Once
Javascript provides the flexibility to declare and set a variable value in a single statement. Each variable should be separated by a comma.
Get Diwakar Chauhan’s stories in your inbox
Join Medium for free to get updates from this writer.
Declaring multiple Variables
General Syntax
var fruit = "mango", cost = 50, isAvailable = true;Javascript Variables Scope
In javascript,variable can be declared either local scope or global scope.Followings are the javascript variable scope:
- Local Scope
- Global Scope
Local Variables
A local variable is declared inside the function and it can only access inside the function. It can not be accessed outside of the function.
learningResource();
document.getElementById("result").innerHTML =
"Today, I would like to learn:" + learningResources;
function learningResource() {
var learningResources = "Web Designing";
}Global Variables
A global variable is declared outside of the function and it can be accessed anywhere in the Javascript code, even inside the function.
var fruit = "Mango "; // global variable
function userTest() {
var msg = " is the one of the best fruit.";
alert(fruit + msg); //can access global and local variable
}
userTest();
document.write(fruit); //can access global variable
document.write(msg); //error: can't access local variableTo read more about, Javascript variables, click here.








