Declare variables, Not war.
What is a variable?
Imagine a computer memory as your home where you put each thing in a particular order so when you need that thing you went there and grab what you want it.
So the same thing happens with a computer it has n number of storage when you want to put some data in it you need some placeholder or container that can do it for you. so variable is that container.
This is not the best practice to declare a variable using the Var keyword. Because with the global scope you can change your variable value accidentally. When your code is small, you can see how many var you declared, it’s hard to keep track of larger code.
A new keyword called let was introduced in ES6 to solve this potential issue with the var keyword. If you were to replace var with let in the variable declarations of the code below, the result would be an error.
let favPprogramming= ‘Python’; // throws an error
This error can be seen in the console of your browser. So unlike var, when using let, a variable with the same name can only be declared once. So using the let keyword we can define our scope of the variable. If we define our variable inside of for loop of if statement, then its scope is limited with that block of code & If we define our variable at the starting of the script, its scope will be global.
The keyword let is not the only new way to declare variables. In ES6, you can also declare variables using the const keyword.
const has all the awesome features that let has, with the bonus that variables declared using const are read-only. They are a constant value, which means that once a variable is assigned with const,
FAV_PROGRAMMING= “Java”; // returns error
As you can see, trying to reassign a variable declared with const will throw an error. You should always name variables you don’t want to reassign using the const keyword. This helps when you accidentally attempt to reassign a variable that is meant to stay constant. A common practice when naming constants is to use all uppercase letters, with words separated by an underscore.
It is common for developers to use uppercase variable identifiers for immutable(Value can’t change after declaration) values and lowercase or camelCase for mutable(Value can change after declaration) values (objects and arrays).
Stay Home, Stay Safe
See you soon 👋