Question:
What are the differences between declaring variables using var, let and const?
✨ Bonus: What is hoisting?
Quick answer:
These are a few...
For further actions, you may consider blocking this person and/or reporting abuse
Hi there 🙌
I do not agree with how you define hoisting even though it’s not entirely false.
I would have say « you encounter hoisting problematic when you call a variable before it’s assignations »
But hoisting perse is how javascript handle your code and how it would read it - which leads to : it’s insightful to understand how javascript works .
When reading one’s code Javascript has hidden process which includes hoisting.
Hoisting is the fact that javascript reads your file and before executing your lines it hoists your variable and function ( meaning that it keeps the the variables declaration, without their value, and functions on « top of the file » before processing to any logic
Common cases are when one calls either a function ( with function keyword ) or variable with the « var » ’ keyword - indeed - before their definitions. :)
Then this was exactly why let and const were created in order to have a better control of those - ( good to know ) knowing that non mutable objects prevents from memory allocation loss in any programming language
[ edit ] Here is a the doc to which we can understand the arguments I have above regarding the def of hoisting developer.mozilla.org/en-US/docs/G...
Thanks! I actually didn't realise that hoisitng can be useful with function declaration. Let me just add an update pointing to your comment. Thanks again!
Actually when you do this:
x = 2
You are declaring the variable.
That's why:
x = 2
var y = x + 1
console.log(y) // 3
Maybe something like this will help to understand better your point:
console.log(x) // undefined
x = 2
var y = x + 1
console.log(y) // 3
var x;
console.log(x) // error
x = 2
var y = x + 1
console.log(y)
I came back over and over to this topic and always find new thigs ;)
yeah, some part of JS is so confusing 🤷 Thanks for a detailed example!
I would argue that knowledge of hoisting isn't a "bonus" for this topic, since it's a major part of the difference between var and const/let.
Yeah, this actually makes sense 👍
I need to come up with a new structure for posts covering multiple related questions.
I literally had this JS question asked to me about the const, let, var 😂
Perfect and what a coincidence
wow, hope this article helped :)