What about scope in JavaScript?

Photo by Zan on Unsplash

What about scope in JavaScript?

ยท

5 min read

Scope... The scope is to JavaScript coder like air is to everyone. It is everywhere in your project. And most of the time you don't even notice it, because it is so natural to you. The scope exists for you in your code. So the scope is our theme for today. Let's get into it.

Did you know that we have 3 types of scope?

Here are those types:

  • global
  • function a.k.a. local
  • block

Let's learn something about the GLOBAL scope

Imagine an enormous box where you can fit an elephant. This will be our global scope. Everything you will put there you can also access. It is the same as with global scope in your code.

Global scope is accessible from every place in your code. Even you can access variables or functions from different files. For example, you define the global variable foo in foo.js,

// foo.js file
var foo = "global scope";

and in your other file bar.js, you can access it.

// bar.js
console.log(foo); // "global scope"

This brings me to a problem with pollution of global scope.

Reduce usage of the global object

You should or better said, it is your duty to use a local or a block scope before the global scope. And why is that? Well, imagine you work in a team of developers. You and your colleague work independently on some features. Then both of you add to the global scope variable named newFeature. Boom! Here we have a clash ๐Ÿคฏ. What value will contain this global variable? What side effects will it have? And that is the reason why you want to prefer local or block scope before the global.

But the global scope has its usage of course. I am sure that at some point in your career you will use libraries or some 3rd party libraries. Some of them will provide you global access to their mighty object. Which will do the magic necessary for your project.

It is not forbidden to define global variables but you should be aware of used namespaces and potential clashes. So nice things to do to prevent problems are

  • write a documentation
  • make tests to see if no one made some bad changes
  • have guidelines that will help with defining variables in the global scope

Var - the ancient one

var is a declaration statement. It was replaced in the ES6 version of JavaScript by const and let. In the present, it is not used so often because we have const and let statements. Which also are not hoisted. Var doesn't have block scope. Var declarations, wherever they occur, are processed before any code is executed. This is called hoisting, but it is a theme for another article ๐Ÿค”.

var x = 1;

if (x === 1) {
  var x = 2;

  console.log(x); // 2
}

console.log(x); // 2

In this example, you can see what it means that the var statement doesn't have block scope. So sometimes when you will use the same name for a variable it can result in unwanted side effects in your code ๐Ÿ˜ง. That is not what you want! So a better solution would be to use const or let in your code. Since they are able to create block scope as you can see in the next example.

const x = 1;

if (x === 1) {
  const x = 2;

  console.log(x); // 2
}

console.log(x); // 1

Local a.k.a function scope

'use strict'

function myFunction() {
    var result = 3;
}

console.log(result); // Error: result is not defined

In the example above we saw what it means local a.k.a. function scope. It means that what you define inside function stays in function. Nice to know is that thanks to the local scope when a function gets executed it isn't available anymore. It will not take any place in the memory, thanks to the garbage collector ๐Ÿ˜ฎ (if this is interesting for you let me know).

There are some situations where you can save local scope for another time when you will need it for example CLOSURES. About closures, I will write in the close future, so stay tuned ๐Ÿ˜‰.

Our guy block scope

Block scope came to us when const and let statements were introduced in the ES6 version. Most of the time you will meet with block scope in if, try-catch, or loop statements. Block scope is something like younger and smaller brother to the local scope. You can access everything from upper scopes but they cannot access the variables defined in the block scope.

Many of us better understand the things we want to learn in images. So here you go:

// global scope
function myFunction() {
    // local scope

    if (statement) {
        // block scope, but only when you use const or let
    }
}

Things to remember

  • What are global, local, and block scopes?
  • Why is good to reduce the usage of the global object?
  • Why you should prefer const or let before var?
  • When and how is it good to use the global scope?

That will be everything from me for this week. I hope you have a nice weekend and if you want to know something more about JavaScript or some specific theme, just write me on Twitter or LinkedIn. See you next Weekend.

ย