Understanding Scopes in JavaScript.

Scope and hoisting is one of the most important concepts to learn in JavaScript. And that’s what we are going to do in this article today.

Scope

In simplest words, scope means where to look for a particular thing.

Let’s take an example.

Imagine a river visible to people in your country only, that river is in the Local Scope of your country.

Whereas on the other hand, the moon is visible from everywhere on earth. The Moon is in the Global Scope of earth.

Right there you got the concept of local and global scope.

In Context of JavaScript.

Any code of JavaScript available everywhere is in global scope. Any variable or function inside a block of code can’t be accessed outside of that block of code.

Exception:

“var” creates a block of code only inside the function, but “let” and “const” creates a block of code everywhere.

There are few default globals in the browser environment of JS. For example Windows and Document.

var name = ‘Swastik’

// Variable “name” is in global scope. It is available everywhere.

function name() {

  var petName = ‘Bittu’

  return petName

}

console.log(petName) // Error: Variable “petName” is not defined.

// Because it is in the local scope of the function name.

var, let & const.

Look at the code below.

console.log(a) // Undefined

var a = ‘A’

console.log(b) // Error: “Cannot access ‘b’ before initialization”

let b = ‘B’

Notice that the first two lines of code didn’t give an error but ‘Undefined’ and the last two lines didn’t complain that b is not defined. That’s because of hoisting and initialization.

The worst thing you could have in programming is magic.

The secret behind this magic is Hoisting. Variables become available before their declaration, that’s all hoisting is.

But why does JavaScript behave like that? We will dive into that question in the next article about Execution Context.

If you have any question about difference b/w variable types, then here is your answer.

 

Variable TypeHoistingReAssignmentReDeclarationInitialization
var
let
const

 

Happy Coding.

 

Leave a comment