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

Комментарии • 224

  • @WebDevSimplified
    @WebDevSimplified  2 года назад +152

    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 года назад +22

      I bet it took you to write this comment longer than making this video 😆

    • @yuvalazaria
      @yuvalazaria 2 года назад +2

      Thanks for the extra info Kyle!

    • @WebDevSimplified
      @WebDevSimplified  2 года назад +45

      @@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 года назад +8

      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."

  • @colinb8332
    @colinb8332 2 года назад +107

    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 года назад +1

      Exactly 💯

    • @dopetag
      @dopetag Год назад +1

      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.

  • @StrayKev
    @StrayKev 2 года назад +105

    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 года назад +8

      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 года назад +11

      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 года назад +5

      ​@@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

    • @ashy7198
      @ashy7198 2 года назад +1

      @@StrayKev yes! That does make sense thanks for clearing that up for me 🙂

    • @memoryleakerz
      @memoryleakerz 2 года назад +1

      @@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 :)

  • @Rafps3player
    @Rafps3player 2 года назад +4

    As always super clean and concise in explaining the concepts; you are great!

  • @muhebollahkhandaker
    @muhebollahkhandaker 2 года назад +9

    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.

  • @lakhveerchahal
    @lakhveerchahal 2 года назад

    Very nicely covered all important points. Thanks Kyle.

  • @jossani6712
    @jossani6712 2 года назад +1

    Really good explanation about the topic, also i really love your content, you are helping me become a greater developer, thanks Kyle

  • @chinemelumelombai5537
    @chinemelumelombai5537 2 года назад

    Straight to the point as always. Nice one 👍

  • @urjaangre2216
    @urjaangre2216 3 месяца назад

    Clear and to the point explanation. Thank you soo much!

  • @just_O
    @just_O 2 года назад

    Great explanation with very straight forward examples👌

  • @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

  • @ESArnau
    @ESArnau 2 года назад

    Great explanation Kyle. Thanks for ur content.

  • @mrxgamer7567
    @mrxgamer7567 Год назад +1

    very clean explaination !

  • @SAKSHIKUMARIP
    @SAKSHIKUMARIP Год назад

    u break down evry complex concepts..keep uploading more such js vid.!!!!!! huge respect...

  • @basiccodingwithadam8125
    @basiccodingwithadam8125 2 года назад

    Great job, as usual, Kyle!

  • @ReejohnStellas
    @ReejohnStellas Год назад

    Thanks bruh
    looking forward to see more videos of yours

  • @glorysinkhonde197
    @glorysinkhonde197 Год назад

    Thank you so much for this... simple to understand

  • @buondevid
    @buondevid 2 года назад +8

    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

  • @mssadewa
    @mssadewa 2 года назад

    I love this video format! in 5 mins to learns some tricks!

  • @kenbinta2246
    @kenbinta2246 2 года назад +1

    A daily dose of Web Dev Simplified makes one a better programmer

  • @marimuthur9456
    @marimuthur9456 2 года назад

    It's very easy to understand thank you so much for your explanation about hosting 😊👌🏼👌🏼👌🏼👌🏼👌🏼

  • @alexjohnson-bassworship3150
    @alexjohnson-bassworship3150 2 года назад +1

    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 года назад +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.

  • @fredca7178
    @fredca7178 6 месяцев назад

    This was great! Thank you very much

  • @jfirestorm44
    @jfirestorm44 2 года назад

    Well I learned something new today. Thanks for the great vid.

  • @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

  • @lostc0de555
    @lostc0de555 2 года назад

    Thank you !! very informative

  • @marna_li
    @marna_li 2 года назад +3

    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.

  • @SaidElnaffar
    @SaidElnaffar 7 месяцев назад

    Amazing! Simple and easy!

  • @Eeebee392
    @Eeebee392 2 года назад

    You are the best coding teacher on youtube👍👍

  • @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!

  • @Fratilitau
    @Fratilitau 2 года назад

    U rule bro! Keep up the awesome work!

  • @abhis3kh
    @abhis3kh 2 года назад

    Thanks man. Really simplifies

  • @zdfvbadfbadb
    @zdfvbadfbadb 2 года назад

    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).

  • @AniMason-Animation
    @AniMason-Animation 2 года назад

    Good at teaching code and styling your hair. Very informative video with great explanations:)

  • @WiLDeveD
    @WiLDeveD 2 года назад

    You are rock... Thanks kyle. great explanation

  • @koffworld7857
    @koffworld7857 Год назад

    Thank you for the explanation

  • @darkknight7623
    @darkknight7623 7 месяцев назад

    Thank you sir, this is a very important video

  • @elakkiyas7142
    @elakkiyas7142 Год назад +1

    we love not only your course😁

  • @festusiyere
    @festusiyere 2 года назад

    Beautiful explanation

  • @theisoj
    @theisoj 2 года назад +7

    Thanks Kyle! Best tutorial ever!

    • @adarsh-chakraborty
      @adarsh-chakraborty 2 года назад +4

      Bruh atleast watch the full video.
      He said 5 mins not 18 seconds

    • @cresent6568
      @cresent6568 2 года назад +3

      Video came out 2 minutes ago. How have you even watched it so quickly smh

    • @anipezalt4422
      @anipezalt4422 2 года назад +1

      Yeah right

    • @theisoj
      @theisoj 2 года назад +1

      @@adarsh-chakraborty I'm watching the full video, but I'm always here in the comments section commenting, as always.

  • @skjahir7365
    @skjahir7365 Год назад

    Great explanation :)

  • @stevenrashid5810
    @stevenrashid5810 2 месяца назад

    one year later and the video is still awesome

  • @danachen2063
    @danachen2063 Год назад

    love your explanation❤

  • @funstories728
    @funstories728 Год назад

    You are really dope at explaining

  • @Key-yf3ou
    @Key-yf3ou 10 месяцев назад

    You are awesome, thank a lot

  • @Arabian_Epileptic
    @Arabian_Epileptic 2 года назад +1

    Please do more on closures and other weird parts of js

  • @vivekkumar36732
    @vivekkumar36732 2 года назад +6

    Very basic, but it's always good to refresh your basics

  • @ramiworkstation
    @ramiworkstation Месяц назад

    Thank you 🌻

  • @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

  • @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 ;)

  • @robertholtz
    @robertholtz 2 года назад +10

    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.

  • @Noritoshi-r8m
    @Noritoshi-r8m 2 года назад

    Ty sir!

  • @maciejmotochannel
    @maciejmotochannel Год назад

    Great job bro

  • @yahyasalimi3254
    @yahyasalimi3254 2 года назад +16

    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

    • @TheStruders
      @TheStruders 2 года назад +14

      @Jojo there's nothing wrong with saying you can do this... anyway, protip: get out and talk to some real people

    • @nonnodacciaio704
      @nonnodacciaio704 2 года назад

      @Jojo i wonder why you thought of saying this

    • @TopBagon
      @TopBagon 2 года назад +2

      @Jojo I wonder if your name is a jojo reference

    • @fluffyniki3257
      @fluffyniki3257 2 года назад

      You can press alt and wherever you click will be cursor
      Or was it ctrl 🤔

    • @yahyasalimi3254
      @yahyasalimi3254 2 года назад

      @@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

  • @maniac1441
    @maniac1441 2 года назад

    Helpful 💕

  • @nitigyajoshi4658
    @nitigyajoshi4658 2 года назад

    brooooooooooo..........you can explain so nicely!

  • @niruddhaRoy
    @niruddhaRoy 2 года назад

    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.

  • @Miguel-dg7ql
    @Miguel-dg7ql Месяц назад

    Thanks!

  • @bryanthompson1070
    @bryanthompson1070 2 года назад +8

    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 ruclips.net/video/Fd9VaW0M7K4/видео.html

  • @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."

  • @lubnaarora4946
    @lubnaarora4946 9 месяцев назад

    Effective explanation

  • @hyderabadipunch1152
    @hyderabadipunch1152 2 года назад

    Hey Kyle...awesome lesson. Thanks. Can you tell me how you skipped using semicolons in your file.

  • @Arabian_Epileptic
    @Arabian_Epileptic 2 года назад

    Thanks Kyle

  • @pranavwani
    @pranavwani 2 года назад

    Thank you

  • @Tesseract9630
    @Tesseract9630 2 года назад

    As always aswome video.

  • @afokerealityigho9003
    @afokerealityigho9003 3 месяца назад

    thanks man

  • @gaganpreetsingh4874
    @gaganpreetsingh4874 3 дня назад

    Thankyou sir

  • @martinheywang4962
    @martinheywang4962 2 года назад +2

    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

    • @WebDevSimplified
      @WebDevSimplified  2 года назад +2

      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.

  • @lioraharon6352
    @lioraharon6352 10 месяцев назад

    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

  • @BostYT
    @BostYT 2 года назад

    I didn't know people got confused on this. It's really a simple concept.

    • @robertholtz
      @robertholtz 2 года назад +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.

  • @surakalaanusha7784
    @surakalaanusha7784 Год назад

    thank you

  • @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..

  • @ukaszzbrozek6470
    @ukaszzbrozek6470 2 года назад +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 3 месяца назад

      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.

  • @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.

  • @7heMech
    @7heMech 2 года назад +2

    Thanks.

  • @0hora313
    @0hora313 2 года назад

    perfect!

  • @doniaelfouly4142
    @doniaelfouly4142 Год назад

    Thanks

  • @emmanuelxs6143
    @emmanuelxs6143 2 года назад

    Thanks man 😅

  • @syedsaadali6765
    @syedsaadali6765 2 года назад

    I understood hoisting just from the thumbnail alone :o

  • @sebastianbraun2473
    @sebastianbraun2473 2 года назад

    Coming from Java, this makes absolutely sense :)

  • @jenso413
    @jenso413 2 года назад

    yo, you got any guitar videos? I’d love to see web dev simplified shred it up haha

  • @eitanwaxman1862
    @eitanwaxman1862 2 года назад +3

    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 года назад +1

      Not changing 'this' when needed, for example if 'this' is something else than window

  • @ajzack983
    @ajzack983 2 года назад

    Thank u ,
    Teach a man how hoist and he will have func for life

  • @ibrahimyoussef4489
    @ibrahimyoussef4489 Год назад

    perfect as ever you

  • @topherlions714
    @topherlions714 2 года назад

    This is a common interview question!!

  • @alwysrite
    @alwysrite 2 года назад

    and now that you spoke about hoisting, can you talk a bit about hosting - ie websites to host for beginners please.

  • @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

  • @shortsScroll
    @shortsScroll 4 месяца назад

    Love you bro 🥰🥰🥰🥰

  • @jnsjknn
    @jnsjknn 2 года назад +5

    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

    • @Laura69
      @Laura69 2 года назад +1

      Really useful, thanks for sharing it.

    • @robertholtz
      @robertholtz 2 года назад +3

      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.

  • @amgdeg4897
    @amgdeg4897 2 года назад

    This video feels emotionally motivated
    Which isn't a bad thing if it is

  • @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

  • @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 года назад +1

      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

  • @egosumkasz
    @egosumkasz 2 года назад

    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 :)

    • @symix.
      @symix. 2 года назад +1

      I am 99% sure there is no need to do that, performance cost for that is so extremely small

  • @kevinbatdorf
    @kevinbatdorf Год назад +1

    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

  • @muhammad_abir
    @muhammad_abir 2 года назад

    make more videos like this.....

  • @alexgolomb363
    @alexgolomb363 4 месяца назад

    Do you play the guitar intro in your videos?

  • @meqativ
    @meqativ 2 года назад +1

    i kinda understanded hoisting before this video, but now i understand it completely (me dumb basically)

  • @nickthequick13
    @nickthequick13 2 года назад +1

    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 года назад +1

      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 года назад +1

      @@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

  • @jamesreynolds3167
    @jamesreynolds3167 2 года назад

    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.

  • @robiparvez
    @robiparvez 2 года назад

    awesome