14 Javascript Variable scoping – JavaScript for Beginners

Learn Javascript from Scratch

Last updated on June 30th, 2018 at 09:46 pm

 

This video is taken from the full course that will teach you HTML, CSS, Programming concepts and Javascript .

Video Transcript:

 

Hey, and welcome back.

So in the last video we said that we’re going to look at variable hoisting.

But before that, we need to look at variable scoping.

So scoping basically defines how a variable is usable.

Watch Full Course >>

Is it a local variable or a global variable.

A global variable is accessible in the entire document.

Any part of the document that you go to, and by document I mean a ‘.js’ file that has lots of JavaScript code.

So that’s what I’m calling and referring to as a document in this case.

So you may find that a document may have functions and may also have something like an ‘if’ block.

So in this case, this is an ‘if’ block.

So this ‘if’ block has its scope.

So the scope of this ‘if’ block ends, it ends where this final closing bracket ends.

So, in a normal programming, in other programming languages, if this was the case, this variable would be what is called a local variable.

It would only be accessible within this block.

That makes it a local variable.

But if it was defined outside of this block and outside of any function, it would be a global variable that is accessible by any other function or by any other ‘if’ block or by any other thing that wants to use that variable.

As long as it is not defined within a function or within an ‘if’ block or any other kind of block like ‘else’ block, it is a global variable.

So JavaScript as you know is a very loose language.

And if you use the ‘var’ keyword, this variable will, will be accessible from outside of this block.

So the scope of this to some extent is a global variable.

If this was something like Java and this was a class, this variable would not be accessible from outside of this block.

In Java we have public variables, protected variables and private variables.

So unless it was declared as a public variable, it would not be able, it will not be accessible from outside of this block.

So I hope you do understand what scoping is.

And in the next video, let’s look at an example of this.

Let’s look at an example of this and see how variables are accessible outside of the block.

Watch Full Course >>

 

This section is from Learn Javascript from Scratch.

Learn Javascript from Scratch

Comment Here