Scope in Javascript

let, const and var explained

Ever been in a situation whereby your 'big name' doesn't grant you any favors anymore? Let's say you went to a club and you wanted to access the VVIP section but on arrival , you get a big ACCESS DENIED slammed on your face. Sucks right? You are required to have a VVIP ticket to access the premises.

"Scope? What is scope? " Well, english defines scope as the extent of the area or subject matter that something deals with or to which it is relevant "And what about JavaScript? " Ahaa , so JavaScript does this, it takes a written program as scope. Don't get lost, stay with me. We have two types of scope i.e Global Scope and Lexical Scope.

Oh dear , don't be frightened by those words.... Global basically means a defined variable can be accessed everywhere. while lexical scope means that there's some restriction. The defined variable has limited access to a particular scop. Remember the scenario at the club, well they kind of are similar.

"So, variables you say?" How are they related to a club and access denial? Well simply put, a variable as stored value which can be later retrieved and modified. Javascript has three types of variable declaratios i.e:

  1. var

    var x = 18
    

    var has been the most common means of variable declaration used since 1995. It therefore withstands all forces and any variable decalred with var can be accessed anywhere in the program. For instance we declared a variable x and assigned to it the value 18 . x can be accessed anywhere.

  2. let

let comes from the word lexical . Variables declared using let are restricted therefore cannot be accessed elsewhere outside the scope. Let's have an example:

function myCity(){
  let city = "Nairobi"
 console.log(city)
}
console.log(city)
myCity()

When you run the above program, you'll get an error ReferenceError: city is not defined meaning that city can only be accessed inside the function scope

3 const

This is not that complicated . const comes from the word constant which refers to defining variables with values that won't change at any time during the scope of the execution

const dog = "Spikey"

In the above case , the dog's value will always be Spikey and if any change is imposed to it for instance,

dog = "Lindsey" , you'll get an error TypeError: Assignment to constant variable.

Satisfied or still confused? I'll dive in deeper next time as we talk about closure. I hope this helped