Closures and Lexical Scoping in JavaScript

BetterKnownToucan avatar
BetterKnownToucan
·
·
Download

Start Quiz

Study Flashcards

5 Questions

What is a closure in JavaScript?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).

When are closures created in JavaScript?

Closures are created every time a function is created, at function creation time.

What is lexical scoping?

Lexical scoping is a way of determining the scope of variables and functions based on their position in the source code.

In the given code example, what is the purpose of the init() function?

The init() function creates a local variable called name and defines an inner function called displayName().

What is the scope of the displayName() function?

The displayName() function is available only within the body of the init() function.

Study Notes

Closures in JavaScript

  • A closure in JavaScript is a function that has access to its own scope, the scope of its parent functions, and the global scope.
  • Closures are created when a function is defined inside another function, and the inner function has access to the variables of the outer function even when the outer function has finished executing.

Lexical Scoping

  • Lexical scoping is the process of resolving the scope of a variable by looking at the lexical context of the code, i.e., the structure of the code.
  • In JavaScript, lexical scoping is used to determine the scope of variables and functions.

The init() Function

  • The init() function is used to create a closure by defining an inner function, displayName(), within it.
  • The init() function sets the value of the variable name, which is then used by the displayName() function.

The displayName() Function

  • The scope of the displayName() function is within the init() function, which means it has access to the variables of the init() function.
  • The displayName() function is a closure because it has access to the variables of the init() function even after the init() function has finished executing.
  • The displayName() function uses the variable name to display the name.

Test your knowledge on closures and lexical scoping in JavaScript with this quiz. Learn about how closures work and how they give access to an outer function's scope from an inner function.

Make Your Own Quizzes and Flashcards

Convert your notes into interactive study material.

Get started for free

More Quizzes Like This

Master Closures in JavaScript
4 questions
JavaScript Syntax and Type Conversion Quiz
12 questions
JavaScript: Variáveis ​​e Funções
10 questions
Use Quizgecko on...
Browser
Browser