Variable is like a container for storing data or values that can be changed later on.
In this example, a,b and c are variables, declared with the 'let' variables.
let message
let a = 100
let b = 'banana'
let c = [1,2,3]
From the example above, the let message is a variable declaration which does not have value yet. However, it declares the variable's name, event though there's no variable, the default value will be undefined.
Above, a stores the value 100 and b stores the string value called 'banana'. c stores the array which contains the value 1,2,3.
Variables label the data with a descriptive name, so they can be identified what they store.
Naming variables is very important to make our programs can be understood more clearly by the reader and ourselves.
Also, once we declare variables, we can use variables later on over and over again, so this way is more productive than keep bringing the data.
For example, if I want to make the multiplaction table, I could write the code like below.
console.log('2 X 1 = 2')
console.log('2 X 2 = 4')
console.log('2 X 3 = 6')
It takes so much time to write the code one by one, so this way is so unproductive.
However, if I declare i and j as variables, the codes become much simple and productive
for(let i=2;i<10;i++){
for (let j=1;j<10;j++){
console.log(i +' x '+ j +'=' i*j)
}
}
var a = 100
let b = 'banana'
const c = [1,2,3]
There are three keyword to declare variables, var, let and const.
Back when JavaScript was first created, there was only var.
However, var can sometimes be confusing or downright annoying because of hoisting. If you want to know about hoisting, please click this link().
However let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used.
var myFriend = 'James'
var myFriend = 'Rubio'
From the above, the value of myFriend is changed from James to Rubio.
However, let doesn't let that happen.
let myFriend = 'James'
let myFriend = 'Rubio'
Because the identifier 'myName' has already been declared, the computer shows you an error and will not work.
For this benefit, let is more likely to use than var.
The keyword const stands out for 'constant'.
After we use const to name variables, the data of variables can't be changed. Therefore, we can call const is immutable.
It's much more secure and safe way to protect the data of programs than using let or var.