Learn JavaScript Hoisting In 5 Minutes

  Рет қаралды 132,445

Web Dev Simplified

Web Dev Simplified

Күн бұрын

Пікірлер: 226
@WebDevSimplified
@WebDevSimplified 2 жыл бұрын
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.
@fluffyniki3257
@fluffyniki3257 2 жыл бұрын
I bet it took you to write this comment longer than making this video 😆
@yuvalazaria
@yuvalazaria 2 жыл бұрын
Thanks for the extra info Kyle!
@WebDevSimplified
@WebDevSimplified 2 жыл бұрын
@@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.
@evangeloskolimitras5276
@evangeloskolimitras5276 2 жыл бұрын
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.
@kenkletzien1210
@kenkletzien1210 2 жыл бұрын
Great stuff, as always, Kyle. Just fyi, the expression is "for all intents and purposes."
@StrayKev
@StrayKev 2 жыл бұрын
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
@Issvor
@Issvor 2 жыл бұрын
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
@ashy7198
@ashy7198 2 жыл бұрын
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?
@StrayKev
@StrayKev 2 жыл бұрын
​@@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: kzbin.info/www/bejne/fJWch5SNZbJqgZY
@ashy7198
@ashy7198 2 жыл бұрын
@@StrayKev yes! That does make sense thanks for clearing that up for me 🙂
@memoryleakerz
@memoryleakerz 2 жыл бұрын
@@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 :)
@buondevid
@buondevid 2 жыл бұрын
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
@alexjohnson-bassworship3150
@alexjohnson-bassworship3150 2 жыл бұрын
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!
@boxboxerson991
@boxboxerson991 2 жыл бұрын
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.
@traceuse13
@traceuse13 2 жыл бұрын
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.
@colinb8332
@colinb8332 2 жыл бұрын
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.
@mudassirakhter6605
@mudassirakhter6605 2 жыл бұрын
Exactly 💯
@dopetag
@dopetag Жыл бұрын
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.
@theisoj
@theisoj 2 жыл бұрын
Thanks Kyle! Best tutorial ever!
@adarsh-chakraborty
@adarsh-chakraborty 2 жыл бұрын
Bruh atleast watch the full video. He said 5 mins not 18 seconds
@cresent6568
@cresent6568 2 жыл бұрын
Video came out 2 minutes ago. How have you even watched it so quickly smh
@anipezalt4422
@anipezalt4422 2 жыл бұрын
Yeah right
@theisoj
@theisoj 2 жыл бұрын
@@adarsh-chakraborty I'm watching the full video, but I'm always here in the comments section commenting, as always.
@Rafps3player
@Rafps3player 2 жыл бұрын
As always super clean and concise in explaining the concepts; you are great!
@kenbinta2246
@kenbinta2246 2 жыл бұрын
A daily dose of Web Dev Simplified makes one a better programmer
@marna_li
@marna_li 2 жыл бұрын
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.
@bryanthompson1070
@bryanthompson1070 2 жыл бұрын
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
@noy1009
@noy1009 2 жыл бұрын
have u got a link mate?
@bryanthompson1070
@bryanthompson1070 2 жыл бұрын
@@noy1009 kzbin.info/www/bejne/fJWch5SNZbJqgZY
@citlaliserratos6066
@citlaliserratos6066 4 күн бұрын
Comment made after watching a useful video so I don't forget what it was about #1. So, hoisting is like a hierarchy that JavaScript follows when some code is running, I mean, functions and var come on top of everything even when those are declared later butt const, let and more are the mortal ones and have to wait for their turn and, if they're called before they are declared, there's an error.
@robertholtz
@robertholtz 2 жыл бұрын
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.
@mohibniazi4797
@mohibniazi4797 Жыл бұрын
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
@mrxgamer7567
@mrxgamer7567 Жыл бұрын
very clean explaination !
@vivekkumar36732
@vivekkumar36732 2 жыл бұрын
Very basic, but it's always good to refresh your basics
@archrodney
@archrodney 2 жыл бұрын
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."
@ukaszzbrozek6470
@ukaszzbrozek6470 2 жыл бұрын
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.
@Tubeytime
@Tubeytime 5 ай бұрын
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.
@josephlivengood4508
@josephlivengood4508 2 жыл бұрын
What I learned... Do not use the var to define a variable but const and let. Thank you sir, great content as always!
@Sartaj.MarvelMinds
@Sartaj.MarvelMinds Ай бұрын
Functions are not moved to the top but it's declaration is hoisted to the top, the function code remains where it is.
@alwysrite
@alwysrite 2 жыл бұрын
and now that you spoke about hoisting, can you talk a bit about hosting - ie websites to host for beginners please.
@Eeebee392
@Eeebee392 2 жыл бұрын
You are the best coding teacher on youtube👍👍
@jim4nz
@jim4nz 2 жыл бұрын
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
@syedsaadali6765
@syedsaadali6765 2 жыл бұрын
I understood hoisting just from the thumbnail alone :o
@jnsjknn
@jnsjknn 2 жыл бұрын
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: kzbin.info/www/bejne/fJWch5SNZbJqgZY
@Laura69
@Laura69 2 жыл бұрын
Really useful, thanks for sharing it.
@robertholtz
@robertholtz 2 жыл бұрын
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.
@nitigyajoshi4658
@nitigyajoshi4658 2 жыл бұрын
brooooooooooo..........you can explain so nicely!
@urjaangre2216
@urjaangre2216 5 ай бұрын
Clear and to the point explanation. Thank you soo much!
@funstories728
@funstories728 Жыл бұрын
You are really dope at explaining
@amgdeg4897
@amgdeg4897 2 жыл бұрын
This video feels emotionally motivated Which isn't a bad thing if it is
@Sindoku
@Sindoku 2 жыл бұрын
let and const are hoisted, it’s just they don’t get assigned a default value like var does. It’s an incredibly small detail, but it’s worth nothing if you truly want to understand hoisting.
@ajzack983
@ajzack983 2 жыл бұрын
Thank u , Teach a man how hoist and he will have func for life
@elhadjbabacarcisse2868
@elhadjbabacarcisse2868 2 жыл бұрын
Thank u so much. I was planning to learn about it but with this video i'm pretty sure i understand it all
@marimuthur9456
@marimuthur9456 2 жыл бұрын
It's very easy to understand thank you so much for your explanation about hosting 😊👌🏼👌🏼👌🏼👌🏼👌🏼
@elakkiyas7142
@elakkiyas7142 Жыл бұрын
we love not only your course😁
@shashisharma9367
@shashisharma9367 2 жыл бұрын
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
@mssadewa
@mssadewa 2 жыл бұрын
I love this video format! in 5 mins to learns some tricks!
@7heMech
@7heMech 2 жыл бұрын
Thanks.
@jfirestorm44
@jfirestorm44 2 жыл бұрын
Well I learned something new today. Thanks for the great vid.
@eitanwaxman1862
@eitanwaxman1862 2 жыл бұрын
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?
@symix.
@symix. 2 жыл бұрын
Not changing 'this' when needed, for example if 'this' is something else than window
@lakhveerchahal
@lakhveerchahal 2 жыл бұрын
Very nicely covered all important points. Thanks Kyle.
@BostYT
@BostYT 2 жыл бұрын
I didn't know people got confused on this. It's really a simple concept.
@robertholtz
@robertholtz 2 жыл бұрын
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.
@AniMason-Animation
@AniMason-Animation 2 жыл бұрын
Good at teaching code and styling your hair. Very informative video with great explanations:)
@bertlemoi431
@bertlemoi431 2 жыл бұрын
does hoisting breech the encapsulation barrier of frameworks like react/angular/etc? and please watch kevin's video about moving lines up and down (ALT + UP/Down to move the line up/down one line). it's driving me nuts haha
@devl0ver666
@devl0ver666 4 күн бұрын
i really like your videos bro
@glorysinkhonde197
@glorysinkhonde197 Жыл бұрын
Thank you so much for this... simple to understand
@ramiworkstation
@ramiworkstation 3 ай бұрын
Thank you 🌻
@skjahir7365
@skjahir7365 Жыл бұрын
Great explanation :)
@chinemelumelombai5537
@chinemelumelombai5537 2 жыл бұрын
Straight to the point as always. Nice one 👍
@jenso413
@jenso413 2 жыл бұрын
yo, you got any guitar videos? I’d love to see web dev simplified shred it up haha
@glitchinLife
@glitchinLife 2 жыл бұрын
Great explanation with very straight forward examples👌
@abhis3kh
@abhis3kh 2 жыл бұрын
Thanks man. Really simplifies
@basiccodingwithadam8125
@basiccodingwithadam8125 2 жыл бұрын
Great job, as usual, Kyle!
@SaidElnaffar
@SaidElnaffar 9 ай бұрын
Amazing! Simple and easy!
@fredca7178
@fredca7178 8 ай бұрын
This was great! Thank you very much
@KeeBeeTz
@KeeBeeTz 2 жыл бұрын
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!
@lunify2814
@lunify2814 2 жыл бұрын
I think he meant that all var identifiers get initialized to the value undefined sometime before the thread of execution begins
@sebastianbraun2473
@sebastianbraun2473 2 жыл бұрын
Coming from Java, this makes absolutely sense :)
@darkknight7623
@darkknight7623 9 ай бұрын
Thank you sir, this is a very important video
@meqativ
@meqativ 2 жыл бұрын
i kinda understanded hoisting before this video, but now i understand it completely (me dumb basically)
@Key-yf3ou
@Key-yf3ou Жыл бұрын
You are awesome, thank a lot
@koffworld7857
@koffworld7857 Жыл бұрын
Thank you for the explanation
@moheaali2049
@moheaali2049 11 ай бұрын
let and const variables are hoisted, only they are hoisted without a default initialization.
@olga_lc
@olga_lc 2 жыл бұрын
Thanks, I didn't know it was called 'hoisting'
@Fratilitau
@Fratilitau 2 жыл бұрын
U rule bro! Keep up the awesome work!
@bertlemoi431
@bertlemoi431 2 жыл бұрын
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 ;)
@maciejmotochannel
@maciejmotochannel Жыл бұрын
Great job bro
@rahimrahim2720
@rahimrahim2720 2 ай бұрын
thank you
@ДмитрийКарпич
@ДмитрийКарпич 2 жыл бұрын
And moral of this story - always use linter at strict mode, and don't anything creepy in you code, moreover at you teem code. Write so simple, that every junior developer can understand you code without disturbing you.
@kevinbatdorf
@kevinbatdorf Жыл бұрын
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
@nickthequick13
@nickthequick13 2 жыл бұрын
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?
@majorhumbert676
@majorhumbert676 2 жыл бұрын
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'.
@nickthequick13
@nickthequick13 2 жыл бұрын
@@majorhumbert676 thanks for awesome reply. It's cool when people are so helpful just to be nice
@majorhumbert676
@majorhumbert676 2 жыл бұрын
@@nickthequick13 It's my pleasure
@bryanDevsJS
@bryanDevsJS Жыл бұрын
great video can you give me roadmap for javascript I want to be a backend devs with this javascript spell
@pranavwani
@pranavwani 2 жыл бұрын
Thank you
@aram5642
@aram5642 2 жыл бұрын
To be precise, it's not about top/bottom of the file, but instead - of the block scope. In the following example: function sum(a,b){ log('computing...') return a + b function log(msg){ console.log(msg) } } log('no way Jose!') log will not be available outside of sum, it will only be hoisted within its scope.
@WebDevSimplified
@WebDevSimplified 2 жыл бұрын
That is correct, but in general the code runs top to bottom ignoring different blocks. This is meant to be a really basic video on Hoisting and if I went into scoping that would only complicate the video I feel.
@aram5642
@aram5642 2 жыл бұрын
@@WebDevSimplified Sure thing, I understand that. Appreciate your content!
@doniaelfouly4142
@doniaelfouly4142 Жыл бұрын
Thanks
@danachen2063
@danachen2063 Жыл бұрын
love your explanation❤
@afokerealityigho9003
@afokerealityigho9003 5 ай бұрын
thanks man
@u-codegate1239
@u-codegate1239 2 жыл бұрын
why i love HTML & CSS & JS
@aravindgop1
@aravindgop1 2 жыл бұрын
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.
@DevMeloy
@DevMeloy 2 жыл бұрын
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..
@alexgolomb363
@alexgolomb363 6 ай бұрын
Do you play the guitar intro in your videos?
@8siaix
@8siaix Жыл бұрын
you got a Jackson, you are aa Metaliprogrammer
@maniac1441
@maniac1441 2 жыл бұрын
Helpful 💕
@petrmai9152
@petrmai9152 2 ай бұрын
OH! MY! GOD! WOW! just WOW!
@das6109
@das6109 Жыл бұрын
Is a function defined in another function hoisted?
@emmanuelxs6143
@emmanuelxs6143 2 жыл бұрын
Thanks man 😅
@EngineBoy
@EngineBoy 2 жыл бұрын
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.
@Noritoshi-r8m
@Noritoshi-r8m 2 жыл бұрын
Ty sir!
@Arabian_Abomination
@Arabian_Abomination 2 жыл бұрын
Thanks Kyle
@ibrahim_youssef_13.12
@ibrahim_youssef_13.12 Жыл бұрын
perfect as ever you
@shortsScroll
@shortsScroll 6 ай бұрын
Love you bro 🥰🥰🥰🥰
@eliyahury8847
@eliyahury8847 2 жыл бұрын
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?
@lunify2814
@lunify2814 2 жыл бұрын
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.
@eliyahury8847
@eliyahury8847 2 жыл бұрын
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.
@lunify2814
@lunify2814 2 жыл бұрын
@@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
@kaziupir
@kaziupir 2 жыл бұрын
Actually it doesnt move any code, but reads code before running and save in memory.
@yukimoe
@yukimoe 2 жыл бұрын
All this time I thought undefined variables just return undefined, but actually they only return undefined if you declare it somewhere otherwise that's an error
@lararawf6100
@lararawf6100 2 жыл бұрын
God bless you
@sak1b
@sak1b 2 жыл бұрын
If anyone wants to deep dive just look for "namaste js"
@grumpylibrarian
@grumpylibrarian 2 жыл бұрын
I would strongly recommend avoiding this. Hoisting is going to make your code harder to read. It's right up there with "import *" and global variables in making it really hard to see where a particular function or variable comes from. When ES6 introduced class declarations, they did remember to not allow hoisting even when done as a declaration ("class MyCLass{") instead of an expression ("const MyClass=class{"). They then went and immediately blew it by allowing blind imports with "import *" that obscure from which module an asset was imported. There's another problem with using the "function" keyword in general, either as declaration or expression: they can be treated as either methods or constructors. Especially for functions exported out into the big scary real world, you should allow a function to be a constructor OR a method, and never both. Class constructors will throw an error if they're called without the "new" keyword. Arrow functions will throw an error if called with the "new" keyword. What some gentle viewers might or might not know is that class methods and object methods also with throw errors if used with "new": class MyClass{ constructor(){ //This will throw if not called with "new" } aMethod(){ //This will throw if called with "new" even if separated from the class //such as with "const aMethod=MyClass.prototype.aMethod;new aMethod()" } } const someObject{ bMethod(){ //This will also throw if called with "new" even if separated from the object }, cMethod: function(){ //This will NOT throw if called with "new" because it's a pointer to a function //and not a class/object method }, } function dFunction(){ //This will not throw if called with or without "new" } const eArrow=()=>{ // this will throw if called with "new" } Arrow functions are a good idea for general-purpose methods. They have the characteristics of A) lexical (code-position) inheritance of "this" and B) inheritance of the "arguments" variable from the lexical scope as well. These are often either desired or not a problem, which is good, because JavaScript doesn't have a clean way to make just a method otherwise. I've used a few patterns, and this is ugly but as good as any: const {method}={method(){ // this will throw if called with "new" }} Finally, this can't be done with generators or async generators, and they're all technically constructors as they create the iterator object. Fortunately, "new" doesn't work with them, and you'll likely get a "not a constructor" error even though it is internally. The "this" value will even kindly work properly, even though the iterator object is not the same as the object holding the generator.
@robiparvez
@robiparvez 2 жыл бұрын
awesome
@aryansharma8794
@aryansharma8794 2 жыл бұрын
It is good but also Watch Akshay saini series on javascript
@Tubeytime
@Tubeytime 5 ай бұрын
JS dev: I made this language that lets you write your own code! JS dev: also it changes your code without your consent! 😈
@jasnar.1870
@jasnar.1870 11 ай бұрын
💜
@naumansulaiman8856
@naumansulaiman8856 2 жыл бұрын
Kyle, ignore the idiots posting the criticism. If they know this stuff they dont even need to be watching this vid
@charlesngerem3198
@charlesngerem3198 2 жыл бұрын
Kyle to 1m
@DevMeloy
@DevMeloy 2 жыл бұрын
I don't think you're correct that const not being hoisted.. if that was true the error would be a reference error, not an initialize error.. const must be initialized;
Learn JavaScript Scoping In 10 Minutes
11:39
Web Dev Simplified
Рет қаралды 61 М.
Spongebob ate Patrick 😱 #meme #spongebob #gmod
00:15
Mr. LoLo
Рет қаралды 16 МЛН
АЗАРТНИК 4 |СЕЗОН 3 Серия
30:50
Inter Production
Рет қаралды 1 МЛН
Speed Up Your React Apps With Code Splitting
16:50
Web Dev Simplified
Рет қаралды 383 М.
Learn JavaScript DOM Traversal In 15 Minutes
14:44
Web Dev Simplified
Рет қаралды 225 М.
How to Learn to Code FAST (Do This or Keep Struggling)
11:00
Andy Sterkowitz
Рет қаралды 708 М.
JavaScript Prototypal inheritance - Tutorial
15:29
ColorCode
Рет қаралды 78 М.
100+ Web Development Things you Should Know
13:18
Fireship
Рет қаралды 1,5 МЛН
JavaScript Visualized - Event Loop, Web APIs, (Micro)task Queue
12:35
8 Must Know JavaScript Array Methods
10:05
Web Dev Simplified
Рет қаралды 1 МЛН
Mindset of Successful Programmers
4:56
bigboxSWE
Рет қаралды 1 МЛН
5 JavaScript Concepts You HAVE TO KNOW
9:38
James Q Quick
Рет қаралды 1,4 МЛН
Spongebob ate Patrick 😱 #meme #spongebob #gmod
00:15
Mr. LoLo
Рет қаралды 16 МЛН