logo

NJP

Learn MORE JavaScript on the ServiceNow Platform: Lesson 4 - Hoisting

Import · Nov 27, 2023 · video

Welcome back, fellow scripters. Today's episode of Learn More JavaScript on the ServiceNow
platform is all about hoisting. Hoisting can cause some head scratching
moments even for experienced developers. So understanding this concept is pretty key to mastering
JavaScript functions and variables. So let's lift the veil on hoisting. Okay. So hoisting is JavaScript’s
default behavior of moving declarations to the top of their scope function
or global before code execution. Despite how it may sound, it's
not a physical movement, but a conceptual one,
both variable and function to declarations are hoisted,
but they behave a little bit differently. So let's see this in action. So as you may have seen in
some of the scripts that you might have seen
in previous videos or in scripts that are around ServiceNow
and all over the place, you can actually write a function and then call that function
before it's actually written. Because what's happening
is when the whole script starts running, it actually goes through and finds
all the things that it needs to hoist to the top. And so functions are one of those things. It's it goes through the entire script
first and says, we don't know when this person
is going to use that function, so let's hoist
that entire thing to the very top so that even if the call for that
function happens before you actually write the script
or when the script is written, it'll still work. And so if I go ahead and execute this code as is, you'll see that it worked. Even though you wrote the function
after the call of that function. And now if we go back and try the same thing with a variable, you'll notice
that it actually doesn't work. So here
we're going to try to call the variable, but the declaration of that variable
actually hasn't happened yet. So it still hoists the variable,
but it doesn't hoist the setting of that variable. So let's run that. You'll see it's undefined now. and that's a very simple difference
between variables and functions as they get hoisted
to the top of your script. See, the next time.

View original source

https://www.youtube.com/watch?v=9qRL78ylw6I