A variable is a container for a value, like a number we might use in a sum, or a string that we might use as part of a sentence.
Let's look at a simple example:
var value = "Hello World";
var x = 10;
- The value stored in a variable can be changed during program execution.
- A variable is only a name given to a memory location, all the operations done on the variable effects that memory location.
- In JavaScript, all the variables must be declared before they can be used.
Before ES2015 (ES6), JavaScript variables were solely declared using the var keyword followed by the name of the variable and semi-colon.
After ES2015 (ES6), we now have two new variable containers: let and const.
There are 3 ways to Declare a JavaScript Variable in ES6 :
- Using
var
- Using
let
- Using
const
var name; // undefined
var name = "Souradeep";
name = "< Whatever Your Name is >";
var num = 10;
var sum = 5 + 10 + 1;
let x; // undefined
let name = 'Souradeep';
let age = 22;
age = 41; //Works same as var.
const name = 'Souradeep';
name = 'Mikhail'; // will give Assignment to constant variable error.
let | var |
---|---|
let is block-scoped. | var is function scoped. |
let does not allow to redeclare variables. | var allows to redeclare variables. |
Hoisting does not occur in let. | Hoisting occurs in var. |
A JavaScript local variable is declared inside block or function. It is accessible within the function or block only. For example:
function abc() {
var x = 10; // local variable
}
If (10 < 13) {
var y = 20; // Also a local variable
}
A JavaScript global variable is accessible from any function. A variable i.e. declared outside the function or declared with window object is known as global variable. For example:
var data=200; // global variable
function first(){
var localData = 400;
console.log(data);
console.log(localData);
}
function second(){
console.log(data);
console.log(localData); // Will give error saying 'localData not defined'
}
first(); //calling JavaScript function
second();