JavaScript Scope

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 : This just means when you assign a value to a variable without the or keywords or if a variable/function is not in your current scope, JavaScript will yell at you and throw a the message that looks similar to this:

RefrenceError: assignment to undeclared variable "x"

Global Scope

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

let myGlobalVariable = "I am global, anyone can touch me"function whereAmI(){
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.

let myCat = "Geoffrey" 
let myCat = "Cynthia" // Error, thing has already been declared

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

var myDog = "Skips"
var myDog = "Comet"
console.log(myDog) // "Comet"

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

function localScope(){const iAmLocal = "I am in my function scope"
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.

const catTalk = 'meow meow meow'

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



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store