I hate intros but we must have one 🤷
Before 2015 javascript developers used to use var
as the keyword to declare variables, and life was easy, but not calm 😅
With using var
to declare variables developers had to fight in many fields…
Redeclaration 🤦♀️
Believe it or not, with var
you can use the same variable name as many times as you can without facing any errors, but you have to be ready for the unexpected results😬.
imagine the following:
function sayHi() {
var name = "Our New User"
var isLoggedIn = true
if (isLoggedIn) {
var name = "Sarah"
}
console.log("Hi" + name) // Hi Sarah
}
The first thing that comes to your mind now is, so what?!,
I redefine the variable, what the problem with that?!🤨 It is not a problem at all, as long as you know that is exactly what you want to do, not just that you forget that this variable has already declared before🧐.
The real problem with redeclaration comes with large apps, and once you forget that you have used the same variable name before.
DISCLAIMER✋: this won`t be a problem in case you have solid memory that helps you remember all the variables you have declared within a specific scope.
Scope 😵
The line above ends with the word SCOPE, before digging deeper, let`s first understand what scope is, think of scop as a box within which some functions and variables are accessible.
Chances are variables declared using var
keyword are limitless, except if they are declared within a function.
This means if a variable is not inside a function it will be accessible in the whole app😨.
Now try to connect this point with the one before, redeclaration,
now developers have to remember all the variables they have declared in the global/function scope else they find themselves trapped with results they never expect.
Imagine the following…
function sayHi() {
var name = "Our New User"
var isLoggedIn = true
if (isLoggedIn) {
var name = "Sarah"
console.log("Hi" + name) // Sarah
}
console.log("Hi" + name) // Sarah
}
The log inside the if block makes sense, as we are logging the variable defined within this block, but the log outside the if block is the one highlights the problem, it supposed to prints “Our New User” the value of the variable declared outside the if block, but what happens here is the variable name
declared within the if block totally replaced the one declared outside the if block and here we have to mention hoisting.
Hoisting 😧
Hoisting is the process of lifting variables and functions declarations to the top of their scope.
Variables declared with the keyword var
hoisted to the top of the global/function scope and initialized with the value undefined.
Connecting this with the previous point,
function sayHi() {
var name = "Our New User"
var isLoggedIn = true
if (isLoggedIn) {
var name = "Sarah"
console.log("Hi" + name) // Sarah
}
console.log("Hi" + name) // Sarah
}
we now can find out what is happening here, the new variable declared within the if block is hoisted to the top of the function and of course replaced the original one, which justifies why the two console logs prints the same result.
Now as we went through the problems js developers spent a long time fighting with, now let`s move forward how ES2015 saved our day 😉.
Regarding redeclaration, variables declared using either let
or const
cannot be redeclared within the same scope.
Mentioning the scope, both let
and const
are block-scoped, a block of code is any set of code within {}, which means if a variable declared using either let
or const
within {} it won`t be accessible outside these {}, despite they are hoisted to the top of their scop, which is the {}.
Now let's check out our sayHi function...
function sayHi() {
let name = "Our New User"
var isLoggedIn = true // out of our scope
if (isLoggedIn) {
let name = "Sarah"
console.log("Hi" + name) // Sarah
}
console.log("Hi" + name) // Our New User
}
Now it works as expected the new variable declared within the if block stays within the if block and it does not affect the one outside the if block
But now the question is, which one to use let
or const
🤔?!
The answer is, whatever you want😇, just remember that variables declared with let
can be updated while those created with const
cannot.
Hope this helps and thanks for reading. If you have any questions or topics you want me to write about I will be happy to help❤️
Top comments (31)
const
till you can't is my rule. Simple and works well for me :)A good starting thought, except you will run out of generic namespaces like
key
orname
very soon 😂. So the thinking behind “should Iconst
it?”, should be whether is it generic? If so, uselet
overconst
.my other convention is to never allow generic namespaces haha . My code is scattered with long descriptive variable names.
Actually so are mine. I tend to be a little verbose.
However, I'm quite drawn by Ryan Dahl's (guy behind Node and Deno) style.
So nowadays I'm a little bit of both.
The other trick I learnt is that your eyes can read text with missing characters in-between, as long as the start and the end characters remains the same. So you can start to shorten using this trick.
var nvrAllow, gnrcNmspaces
i loved the rhythm 😃
a huge portion in the community agrees on the same,
but i believe in making it more flexible as for some use cases variables are made to be updated, and for newbies, I am not sure if it is easy to know when you cannot form the early start,
but after all, i totally agree
I agree it's weird learning curve for newbies. I also enforce this convention with ESLint
no-const-assign
. This means that whenever I try to reassign aconst
, my linter will remind me to convert it to alet
.see the following - eslint.org/docs/rules/no-const-assign
oh🤩,
i have not tried that before,
it looks handy,
thanks for sharing🙏
Agree.
Wow,that's amazing Nagwan, thanks a lot
I want to know more about npm,npx, yarn if you write about this it will be so nice
thanks for your feedback,
sure as soon as i can
Way to go Nagwan 🎉🎉
It's very useful as you have used some examples that we find in our daily work.
I think it will be great if you can give us a brief about the data types in javascript.
Hope the best for you and waiting you coming interesting articles
thank u Moatasem for the feedback,
and for the data types article, i will as soon as i can
Great demonstration of
var
vslet
/const
. I remember getting asked in a couple interviews about the difference, I wish I could reproduce an example as clear as this one back then.chances never end😉,
just be ready for the next one💪
if want any topic to be discussed here u can suggest it
And not forgetting the best that
let
has done is to solve nested looping:for(let i=0; i<100; i++) { for(let i=0; i<500; I++) {}}
Where before you would need to be using i, j, k... until if you have complicated loops with conditionals, you won’t even know if it has conflicted.
this is one of the most common interview questions,
thanks for mentioning that,
i wanted to add this section, but i wanted the article to be as concise as I could,
thank u
Good job 👍👍
thank you
Nice article and direct to the point,
If you write about closures I will be grateful
Keep it up
it is gonna be the next article,
thanks for your feedback
Great
thanks
Nice article.
Thanks
hope it helps,
thank u for the feedback
A simple and clear explanation, thank you for this article
thanks for the feedback