loading...
Cover image for How to scoop JavaScript

How to scoop JavaScript

damewold profile image Denis Woldemariam Updated on ・6 min read

Fundamental JavaScript Concepts Series

Fundamental JavaScript Concepts Series

1.SCOPE

How to scoop JavaScript

I know what you are thinking. Scoops of JavaScript? What is that? I know, I know! JavaScript is not ICE CREAM but it’s possible to get a scoop of it. Well, at least the variables. Only problem is you have to understand the concept of Scope. Why? Because Scope determines what you can scoop in javaScript. What does that mean? Okay, let me explain.

What is scope?

Imagine you go out to an ICE CREAM shop and buy two scoops of ICE CREAM. How would you feel if a random person in the shop takes a bite off your ICE CREAM without your permission? Or the owner of the ICE CREAM shop mixes up your order and gives you the wrong one by mistake. You wouldn’t want that to happen to you, right? Because it is not going to feel right. Unless you decide to share no one should have access to it. Because at the end of the day you paid for it and it’s yours. On the other hand you can not tell the ICE CREAM shop to make ICE CREAM available for sale to the public.Because it’s not yours. But as long as it is available to the public, you can get it as well. Of course if you can pay for it. What does this got to do with the concept of Scope? Well, it demonstrates how the accessibility of a product is determined by ownership of the product. In the same token, accessibility of variables is determined by scope.

Scope is an enclosure or fence created by functions or curly brackets. It determines the accessibility or visibility of variables. The codes you write inside the scope have exclusive access to the variables inside but also all the variables outside of the scope. But codes outside the scope can not access the variables inside the scope. Think about scope like an enclosure or a fence that delineates what is yours or not. Just like the ICE CREAM you bought the variables inside that enclosure or fence is what is exclusively available to your code. Just like the ICE CREAM shop is available to the public or everyone, what is written outside of the scope is available to all codes written inside the scope and outside of it. That shows how JavaScript manages the accessibility of variables through the use of scope. In other words the scope determines what you can scoop in javaScript.

Kinds of Scope

There are three main scopes in JavaScript.

  1. Global Scope
    • This is default enclosure and one that contains all the code including the local scope created by functions
  2. Function or local scope
    • This is the scope or enclosure created inside the functions
  3. Block scope
    • This is the scope or enclosure created inside curly brackets

Let’s see how this looks like in examples.

  • Everything outside of the function localScope is in the global scope. It is the default scope that is the parent of all local scopes.
  • We also have a local scope created or enclosed by function localScope.

As we can see above all the global variables e and global can be accessed from inside the local scope as well as from the global scope. However the variables that are only found inside the local scope which are variables y and x can only be accessed from inside the local scope only. When we tried to access it from the global scope we get uncaught Reference error.

  • So in short we can access variables from inside the scope they are written in but not from the outside of the scope.

What if the scope is nested inside another scope? Well, the same principle applies. The variables inside the nested scope will only be accessed by codes inside that scope. But as explained above if your code is inside the nested scope, it has access to the variables inside the scope it is in as well as all the variables outside in the subsequent chain of scope. Let’s look at the following example:-

What is lexical scope?

This is put simply the accessibility of variables from the outer scope.

[Not Really! "Lexical scope is the region of text where a particular lexeme (name) has a particular meaning." In other words the scope any variable is determined by its location in the code. Look at the correction below in the comment section further explanation]

In other words it’s being able to access the variables in the parent scope and subsequent scope chain in nested functions. This is particularly important when it comes to a unique feature of functions called closure

[Not really! closure is not a feature of functions rather lexical scope. It makes it possible for function to have access to a "private" data written outside the outer environment of function. Look at the the comments below for more some more explanation for now].

But that’s a topic for another day. But here is an example of lexical scope.

lexical scope

As you can see above, function coreScope was able to execute arithmetic operation even though one of the operands(variable y) was not inside its scope. How was it able to execute the operation? Well, javaScript engine first looks for variable y inside the scope and moves up the scope chain until it finds it. If it doesn't find it, it will give you error. The same can be said about the arithmetic operation inside function innerScope. It was able to fetch variable y after first looking inside its own scope and moving up to the outer scope which is the scope of its parent function. This was possible due to lexical scope.

What is block scope?

This is the scope created when we use curly brackets most commonly in if/else statements, switch statements, for-loops and while loops. One interesting aspect of block scopes is that the variables inside of it can be accessed from outside the scope if they are declared using var instead of let and/or const. So you have to use let and/or const for block scope to work. Let's look at the following example:-

Block Scope example

As you can see above block scope doesn't work with var. The variable music was accessible from outside the block scope but the variables declared with let and const were not accessible from outside the block scope. This shows that block scope only works when you declare the variables with let and/or const. What is the difference between let and const though?

Well, as the name suggests variables declared with const are constant variables. This means you only declare the variable once but also you must assign it a value. Using const can be beneficial in preventing accidental mutations of the variables. On the other hand you don't have to initialize the variable when you declare it using let. And you can assign value to the variable multiple times once it has been declared. This opens up more opportunities for accidental mutations of the variables.

Why is Scope important?

Scope is important since it helps to manage the accessibility or visibility of variables in javaScript. This is particularly important when you are working in teams since there is a lot of opportunities for accidental overwriting of variables. Understanding scope can decrease the likelihood of bugs from data corruption and it can reduce conflicts as well. Understanding scope also lays the ground work for understanding other fundamental javascript concepts such as execution context, hoisting and closure.

Thoughts?

Thank you for reading this far. I am writing a series of blog posts on fundamental javascript concepts. If you like my writing follow me.

Posted on by:

damewold profile

Denis Woldemariam

@damewold

["JavaScript and React enthusiast", "technical blogger", "Half-Marathon runner", "book lover" & "Science and financial literacy passionate advocate"]

Discussion

markdown guide
 

What is lexical scope?
This is put simply the accessibility of variables from the outer scope.

Not exactly.

Lexical scope is the region of text where a particular lexeme (name) has a particular meaning.

It's an important distinction because it is a property of the source code, rather than of the running program.

Consider dynamically adding a property to the global object -- this does not affect the lexical scope, but it does affect how variables are resolved at run time.

This is particularly important when it comes to a unique feature of functions called closure.

Lexical closure isn't a feature of functions -- it's a feature of lexical scope.

A lexical closure occurs when a free variable is shared as a bound variable by closing over a lexical binding in another lexical scope.

Consider

const a = 1;
{
  const b = a;
}

The anonymous block has a lexical closure over a from its surrounding environment.

We don't usually talk about this case because it isn't very interesting -- but it's the same thing, lexically speaking.

Compare with

const a = 10;
const b = () => a;

where the lexical closure is more obvious and equally uninteresting. :)

Where lexical closures become interesting is when they affect the extent of variables, for example with

const a = (v) => () => v;

Normally v would have the same extent as a call to a, but due to being captured in a lexical closure it has the combined extent of the call to a and the extent of the returned function that captured it.

 

Thank your for the feedback and the correction! I will make the changes.