JavaScript the Hard Parts 01-06

JavaScript

Global Execution Context

const num = 3;
function multiplyBy2(inputNumber){
  const result = inputNumber * 2;
  return result;
}
const name = 'Will';
  1. Processes in line by line (single-threaded)
  2. 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);

local_execution_context

  • Running / Calling / Invoking a function !== Defining a function
  • When you execute a function you create a new execution context comprising:
    1. The thread of execution (we go through the code in the function line by line)
    2. 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);

call_stack global_memory

  • 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 a function 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, use const instad of `var (ES2015)
    • If you’re reassigning, use let instead of var

Principles Review

  • Synchronous JavaScript:
    • Calling a function creates a new execution context
      • Includes Memory / Thread
    • Call Stack keeps track of multiple execution context
  • There is asynchronous JavaScript as well