Learnings-from-JS-01: JS simple definitions

Learnings-from-JS-01: JS simple definitions

·

10 min read

Call stack

Call stack is a data structure that keeps track of function calls in a program, ensuring they are executed in a sequential and orderly manner, following the Last In, First Out (LIFO) principle.

Coercion

Coercion is the process of converting one type to another in JavaScript, which can occur implicitly or explicitly to ensure compatibility for calculations or comparisons.

"=== vs ==”

"=== in JavaScript checks both value and type equality, if types defer “==” performs type coercion before comparison”

Scope

Scope in JavaScript defines the accessibility and visibility of variables, determining where they can be accessed and modified within a program.

Scope chain

In JavaScript, "Scope Chain" is the hierarchical order in which the engine looks for variables and their values, starting from the current scope and moving up to outer scopes, ensuring proper variable resolution.

Closure

Closure allows Inner function can retain and access variables from its lexical scope, even after the outer function has completed execution and been returned.

Hoisting

Parser makes variable and function declarations accessible before their actual initialization in the current scope. Enabling them to be referenced earlier in the code.

Temporal Dead Zone

Temporal Dead Zone is the period between the beginning of current scope to an actual initialization of variable using let or const. if accessed during this period, ReferenceError will be thrown.

Expression vs Statement

An “Expression" produces a value and can be a part of a larger expression, while a "Statement" performs an action and doesn't produce a value directly.

IIFE

IIFE stands for Immediately Invoked Function Expression and is a self-executing anonymous or named function used to encapsulate code and prevent variable collision.

ESM modules

ESM modules, short for "ECMAScript Modules," are a modern way to organize and share code in JavaScript, allowing you to import and export functions, objects, or values between different parts of your code or even across different files.

CommonJS modules

CommonJS modules are a method used in JavaScript to organize and share code between different parts of a program or across different files. They allow you to export functions, objects, or values from one module and import them into another module using the require and module.exports syntax.

Lexical Analysis

In lexical analysis code is broken down into smaller units called tokens. Tokens are meaningful chunks like keywords, identifiers, operators, and literals. This analysis helps identify the basic building blocks of the code.

Syntax analysis

Syntax analysis is the process of checking the arrangement and structure of tokens according to the language's grammar rules.

Prototype

"Prototype" is a shared template object that defines common properties and methods for other objects, enabling inheritance and efficient memory use.

Prototype chain

"Prototypal chain" in JavaScript signifies the sequential link of objects through their prototypes, allowing properties and methods to be accessed in a cascading manner.

Prototypal Inheritance

"Prototypal Inheritance" in JavaScript involves inheriting properties and behaviors from a parent object, or prototype, enabling code reusability and efficient object hierarchy.

this

this refers to the context in which a function is called. It can vary depending on how the function is invoked.

new

new allows us to create new objects from a constructor function.

call

"call" in JavaScript is a method used to invoke a function, specifying the context (object) for 'this' and passing arguments individually.

apply

"apply" is a method that calls a function with a context and an array of arguments.

bind

"bind" creates a new function with a specific context ("this") and, optionally, pre-set arguments, without invoking the original function immediately.

this Reference table

ContextWhat this Refers To
Global ScopeRefers to the global object (like window in browsers or global in Node.js).
Function (Regular)Depends on how the function is called. If called as a method, this points to the object the method is called on. If called normally, this could point to the global object (in non-strict mode) or undefined (in strict mode).
Arrow FunctionInherits the value of this from the surrounding code. It doesn't have its own this.
Object MethodRefers to the object that the method is called on.
Constructor FunctionRefers to the newly created instance of the object being constructed.
Event HandlerRefers to the DOM element that triggered the event.
Explicit BindingUses methods like call, apply, or bind to directly specify what this should be.

this value will be dynamic assigned depending on the context in which it's used.

arguments

The arguments object in JavaScript is an array-like object available within functions, containing all the arguments passed to the function, allowing access to parameters regardless of their defined names.

Event loop

The "Event Loop" in JavaScript manages the execution of asynchronous tasks, ensuring that they are processed in a non-blocking manner, allowing the main program to remain responsive to other tasks.

Callback Queue

The "Callback Queue" in JavaScript is a data structure that holds asynchronous callback functions, which are ready to be executed in the order they were added, after the current execution stack is cleared.

Microtask queue

The "Microtask Queue" in JavaScript is a queue that holds microtasks, which are higher priority asynchronous tasks than regular tasks in the event loop. ex: Promise, Mutation Observer

Macrotask queue (Job queue)

The "Macrotask Queue" in JavaScript is a queue that holds macrotasks, which are lower priority asynchronous tasks. ex: Timers, I/O operations

process.nextTick

In Node.js, "process.nextTick" is a method that schedules a callback function to be executed immediately after the current operation, before any other I/O events or timers in the event loop. It provides a way to schedule high-priority tasks in the microtask queue.

process.nextTick(() => {
  console.log("Callback executed in the next tick.");
});

Methods to create object

  1. Object literal

  2. Constructor Function

  3. ES6 class

  4. Object.create

  5. Factory function

  6. Object assign

Execution Context

An execution context represents the environment in which JavaScript code is executed. It includes variables, objects, and scope chains. Each time a function is invoked, a new execution context is created and pushed onto the call stack.

Execution context phases

  1. Creation Phase:

    • Variable Object Creation: In this phase, a Variable Object is created, which holds variables and function declarations. For functions, a special property called "this" is also determined.

    • Scope Chain Creation: The Scope Chain, which defines the scope and hierarchy of variables and functions, is established. It includes the current execution context's Variable Object and the Variable Objects of outer (enclosing) contexts.

    • Function Declarations: If there are function declarations in the code, they are hoisted to the top of the execution context, making them available for use before they are formally declared in the code.

    • Variable Declarations: Similarly, variable declarations with "var" are hoisted to the top but initialized with "undefined."

  2. Execution Phase:

    • During this phase, the JavaScript engine executes the code line by line. It assigns values to variables and performs operations based on the instructions in the code.

    • Function expressions and other code are executed as encountered.

    • Any variables declared with "let" and "const" remain in a "temporal dead zone" until they are reached in the code.

    • Once the execution is complete, the execution context is popped off the call stack.

First class function

In JavaScript, "First-Class Function" refers to a function that can be assigned to variables, passed as arguments, and returned from other functions, treating functions as flexible and portable entities.

Pure function

A "Pure Function" in JavaScript is a function that always produces the same output for the same input and has no side effects, meaning it doesn't modify external state or variables. It relies solely on its input parameters and returns a result without causing changes outside the function.

First-order function

First-order function is a function that doesn’t accept another function as an argument and doesn’t return a function as its return value.

Higher order function

A "Higher-Order Function" in JavaScript is a function that either takes another function as an argument or returns a function as its result. This concept enables functional programming paradigms like passing behavior as data, composing functions, and creating abstractions for more modular and flexible code.

Unary function

Unary function (i.e., monadic) is a function that accepts exactly one argument.

Currying function

Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument.

const curryAdd = (a) => (b) => (c) => a + b + c;

Memoization

"Memoization" in JavaScript is a technique of caching the results of expensive function calls to optimize performance by avoiding redundant computations.

Promise

A "Promise" in JavaScript is an object representing the eventual completion of an asynchronous operation.

States

  • pending: initial state, neither fulfilled nor rejected.

  • fulfilled: meaning that the operation was completed successfully.

  • rejected: meaning that the operation failed.

Promise (all, allSettled, any, race)

TypeWhen CompletedWhen FailureResponse Format
Promise.all()When all promises resolveIf any promise is rejectedArray of results
Promise.allSettled()When all promises settle-Array of result states
Promise.any()When any promise resolvesIf all promises are rejectedSingle result
Promise.race()When the first promise resolves or rejects-Single result

Async & Await

"Async/await" in JavaScript is a modern syntax that simplifies asynchronous code by allowing the use of the "async" keyword to define functions that can contain "await" to pause execution until promises are resolved, enhancing code readability and maintainability.

eval function

The eval() function in JavaScript is used to execute code represented as a string, allowing dynamic code execution at runtime. However, it's generally advised to avoid using eval() due to security risks and potential performance issues.

Shallow copy

A "Shallow Copy" in JavaScript refers to creating a new object or array that is a duplicate of the original, but only on the top level. In other words, the copied object or array shares references to the same nested objects or arrays as the original. Changes made to nested objects or arrays in the copy will affect the original and vice versa.

Here are some methods to create a shallow copy of an object or array:

  1. Spread Operator for Objects:

     const shallowCopy = { ...originalObject };
    
  2. Spread Operator for Arrays:

     const shallowCopy = [...originalArray];
    
  3. Object.assign for Objects:

     const shallowCopy = Object.assign({}, originalObject);
    
  4. Array.slice for Arrays:

     const shallowCopy = originalArray.slice();
    

These methods copy the top-level properties or elements of the original object or array, but any nested objects or arrays are still shared references between the original and the copy.

Deep copy

A "Deep Copy" in JavaScript refers to creating a completely independent duplicate of an object or array, including all nested objects and arrays. In a deep copy, changes made to the copy do not affect the original, and vice versa.

import { cloneDeep } from 'lodash';

const originalObject = {
  name: 'John',
  address: {
    street: '123 Main St',
    city: 'Anytown',
  },
};

const deepCopy = cloneDeep(originalObject);

Dynamic imports

"Dynamic Imports" in JavaScript refer to a feature that allows you to load modules or code chunks asynchronously, only when they are needed. This helps improve page performance by reducing initial load times and optimizing resource utilization.

Dynamic imports are typically used with the import() function, which returns a Promise that resolves to the module or code you're importing. Here's an example:

// Using dynamic import
import('./module.js')
  .then(module => {
    // Use the imported module
  })
  .catch(error => {
    // Handle errors
  });

Did you find this article valuable?

Support Arun Praba's Notes by becoming a sponsor. Any amount is appreciated!