JavaScript the Hard Parts 01-06
JavaScriptGlobal Execution Context
const num = 3;
function multiplyBy2(inputNumber){
const result = inputNumber * 2;
return result;
}
const name = 'Will';
- Processes in line by line (single-threaded)
- Creates memory for variables (Global Variable Environment) const result is never stored in memory if the function is never called
JavaScript threads are …
- Single threaded
- Synchronous execution
Local Execution Context
- How do we call a function in JS: add a parenthesis
const num = 3;
function multiplyBy2(inputNumber){
const result = inputNumber * 2;
return result;
}
const output = multiplyBy2(4);
const newOutput = multiplyBy2(10);
- Running / Calling / Invoking a function !== Defining a function
- When you execute a function you create a new execution context comprising:
- The thread of execution (we go through the code in the function line by line)
- A local memory (‘Variable environment’) where anything defined in the function is stored output is defined as undefined until a value gets assigned Once execution is done, the execution context gets erased (goes into global)
Call Stack
- The call stack keeps track of function
- Checks where the thread of execution is currently at in the code
- 1 JS application == 1 call stack
const num = 3;
function multiplyBy2(inputNumber){
const result = inputNumber * 2;
return result;
}
const output = multiplyBy2(4);
const newOutput = multiplyBy2(10);
- When entered,
global()
is added to the execution context - When a function is called, the function is pushed into the stack
- Before a function returns, calling
console.log(multiplyBy2)
is returned with afunction object
andundefined
- When a function is returned, the function is now popped from the stack, and the code points to whichever function was right beneath it
-
Whatever is top of the call stack is where JavaScript thread is running the code
const
: If you’re not going to reassign it to memory, useconst
instad of `var (ES2015)- If you’re reassigning, use
let
instead ofvar
- If you’re reassigning, use
Principles Review
- Synchronous JavaScript:
- Calling a function creates a new execution context
- Includes Memory / Thread
- Call Stack keeps track of multiple execution context
- Calling a function creates a new execution context
- There is asynchronous JavaScript as well