Table of contents
Today we'll be taking a look at SCOPES and CONTEXT in JAVASCRIPT
WHAT IS SCOPE?
In simpler terms, a scope is a value given to the variable. There are two types of scopes:
- Global Scopes
- Local Scopes
Global Scope You can define a value to a variable even before it is actually called or used.
let myName = "Jim"
function name(){
console.log(myName)
}
name()
After running the above code, you'll see that the console will return Jim as output. This is because we have already declared that the value of variable myName is JIM.
Local Scope Now, let's take a look at another code:
let myName = "Jim"
function name(){
let myName = "Creed"
console.log(myName)
}
name()
After running the above code you'll see that we'll get the output Creed even though we have globally declared the value of myName to be Jim. If you look inside the code you'll see that we have overridden the value of myName to be Creed locally. While displaying the value of myName the function will look for the nearest value of the variable and then show it accordingly.
Now again if run the given code you will get some surprising results:
let myName = "Jim"
function name(){
let myName = "Creed"
console.log(myName)
}
name()
console.log(myName)
The output of this actually shows us that the using a local variable you can temporarily override the value of the Global variable but as soon as you exit out of the local one the global variable will take its original place.
WHAT IS CONTEXT?
By now, you might have figured out that scopes are related to variables. Well, context is related to objects. Context is always the value of this keyword which is a reference to the object that “owns” the currently executing code or the function where it's looked at.
let name = {
first: "Jim",
last: "Helper",
driveCar(){
console.log(this.first+" "+ this.last + " is driving a car.")
}
}
name.driveCar()
In the above code, we have declared an object name and inside it, we have declared a function driveCar(). You can see that we have used a new keyword this. Well, think about this how can we access the outer object inside the function? Well, this is where this keyword comes into play. You can access an object inside it using this keyword.