JavaScript execution context — lexical environment and block scope (part 3)

  • Global scope
  • Function scope
  • Block scope

An example of the global scope

Block scope

Lexical environment

  • it is a variable created with the let, and
  • it is in a block scope.

Scope stack in the lexical environment

Tricks of creation, initialization, and assignment

  1. Creation
  2. Initialization
  3. Assignment
  • For a let variable, its creation is hoisted, but not initialization and assignment.
  • For a var variable, its creation and initialization are hoisted, but not the assignment.
  • For a function, its creation, initialization, and assignment are hoisted at the same time.
  • If you try to access a variable before the creation, you see the error “[variable name] is not defined.”
  • If you decide to access a variable before the initialization, you see the error “Cannot access [variable name] before initialization.”
  • If you log a variable before the assignment, you see the value undefined.

What are the takeaways?

  • The lexical environment is another component of an execution environment.
  • let and const variables in a block scope are created at the execution step instead of the compiling.
  • These variables are stored in the lexical environment.
  • Multiple block scopes are maintained as a stack structure in the lexical environment.
  • When the JavaScript engine executes all codes in a block scope, the related let and const variables are removed.

Join Medium

Up next…

Further reading

  • If you want to know a different understanding of the lexical environment, this post worth reading.
  • If you are not familiar with hoisting, I hope my post could help.
  • This answer is a comprehensive one explaining the temporal dead zone.

--

--

--

a coder 🧑🏻‍💻

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Serverless node.js REST API with Google Cloud Function & Firestore

DECK with svelte 🔥

Laravel Real-Time Controllers monitoring

How to take advantage of GraphQL with Nodejs

How to localise NodeJS with Polyglot.js and Localazy

Intro to JavaScript…

State vs Complexity

Changing components dynamically using Vuetify, Vue and Typescript

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Carson

Carson

a coder 🧑🏻‍💻

More from Medium

How to Extract Metadata from Music Files with JavaScript using jsmediatags

The concept of Closure in JavaScript

Introduction and Basics of JavaScript | Part 3

Create and Print Linked List in JavaScript