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

Get rid of Error Handling with NodeJS + Express

Creating a CI pipeline for Angular

How to Render a Maze in Canvas

Using UI-Router for better React routing

Understanding Angular Interceptors

angular logo with article’s title underneath

Basic String Search in Javascript — Trie Data Structure

Why Choose MEAN Stack For Web and Mobile App Development?

10 interesting topics in Javascript

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

JS-12— JavaScript for Programmers, Chapter9, Part2

Replacing conditional statements with object literals.

Basics of JavaScript for technical interviews

Event Loop in JavaScript!