Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their containing scope (global or function) during the compilation phase, before code execution.
Example:
var
: Function-scoped, hoisted, can be re-declared.
let
: Block-scoped, not hoisted, can be reassigned.
const
: Block-scoped, not hoisted, cannot be reassigned.
Primitive types: String
, Number
, Boolean
, BigInt
, Symbol
, undefined
, null
Non-primitive types: Object
, Array
, Function
It returns the type of a variable:
A closure is a function that remembers its outer scope variables even after the outer function has returned.
Executes line by line, one at a time.
Each operation blocks the next one until it completes.
Easier to understand but can be slow if a task takes time (e.g., a long loop or API call).
Example:
Allows certain operations to run in the background.
Does not block the rest of the code.
Useful for tasks like API calls, timers, or reading files.
Example:
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation.
They help you manage asynchronous code (like API calls, file loading, etc.) in a cleaner way than using nested callbacks (callback hell).
A promise has three states:
pending
– The initial state (operation still running)
fulfilled
– The operation completed successfully
rejected
– The operation failed
Example 1:
Note: The "resolve" and "reject" are not keywords. You can use any name that you want to give to a function.
Example 2:
Example 3:
async
makes a function return a Promise. await
pauses the execution until the promise is resolved or rejected.
Example:
Destructuring extracts values from arrays or properties from objects.
1. Array Destructuring
2. Object Destructuring