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 : 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:

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)
}
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 var 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)
}
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

--

--

--

Software Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How I tried to validate React forms (with hooks)

Final Project Phase-1 Javascript

TypeORM Tutorial for Beginner— CRUD in Express.js (TypeScript)

What’s the big deal with TypeScript?

How to integrate Zoom APIs in your applications?

Leverage the power of Zoom in your applications.

From @Balthomeservice on Twitter

Setting up Flow the right way

Creating a React Timer

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
Akiko Green

Akiko Green

Software Engineer

More from Medium

Javascript roadmap: Scope

JavaScript

Javascript Strings