DEV Community

Cover image for How Do Closure and Scope Work In JS?
Quokka Labs for Quokka Labs

Posted on

How Do Closure and Scope Work In JS?

Professional JavaScript developers may know the Closure and Scope. Still, the rising JavaScript programmers may need to learn more about it. No worries! If you don't know, this blog post is for you to understand how Closure and scopes work in JS efficiently and can help speed up your app development.

If you are new to mobile app development, you can see our best blog on step-by-step procedures: Read More.

A Step-by-Step Guide to Mobile App Development Process

What Mobile App development process Quokka Labs follows, let’s learn what stages are there in the development and enhancement they go.

favicon quokkalabs.com

Closure and Scopes are very much needed in JavaScript, but sometimes newcomers need clarification. So, let's start with the Scope first.

What Are Scopes and How Do They Work In JS?

Scope gives you access to variables you need. In JavaScript, there are two types of Scopes, described below:

Global Scope

They are variables declared outside of all functions or out of the ({}).

const hi = 'Hi QL Reader!'

function sayHi () {
  console.log(hi)
}

console.log(hi) // 'Hi QL Reader!'
sayHi() // 'Hi QL Reader!
Enter fullscreen mode Exit fullscreen mode

You can declare variables, but it's not recommended to do so because there are chances for naming collisions. There can be same-name variables so that errors may occur.

Local Scope

They are only usable in a specific part of the code, so they are called local Scope. There are two Local Scopes: Function scope and block scope.

Function Scope

Function scope is you can only access a variable within the function. Let's see the example below.

function sayHi () {
  const hi = 'Hi QL Reader!'
  console.log(hi)
}

sayHi() // 'Hi QL Reader!'
console.log(hi) // Error, hi is not defined
Enter fullscreen mode Exit fullscreen mode

Block Scope

Block Scope means declaring a variable with const or within ({}). It means you can access only the curly braces. Let's see the example below:

{
  const Hi = 'Hi QL Reader!'
  console.log(Hi) // 'Hi QL Reader!'
}

console.log(hi) // Error, hi is not defined
Enter fullscreen mode Exit fullscreen mode

Scopes And Function Hoist

Functions are always hoisted on the top when they are declared. They are hoisted on the top of the current Scope. See the below example.

// Same as the one below
sayHi()
function sayHi () {
  console.log('Hi QL Reader!')
}

// The same as the code above
function sayHi () {
  console.log('Hi QL Reader!')
}
sayHi()
Enter fullscreen mode Exit fullscreen mode

Now, if we declare a function with expression, functions will not be lifted on the top of the current Scope. Let's see the example below.

sayHi() // Error, sayHi is not defined
const sayHi = function () {
  console.log(aFunction)
}
Enter fullscreen mode Exit fullscreen mode

Nested Scopes

It has a behavior called lexical scoping. It happens when a function is defined in another function. Hence, the inner function gets access to the outer function's var., but the outer function does not access the inner function var.

function outerFunction () {
  const outer = `I'm the outer function!`

  function innerFunction() {
    const inner = `I'm the inner function!`
    console.log(outer) // I'm the outer function!
  }

  console.log(inner) // Error, inner is not defined
}
Enter fullscreen mode Exit fullscreen mode

Debugging Scopes with DevTools

Debugging is easy with Firefox and Chrome DevTools. There are two methods to use these functions.

  • The first method is using the keyword "debugger" in the code. It will pause Javascript execution in browsers so JavaScript developers can debug.
function prepareCake (flavor) {
  // Adding debugger
  debugger
  return function () {
    setTimeout(_ => console.log(`Made a ${flavor} cake!`), 1000)
  }
}

const makeCakeLater = prepareCake('banana')
Enter fullscreen mode Exit fullscreen mode

You can also move the keyword into the Closure:

function prepareCake (flavor) {
  return function () {
    // Adding debugger
    debugger
    setTimeout(_ => console.log(`Made a ${flavor} cake!`), 1000)
  }
}

const makeCakeLater = prepareCake('banana')
Enter fullscreen mode Exit fullscreen mode
  • The second way is adding a breakpoint in your code directly in the sources.

What Are Closures and How Do They Work In JS?

The Closure is a type of boundary. The Closure is when you create a function in another function. The inner function is called Closure. At last, the Closure is returned so you can use the outer function's var.

function outerFunction () {
  const outer = `Outer variable!`

  function innerFunction() {
    console.log(outer)
  }

  return innerFunction
}

outerFunction()() // Outer variable!
Enter fullscreen mode Exit fullscreen mode

We can compress the code also like below:

function outerFunction () {
  const outer = `Outer variable!`

  return function innerFunction() {
    console.log(outer)
  }
}

outerFunction()() // Outer variable!
Enter fullscreen mode Exit fullscreen mode

Using Closure to Limiting Errors

Many errors, like Ajax Requests, a timeout, or a console.log statement, can happen. But be careful using closures because Closure may cause ajax request errors too. To understand it better, let's go to the example.

function makeCake() {
  setTimeout(_ => console.log(`Made a cake`), 1000)
}
Enter fullscreen mode Exit fullscreen mode

You can see that it got a timeout. Let's see another example.

function makeCake(flavor) {
  setTimeout(_ => console.log(`Made a ${flavor} cake!`), 1000)
}
Enter fullscreen mode Exit fullscreen mode

Now you can see that the cake is immediately made after knowing the flavor. But we want to make the cake when the time is right. Let's see the code below.

function prepareCake (flavor) {
  return function () {
    setTimeout(_ => console.log(`Made a ${flavor} cake!`), 1000)
  }
}

const makeCakeLater = prepareCake('banana')

// And later in your code...
makeCakeLater()
// Made a banana cake!
Enter fullscreen mode Exit fullscreen mode

As you can see how we used closures to make fewer errors.

Closures with Private Variables

As previously said that in a function, a variable could not access outside the function. So these are called private variables. Sometimes java developers need private variables. So here's how you can get the help of closures.

function secret (secretCode) {
  return {
    saySecretCode () {
      console.log(secretCode)
    }
  }
}

const theSecret = secret('QL is amazing')
theSecret.saySecretCode()
// 'QL is amazing'
Enter fullscreen mode Exit fullscreen mode

Wrapping Up!

Scopes and Closures are relatively easy to learn as a beginner JavaScript developer. They are effortless to know. Well, this was about Closures and Scopes. Still, even pro JavaScript developers sometimes need help solving complex project errors.

So, in that case, our top 3% of experts can help you get out of that situation; hire JavaScript developers to solve the mistakes quickly. Also, get apps developed speedily with our mobile app development services.

Oldest comments (0)