Javascript variables are 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.
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.
var variableName; //variable initialization
var variableName = value;//assigning value to the variable
Source Code
var FruitName = "Mango";
var Cost = 25;
var isAvailable = true;
A javascript variable that is declared without a value will have an undefined value.
Source Code
var fruitName;
document.write(fruitName);
//output:undefined
Javascript provides the flexibility to declare and set a variable value in a single statement. Each variable should be separated by a comma.
Source Code
var fruit = "mango",
cost = 50,
isAvailable = true;
In javascript,variable can be declared either local scope or global scope.Followings are the javascript variable scope:
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.
Source Code
learningResource();
document.getElementById("result").innerHTML =
"Today, I would like to learn:" + learningResources;
function learningResource() {
var learningResources = "Web Designing";
}
A global variable is declared outside of the function and it can be accessed anywhere in the javascript code, even inside the function.
Source Code
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 variable