Creation of global execution context for the top level code i.e code which not inside any fn. Hence, code outside the fn is executed first.
Code inside fn body of fn-decln/exprsn is only executed when its called.
Execution Context(EC)
Environment in which piece of JS is executed.
Stores all the necessary information for some code to be executed like local variables, args passed to a fn.
JS code always runs inside an EC.
Exactly one global EC irrespective of the size of JS project.
Default context, created for code not inside any fn.
Then the code is executed inside the global EC
After the top level code is executed, execution of fns & waiting for C/bs
For each fn call, a new EC is created to exectute that fn. Same goes for methods, as they are also fns attached to objects.
All these ECs together make up the Call Stack.
When all fns are executed, engine waits for CBs to arrive & execute them. Ex. click event callback, provided by the event loop.
What is inside EC
- Variable Environment consisting of
- let, const, var declarations
- Functions
arguments object : stores all the args passed to the fn in its EC.
Each fn gets its own EC as its called. And variables declared end up in variable environmentScope Chain:
Fns can access variables outside of fns using scope chain.
Contains references to the variables located outside of the current fn and to keep track of the scope chain, it is stored in each EC.Each EC also get the 'this' keyword.
All these three above are generated during "Creation Phase", right before execution. These the things necessary to run the code in top level.
For arrow fns EC:
We won't be having: arguments object, this keyword. Arrow fns use from their closest regular fn, the above two.
arguments: array like object, containing all the arguments passed into the regular fn, not arrow fn.
Call Stack Memory Heap = JS Engine
Call Stack
Place where ECs get stacked on top of each other, to keep track of where we are in the execution. The topmost EC is the one we are running. As the execution is over, its removed from the top of stack and the control is trasferred to the underlying EC.
If there is a nested fn call, the outer fn call will be paused so as to return the result of the execution of inner fn on call stack as JS has only one thread of execution. Now the prev EC will become the active EC
Then the top-most EC is popped out of Call Stack as its returned.
Lowest in Call Stack will be global EC, on top it will be fn calls as they occur in order.
Ensures order of execution never gets lost.
In the end, program will be finished and global EC will also be popped out the Call Stack.
JS code runs inside an EC, which are placed on Call Stack.
Hence, we can say that each EC has: 1. Variable environment 2. Scope chain 3. 'this' keyword
Scoping
How our program variables are organized and accessed by JS Engine.
Where do variables live
Where can we access a certain variables and where not.
Lexical Scoping:
JS has leical scoping which means scoping is controlled by placement of fns and blocks in the code.
Ex. A nested fn has access to variables of its parent fn.
Scope:
Space or env in which a certain variable is declared(variable environment in case of fns). Its the variable env which is stored in fns EC.
For fns, Var env & scope both are same.
Three scopes in JS are: 1. Global scope 2. Fn scope 3. Block scope [ES6]
Scope is a place where variables are declared. Hence, true for Fns also as fns are just values stored in variables.
Scope of a Variable
Region of our code where a certain variable can be accessed.
Scope is different from scope of a variable with subtle differences.
## Global Scope: For top level code For variables declared outside of any fn or block which are accessible from everywhere Variables in this scope are at the top of scope chain. Hence, can be used by every nested scope.
## Fn Scope: Each fn has creates its own scope Variables are accessible ONLY inside fn, NOT outside. Else Reference Error Also called local scope Fn decln, exprsn, arrow all three create their own scopes. Only way to create scope using ES5 which had only fn & global scope.
## Block Scope: Introduced in ES6, not only fn but {} also create a scope known as block scope which work only for ES6 variables i.e let-const types. DOesn't work for variables declared with 'var' as its fn scoped. Variables accessible only inside block i.e {} This only applies to variables declared with let-const only. Fns are also block scoped in ES6 (only in strict mode, should be used) variables declared using 'var' will be accessible outside the block Scoped to the current fn or the global scope. var variables only care about fn, they ignore blocks. They end up in nearest fn scope.
Every nested scope has access to variables from its outer scope & the global scope. Same is applicable to fn arguments also.
If a fn doesn't find the variable in its scope, it looks up the scope chain to find out the varibles in its outer scopes. This process is called variable lookup in scope chain. This doesn't work the other way around i.e we cannot access nested fn variables or scopes from outside the fn or outer scopes.
Sibling scopes cannot access each other's variables
Only the innermost scope can access its outer scopes, not the reverse.
One EC for each fn in the exact order a fn is called is placed on Call Stack with its variables inside the EC. Global EC is at the bottom of the Call Stack
Scope chain:
Its all about the order in which fns are written in the code.
Has nothing to do with order in which fns were called.
Scope chain gets the variable environment from the EC.
Order of fn calls is not relevant to the scope chain at all.
const a = 'Alice'; first(); function first(){ const b = "Hello"; second(); function second(){ const c = "Hi"; third(); } } function third(){ const d = "Hey"; console.log(d + c + b + a); // Reference Error } ## Call Stack order: third() EC - top second() EC first() EC global EC - bottom Scope Chain: second() --nested inside--> first() --nested inside--> global scope. third() is independently defined inside gloabal scope. Reference Error occurred because both 'c' as well as 'b' cannot be accessed using the scope chain.
Summary:
E-C, Var Env, Cl-Sk, Scope, Scope-chain are all different but related concepts.
Scoping asks the questions where do variables live, where can we access the variables and where not.
Lexical Scoping in JS: Rules of where we can access variables are based exactly where in the code fns and blocks are written.
Every scope has access to all the variables from all its outer scopes. This is scope chain which is a one-way street. An outer scope can never access variables of inner scope.
Scope chain of a certain scope is equal to adding together all the Var Envs of all the parent scopes.
Scope chain has nothing to do with the order in which fns are called. It does not affect the scope chain at all.
When a variable is not found in current scope, engine looks up the scope chain until it finds the variable its looking for. This is called variable look-up.
The above is the detailed content of Execution Context & Call Stack. For more information, please follow other related articles on the PHP Chinese website!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

Enhance Your Code Presentation: 10 Syntax Highlighters for Developers Sharing code snippets on your website or blog is a common practice for developers. Choosing the right syntax highlighter can significantly improve readability and visual appeal. T

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

This article presents a curated selection of over 10 tutorials on JavaScript and jQuery Model-View-Controller (MVC) frameworks, perfect for boosting your web development skills in the new year. These tutorials cover a range of topics, from foundatio

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
