Deep JavaScript Foundations, v3

Hoisting Exercise

Kyle Simpson

Kyle Simpson

You Don't Know JS
Deep JavaScript Foundations, v3

Check out a free preview of the full Deep JavaScript Foundations, v3 course

The "Hoisting Exercise" Lesson is part of the full, Deep JavaScript Foundations, v3 course featured in this preview video. Here's what you'd learn in this lesson:

Students are instructed to refactor existing code to take advantage of hoisting.

Preview
Close

Transcript from the "Hoisting Exercise" Lesson

[00:00:00]
>> Kyle Simpson: In this hoisting exercise, you're gonna get a chance to practice with that idea of bringing functions out of their scopes if they don't need to be nested, or using functions at the bottom of scopes. That sort of thing like we've just talked about in the lecture, you're gonna get a chance to practice with that.

[00:00:17]
So we're gonna take an existing code base that already uses a variety of function expressions, and we're going to refactor that code base using our newfound knowledge of hoisting, our ability to change the way that it's written. We're not changing any behavior, we're just simply changing the coding style.

[00:00:37]
If you look at the current version of it, It looks like this. We have a set of function declarations and inline function expressions, and there are several places where we have inline function expressions that don't really need to be inline function expressions. Once such example, right here. That function expression isn't using any of the lexical variables around itself, so there's no particular reason to inline it, other than maybe just a style preference.

[00:01:07]
But there's no mechanical reason to do so. So using what we know about function declarations and function hoisting, let's pull that one out. So you look for those examples where functions can be pulled out to an outer scope, if they don't need to be nested, that makes simpler and flatter scope structure.

[00:01:27]
And the simpler and flatter the scope structure you have, the easier it will be to read and understand. The more nested it is, the harder it is to keep track of all those boundaries. Also, you'll notice that all the executable code is at the bottom of this program.

[00:01:42]
And what we learned about function hoisting is that we can put executable code at the top, and all the functions at the bottom. So your task is to sort of refactor, or rearrange, these functions, pull them out where necessary, And refactor this code so that it uses or leverages the benefits of function hoisting.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now