3 Steps to Getting Connected During the Holiday Season

You are down. You feel off. You’ve got negative or disempowering conversations swirling around inside your head. It’s not an entirely unfamiliar state, but generally you enjoy people’s company and…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Trying to Understand The Different Types of Scopes In JavaScript

Scope is an important aspect of JavaScript and programming in general. In JavaScript, when we speak about scopes, we are referring to the accessibility or visibility of variables. That is, which parts of a program have access to the variable or where the variable is visible.

JavaScript has three types of scopes: 1) Global Scope, 2) Function Scope, and, 3) Block Scope.

Any variable that’s not inside any function or block (a pair of curly braces), is inside the global scope, when we call a scope global, it means that the variable inside the environment of the entire app, not closed up in a function. The variables in global scope can be accessed from anywhere in the program. For example:

Variables declared inside a function is inside the local scope. They can only be accessed from within that function, that means they can’t be accessed from the outside code. For example:

The last console log is not inside of the function, therefore it does not have access to the variable ‘sayHi’.

ES6 introduced let and const variables, unlike var variables, they can be scoped to the nearest pair of curly braces. That means, they can’t be accessed from outside that pair of curly braces. For example:

We can see that var variables can be used outside the block, that is, varvariables are not block scoped. Which is part of the reason why after ES6, using var is unpopular and programmers mostly use let and const for the purposes of their apps.

Scopes also apply to callback functions as well. Callback functions are literally functions that call other functions in JavaScript. Let’s see an example:

Even though scope is a thing in every programming language, Javascript has different variable names that only allow you to do certain things. I don’t know everything about Javascript just yet, but from what I know so far, understanding the scope is understanding most of JavaScript.

Add a comment

Related posts:

How My Cat Saved My Life

In the summer of 2016, freshly 18 and dropped from high school, I had moved from the bay area of Santa Cruz to a small farming town in Nevada, with plans to live with some family. My dreams were…

Elizabeth of Valois and Philip II

The reign of Felipe II is one of the most studied due to the importance it had in our country and in Europe. Of the many possible ways that exist to express monarchical and political power, Felipe…

A Wound So Deep

The pain that started long ago Still hasn’t gone completely silent There is no way that we could know If everyone was violent The words more painful than the actions All the anger manifesting the…