Halo Top Ice Cream Image

I remember encountering a plethora of errors regarding the Javascript scope. An error you will be more than acquainted with is the : RefrenceError. This just means when you assign a value to a variable without the let, or const keywords or if a variable/function is not in your current scope, JavaScript will yell at you and throw a RefrenceError the message that looks similar to this:

Global Scope

Global scope is when a variable is declared outside of all functions, giving full access anywhere in your code!

function whereAmI(){
console.log(myGlobalVariable)
}
console.log(myGlobalVariable) // "I am global, anyone can touch me"
whereAmI() // "I am global, anyone can touch me"

Although it may be tempting to declare variables in the global scope, it is highly advised not to in case of naming collisions! Having two variables named the same thing will cause a collision and will raise an error as well.

But, naming your variables with var will having the second variable overwrite the first, making it possible to name two of the same

Local Scope

Variables that are usable only in a specific part of your code are considered to be in a local scope. There is considered to be two kinds of local scope: function and block scope

Function Scope

When a variable is declared inside a function, you can only access it within that function

const iAmLocal = "I am in my function scope"
console.log(iAmLocal)
}
console.log(iAmLocal) // Error, iAmLocal is not defined
console.log(localScope) // "I am in my function scope"

Block Scope

When a variable is declared with const or let within curly braces ({}), the variable is only accessible within these braces.

} 
console.log(catTalk) // Error, catTalk is not defined

Software Engineer