Camaria Bevavy initials
Camaria B.

Functions: declarations vs expressions

javascripthoisting

Function Declarations

A function declaration is hoisted into the Global Environment and initialized to the function object before execution begins, so it can be called before its declaration. During the creation phase, the JavaScript engine creates the binding for the function and initializes it with the actual function object. As a result, the function is fully available when the execution phase begins.

askMe();

function askMe() {
     console.log("How are you?");
}
> How are you?


Function Expression: var

A function expression declared with `var` is hoisted to its enclosing function scope or the Global Environment and initialized to `undefined` before execution begins. The variable is therefore available before its assignment is executed, but attempting to call it before the assignment will result in a `TypeError` because its value is `undefined`.

askMe();

var askMe = function () {
  console.log("Hello");
};
> Uncaught TypeError: askMe is not a function

Function Expression: let or const

A function expression declared with `let` or `const` is hoisted to its block scope or the global environment but remains uninitialized before execution begins. The variable is in the Temporal Dead Zone (TDZ), so attempting to access or call it before its declaration is reached results in a `ReferenceError`.

askMe();

const askMe = function () {
  console.log("How are you");
};
> Uncaught ReferenceError: can't access lexical declaration 'askMe' before initialization