Learn JavaScript Hoisting In 5 Minutes
HTML-код
- Опубликовано: 30 июл 2024
- JavaScript Simplified Course: javascriptsimplified.com
Hoisting. It is the word everyone throws around when talking about JavaScript, yet no one takes the time to actually explain what hoisting is, how it works, and why it is important. In this video I will be explaining everything you need to know about hoisting so next time someone mentions it you can understand exactly what they mean.
📚 Materials/References:
JavaScript Simplified Course: javascriptsimplified.com
🌎 Find Me Here:
My Blog: blog.webdevsimplified.com
My Courses: courses.webdevsimplified.com
Patreon: / webdevsimplified
Twitter: / devsimplified
Discord: / discord
GitHub: github.com/WebDevSimplified
CodePen: codepen.io/WebDevSimplified
⏱️ Timestamps:
00:00 - Introduction
00:30 - Hoisting Functions
03:15 - Hoisting Variables
#Hoisting #WDS #JavaScript
IMPORTANT: I want to make a few clarifications to this video based on some comments.
1. JavaScript does not actually move your code around before executing. I know I talk a lot about how JavaScript will act like it moves your functions to the top of your file, but it doesn't actually do this moving. In reality what happens is it first reads your code before executing the code so it knows which functions you have defined before executing. This is really not important, though, as all that matters is how the code actually works and not what happens with your code when the computer parses it.
2. One thing I did not mention in this video is how hoisting works within scopes. For example if you define a function called a and inside that a function you define another function called b the b function would only be hoisted to the top of the a function since the b function is inside the scope of the a function. I probably should have covered this, but this topic is more related to scoping which could be its entirely own video.
3. Technically, let and const are actually hoisted, but they are not initialized with a value which is why you get an error when trying to use them before they are declared. The code example people use to demonstrate this generally looks like this.
function log(){
console.log(value)
}
let value = 1
log() //output: 1
In this example value is technically used above where it is declared, but it is used inside a function that is called after value is defined which is why there is no error. In some programming languages this would cause an error, but not in JavaScript. For these types of examples you can still use the top to bottom nature of JavaScript to understand what is happening and see why this works. First we define a function called log. None of the code in this function is executed when we define it so we can ignore the code in the function for now. Next we define a variable called value and set it to 1. Finally we call the log function we defined previously which prints out the variable value. As you can see from this top to bottom example the variable value is only ever used after it is defined which is why there is no error and for all intents and purposes you can treat let/const as if they are not hoisted since they are not able to be used before initialization like var/function.
Now the reason I did not include all this information is for 2 reasons (I did not know some of it, and it is irrelevant). The point of this video is to help someone that does not understand hoisting understand what it is, how you can use it, and why it is important. I could have made this video 10-20 minutes long and talked about every edge case and technicality behind hoisting, but that needlessly bloats the video, makes things much more complicated for someone just learning hoisting, and goes against everything my channel is about. I called the channel Web Dev Simplified for a reason. I want to simplify the web for everyone and not worry about technicalities that don't impact how your program day to day.
In my opinion this video covers all the main concepts behind hoisting without being too long or too complicated so that someone can easily watch this video and walk away with a solid understanding of what they need to know about hoisting to do work as a developer. For example, I had no idea that let and const were technically hoisted when making this video, but I have never ran into an issue where that information would have been relevant in my development career so it probably isn't important for me to teach in this video even if I did know it.
I bet it took you to write this comment longer than making this video 😆
Thanks for the extra info Kyle!
@@fluffyniki3257 If you believe this, then you severely underestimate how long it takes to make a video. Even a simple 5 minute video like this takes much longer than writing out a few paragraphs of text.
I suggest you re-upload the video. There are many missing points you did not cover as you already mentioned in your comment. The quick answer on the whats and hows of hoisting is "the two step compilation process". By that token you will also cover hoisted scopes. Just a suggestion. Don't get me wrong but your video now creates more confusion than it solves, especially for beginner javascript devs.
Great stuff, as always, Kyle. Just fyi, the expression is "for all intents and purposes."
I would really recommend people going to the MDN documentation. There’s some weirdness of hoisting that they give good examples of. Especially in concern of block scopes.
Exactly 💯
Great and short read which makes a lot of sense!
So it's basically:
1. for functions:
Being able to use a variable's value in its scope before the line it is declared. ("Value hoisting")
2. for var:
Being able to reference a variable in its scope before the line it is declared, without throwing a ReferenceError, but the value is always undefined. ("Declaration hoisting")
3. for let, const and class:
The declaration of the variable causes behavior changes in its scope before the line in which it is declared.
2:34 - 3:00 let and const are hoisted
MDN web docs:
Variables declared with let and const are also hoisted but, unlike var, are not initialized with a default value. An exception will be thrown if a variable declared with let or const is read before it is initialized.
Example:
function foo(){
console.log(bar)
}
let bar = 1
foo(); //output: 1
Akshay Saini does a pretty good job at explaining hoisting in his Namaste Javascript series on youtube, and goes into detail about how the call stack works and why let and const are hoisted, but in a different manner than var
if they are hoisted but not initialized, isnt that just the same as them not being hoisted in the first place? Or am i missing something?
@@ashy7198
Written code:
function foo(){
console.log(bar)
}
let bar = 1
foo() //output: 1
Equivalent code or when hoisting is applied:
let bar
function foo(){
console.log(bar)
}
bar = 1
foo() //output: 1
Another way of thinking about hoisting is that memory will be allocated for variables and functions before execution. If variables aren't hoisted then the code above would throw an error inside the function stating that bar is undeclared.
Does this make sense?
As mentioned by another comment, I recommend this video for a deeper dive on hoisting/execution context: ruclips.net/video/Fd9VaW0M7K4/видео.html
@@StrayKev yes! That does make sense thanks for clearing that up for me 🙂
@@StrayKev If I am not mistaken here the reason for this is that while JavaScript is interperted is that it is ran twice, once for memory allocation and once for execution :)
As always super clean and concise in explaining the concepts; you are great!
When running the JS code, a global execution context is created. It is created in two phases:
1. Creation Phase
Creation of the Variable Object
Creation of the Scope Chain
Setting the value of this keyword
2. Execution Phase
Runs code line by line.
This is the correct answer. I was about to post this as well.
Thank you for rectifying that.
@@robertholtz welcome
@@its_maalik thanks
Very nicely covered all important points. Thanks Kyle.
Really good explanation about the topic, also i really love your content, you are helping me become a greater developer, thanks Kyle
Straight to the point as always. Nice one 👍
Clear and to the point explanation. Thank you soo much!
Great explanation with very straight forward examples👌
Thank u so much. I was planning to learn about it but with this video i'm pretty sure i understand it all
Great explanation Kyle. Thanks for ur content.
very clean explaination !
u break down evry complex concepts..keep uploading more such js vid.!!!!!! huge respect...
Great job, as usual, Kyle!
Thanks bruh
looking forward to see more videos of yours
Thank you so much for this... simple to understand
let and const are actually hoisted, you get a reference error if you try to access them in their TDZ (i.e. Temporal Dead Zone) which is different from them not being hoisted at all
I love this video format! in 5 mins to learns some tricks!
A daily dose of Web Dev Simplified makes one a better programmer
It's very easy to understand thank you so much for your explanation about hosting 😊👌🏼👌🏼👌🏼👌🏼👌🏼
Kyle - I think you did a great job, and I think you're right. The point of a video like this is to give the general overview to someone who does not understand what the concept is and to simplify it. If they would like to know more, there are always docs that they can go look at elsewhere. I also know you like to do your blog posts so I'm sure you will do one at some point on this topic if you haven't already. All in all, disregard the people who have to make it such a big deal to write negative comments when you clearly created such an amazing channel that has helped individuals like me learn way more than I ever thought I could learn without formalized education. Keep it up, my man!
You shouldn't encourage him to ignore feedback. He's explaining why it works like that, the details matter. And for someone who focuses most of his time on cringe thumbnails and very opinionated topics you'd think he can manage less than constructive feedback.
I agree. This video is awesome. Everyone needs to freaking chill. Kyle does really amazing work and thanks to him, I was able to learm faster and get a job.
This was great! Thank you very much
Well I learned something new today. Thanks for the great vid.
sir your way to explain hoisting in 5 min is amazing because hoisting is hard to understand but you made it just a piece of cake
Thank you !! very informative
It all comes down to the history of JavaScript and how Var and Function is implemented. These constructs are members of the enclosing Function object or Global object - to which the variable is scoped. Vars are not scoped to blocks.
Since JavaScript runs from top down the Var statement is not executed until the line is hit and the member not created until then. Function declarations are treated differently, detected when the code is parsed, and the identifier/name is hoisted. Let and Const are later inventions that are implemented a bit differently and don't result in members on the enclosing object. That is why they are not hoisted.
Amazing! Simple and easy!
You are the best coding teacher on youtube👍👍
What I learned... Do not use the var to define a variable but const and let. Thank you sir, great content as always!
U rule bro! Keep up the awesome work!
Thanks man. Really simplifies
Nice simplification of this topic, Kyle! As seen in the comments here, hoisting is one of those topics that mostly just let's the nerds come out and try and show how smart they are. Really, though, outside of job interviews, the concept is largely irrelevant. Not because it is not important, but because of how easy it is to spot and fix if you do get it wrong. Oh, got an error... 30 seconds later, oh, just need to move this line above that line...done. Not a big deal (unless you just want to show how smart you are by blasting a brilliant RUclipsr).
Good at teaching code and styling your hair. Very informative video with great explanations:)
You are rock... Thanks kyle. great explanation
Thank you for the explanation
Thank you sir, this is a very important video
we love not only your course😁
Beautiful explanation
Thanks Kyle! Best tutorial ever!
Bruh atleast watch the full video.
He said 5 mins not 18 seconds
Video came out 2 minutes ago. How have you even watched it so quickly smh
Yeah right
@@adarsh-chakraborty I'm watching the full video, but I'm always here in the comments section commenting, as always.
Great explanation :)
one year later and the video is still awesome
love your explanation❤
You are really dope at explaining
You are awesome, thank a lot
Please do more on closures and other weird parts of js
Very basic, but it's always good to refresh your basics
Thank you 🌻
More in depth hoisting is due to LFS = RHS reference, javascript act as compiler where they will define LFS (left hand side) first prior code execution
great video. didn't know that. may want to implement it. but can you also make a deep dive into this topic and talk about how this works in a framework like react? like react encapsulate code to components but does hoisting breech that boundry?
but why are the line numbers not displayed? and why are you not using ALT + [Up/Down] to move lines? Kevin has a video about it ;)
I know there is a lot of recent hate for var because const and let are more precise in their scoping. That said, in my opinion, there are still valid use cases for choosing var over let. If you want to make sure a variable or variable-function is always scoped globally, var is still a good way to go. That, of course, gives rise to the argument against the use of globals in general but that's a separate debate. Global scoping actually removes code complexity if you use it properly and sparingly.
Ty sir!
Great job bro
Pro tip: You can use ALT + up/down to move line of code up or down instead of cutting and pasting
Btw very good video, it really helped to understand the topic
@Jojo there's nothing wrong with saying you can do this... anyway, protip: get out and talk to some real people
@Jojo i wonder why you thought of saying this
@Jojo I wonder if your name is a jojo reference
You can press alt and wherever you click will be cursor
Or was it ctrl 🤔
@@fluffyniki3257 You made me think again. I checked again and it is definitely ALT. Pressing Ctrl does not move line. It only moves screen up/down
Helpful 💕
brooooooooooo..........you can explain so nicely!
Hey kyle, I am big fan the way you describe the issue, many ideas and pr i resolved after watching your tuts, I have an request can you make a tutorial on @mentions, that we find on any chat app, how we can do this?
Thanks very much for your effort.
Thanks!
Good simplified explanation. Brad at Traversy Media deep dives the JavaScript engine in his JavaScript Under The Hood series if you want a more thorough understanding of hoisting
have u got a link mate?
@@noy1009 ruclips.net/video/Fd9VaW0M7K4/видео.html
I read in the O'Reilly book that even import statements are hoisted:
10.3.2 ES6 Imports
"By near-universal convention, the imports needed by a module are placed at the start of the module. Interestingly, however, this is not required: like function declarations, imports are hoisted to the top, and all imported values are available for any of the module's code runs."
Effective explanation
Hey Kyle...awesome lesson. Thanks. Can you tell me how you skipped using semicolons in your file.
Thanks Kyle
Thank you
As always aswome video.
thanks man
Thankyou sir
What happens with functions declared inside another (possibly arrow) function, like in React components?
I guess they get "moved" to the top of the scope defined by the react component, but I'm not sure about that
That is correct. Arrow functions will not move to the top of the scope, but normal functions will move to the top of the current scope.
Actually i can say this is very important because i was having interview about hoisting and they gave me the same tricky questions
It's a very popular question on javascript interview
I didn't know people got confused on this. It's really a simple concept.
Kyle's whole mission with WDS, as the name suggests, is to simplify otherwise complex concepts. That said, in this case, even though I'm a fan, and subscriber, and patron, he may have oversimplified this one. There are specific valid reasons why there is confusion on this issue. Over the many years of Javascript's evolution and maturation, there are inconsistencies that manifest in all kinds of counterintuitive and seemingly unpredictable ways. Hoisting is one of those aspects where a developer can get unexpected sometimes erratic results if they don't have a firm grasp. Kyle attempted to do something very ambitious here, which is to try and present an incredibly complex concept AS IF it was simple. That said, if you truly want to understand hoisting, a better approach is to learn how the interpreter works. Specifically, how the file is parsed and memory is allocated ahead of execution. If you acquire a firm grasp of the Execution Context, everything else kind of clicks into place.
thank you
Good to know this concept …
can you pls cover the concept on how javascript frameworks recognise custom html tags without actually using inbuilt browser’s custom element registry …
We are trying to create a web application in vanilla JS where we are trying to leverage the idea of directives/components in modern frameworks.
If you don't want to use a framework I'd recommend using web components.. frameworks just use JS to write HTML, CSS that the browser can render..
The way how hoisting works is that there is a creation phase when the code is executed where all declare values in certain scope are initilize. There is no moving code around.
Regardless, this creation phase is hidden from the programmer. It is essentially a program that runs outside your program which you can't switch off.
Let & const are also hoisted but you got reference error by calling inside temporal dead zone. & JavaScript doesn't move any function at top of file it gets parsed into the memory while memory allocation process.
Thanks.
perfect!
Thanks
Thanks man 😅
I understood hoisting just from the thumbnail alone :o
Coming from Java, this makes absolutely sense :)
yo, you got any guitar videos? I’d love to see web dev simplified shred it up haha
Doesn't this make using the function keyword somewhat superior to declaring functions with const? Except for being hip and ES6, what are the advantages to using const?
Not changing 'this' when needed, for example if 'this' is something else than window
Thank u ,
Teach a man how hoist and he will have func for life
perfect as ever you
This is a common interview question!!
and now that you spoke about hoisting, can you talk a bit about hosting - ie websites to host for beginners please.
Named function doesn't get moved to the top of the file rather it's copied within the memory itself and the same for const and let, it's just they are not assigned a value until and unless the program run.
The steps are like 1. copy named functions and all the const, let and var to the memory
2. then run the run code from the memory
Love you bro 🥰🥰🥰🥰
Hoisting is a made up term that doesn't exist anywhere in the ECMAScript specification. It is a useful shortcut to explain why you can reference functions before their initialization but that's all it really is. The actual reason for this behavior is due to the two phases of the JavaScript interpreter. Here's a lot better explanation of "hoisting" by Brad on Traversy media: ruclips.net/video/Fd9VaW0M7K4/видео.html
Really useful, thanks for sharing it.
You're quite right. If more developers understood the phases of the Global Execution Context, we wouldn't need terms like "hoisting." To your point, telling developers that hoisting is the equivalent of moving declarations to the top of the file, while easy to grasp, is also an incredibly inaccurate explanation of what's actually happening. In many ways, it fuels the confusion on this subject. Here I have the quirky advantage of being old. For a long long time, ALL interpreters needed a separate memory creation phase that preceded code execution. You had to know up front if you had enough memory to to store and act upon your objects and methods, otherwise there was no point in proceeding to runtime and very likely overflowing the execution stack. It's something young developers pretty much never need to think about or concern themselves with because memory space is generally so abundant, stable, and dirt cheap. That said, it consistently explains everything a modern developer would ever need to know about what we collectively call hoisting. By the way, technically, const and let ARE also "hoisted" to memory but just not to the global scope. They are waiting patiently for us in a special allocation we used to call "reserve memory" or a "reserved block" - what the official ECMA spec hilariously calls the "Temporal Dead Zone." But that's a whole other conversation. Cheers! ...and thanks for your great comment.
This video feels emotionally motivated
Which isn't a bad thing if it is
In fact, i think that var is hoisted with declaration, no with initalization like you said var a = undefined. I think that hoisting do that on declarations of variables and fuctions, except let and cost cuz they get stuck in temp deadzone.
It's something like this when var is hoisted:
var a; (its undefined but i think its look like this, without initialization)
clg(a);
a = 2;
And one more, hoisting is linked with scope, so hoisting is concept where declarations are moved up on top of their scope!
I think he meant that all var identifiers get initialized to the value undefined sometime before the thread of execution begins
Hi Kyle, if you have two functions, which one are going to be at the very top?
For example:
function first (){
second()
};
function second () {
//Do something
};
Is the order matters?
Very good question. TLDR: the order doesn't matter.
If we're being technical, javascript doesn't move code around, that's just a way some people try to explain the phenomenon they perceive when it gets executed. It also doubles as a way to hide complexity from beginners.
First, let's start with some terminology to ease understanding:
There are 2 related concepts here, variable declaration and variable initialization. when both happen at the same time, we call it variable definition.
examples:
- var myDeclaration= function funcExpression() { // do something } // this is a variable definition
- let myDeclaration2// this is a variable declaration
myDeclaration2 = "initialization" // this is a varaible initialization (as in 1st ever assignment for a variable)
- const varDeclaration3 = () => { // do something } // another variable definition
- function funcDeclaration() { // this is a function declaration
// do something...
}
With that out of the way, javascript code goes into 2 phases. Without getting too much into details, JS actually reads the code multiple times (1st phase, compilation) and then runs it (2nd phase, execution). By the time the code finishes compiling, all the information about variable declarations in your code has been stored (what the specification calls the variable environment).
So by the time your program starts getting executed (line 1), it already knows both first and second.
So when 'var' is used, js lets ('let' lol) all the code know it. but unlike the function, the variable can be changed in any line, so until then the compiler set it to undefined.
@@eliyahury8847
Yes, 'var' declared variables get auto initialized to undefined, unlike 'let' and 'const' ones.
What you're describing when refering to functions (variable not being able to change values) is actually the difference between const declarations (prevents reassignment) and all the other types (function declarations included).
in fact, the keyword 'function' is just a special way to declare a variable and give it a function as a value at the same time. You may have noticed from what it does that it's just a variable definition, and you'd be 100% right.
You can reassign a new value to it if you want to. Example:
function myVar () { console.log('hi') }
myVar() // hi
myVar = 'hello'
console.log(myVar) // hello
myVar() // TypeError: myVar is not a function
Unrelated to hoisting, but I have a question: Would it be considered good/ bad practice to check if an array is empty, before executing a foreach? (I would currently consider this to be unnecessary)
I ask this in the context of a loop, trying to optimise efficiency. Example: { if (array.length === 0) return; array.forEach(index => index.run) }
Thanks in advance :)
I am 99% sure there is no need to do that, performance cost for that is so extremely small
The real lesson here is to use const to define functions so that you don't get unexpected or confusing behavior, as you highlight at 1:18
make more videos like this.....
Do you play the guitar intro in your videos?
i kinda understanded hoisting before this video, but now i understand it completely (me dumb basically)
So what's the advantage of using const for functions? Only when you don't want it hoisted and if so when would that be?
My opinion:
1. Consistency with the rest of the syntax. Treat functions as any other type (string, number, object, etc.). I like to only use arrow functions in my code.
2. No function scope. Virtually everyone agrees that we shouldn't use 'var', so let's apply the same standard to functions.
3. Arrow functions doesn't bind 'this'. 'this' has a lot of weirdness and I find it easiest to just not use it at all. That means no usage of 'function', 'new', or 'class'. These features are just not needed. Use closures instead. Closures is largely what makes JavaScript an amazing language.
There's generally no reason to hoist stuff. When you export arrow functions from modules, the order of the function declarations doesn't matter anyways. When you declare functions within another function, just use arrow functions and limit yourself to block scopes. So I'd only use arrow functions and never use 'function'.
@@majorhumbert676 thanks for awesome reply. It's cool when people are so helpful just to be nice
@@nickthequick13 It's my pleasure
My work uses an old version of a js framework that can't be transpilled. And we require IE support.
So we have to use var instead of let and const in our legacy front end.
awesome