Learn MORE JavaScript on the ServiceNow Platform: Lesson 3 - More on scope
Hello Brilliant minds in this session
of Learn more JavaScript on the ServiceNow platform, we're going to do a really,
really quick lesson on scope. Scope as in JavaScript scope,
not scoped applications in ServiceNow. Scope can be a pretty subtle concept,
but it's a vital concept for mastering JavaScript. Let's get scoped in. Okay. Anyways, so scope in JavaScript determines
the accessibility of variables and functions
at various parts of your code. We have the global scope
and we have a local scope. So let's kind of
look in on this demonstration real quick. So I have this variable I'm declaring it's a I'm calling it
“I am global” as a string, and if I go into a function
and create a new variable called local variable,
and I call it “I am local”, if we call both of them,
you'll see that both of them appear. So I'm going to do a log statement
of global variable and it prints out properly. I'll do a log statement of local variable
and it prints out properly. Then I will go ahead and call the same
two variables outside of that function
and see what happens. So you'll see first two happens normally, the ones that were called
inside the function, and then I call them again outside
of the function, the global worked, but then the local variable through not just resulted it
an undefined actually through an error. It made the
you made the entire code stop running. And if you look back, it's
because of scope. This variable local variable
was defined within this function, so it automatically becomes
a local variable. It's not accessible to your entire script,
it's only accessible within that function. So when I called it down here, outside of the function,
it basically stopped the code. So something we need to know and something you will encounter
probably a lot in the future. But it's a good quick lesson. I'll see you next time.
https://www.youtube.com/watch?v=Y9GLxf8sfNI