JavaScript Notes
Learn JavaScript function expressions – anonymous vs named, hoisting differences, assigned to variables, as callbacks, vs declarations & arrow functions, with real examples.
Introduction
A function expression is another way to define a function in JavaScript. Instead of using function as the first word of a statement (which makes it a declaration), a function expression assigns a function to a variable.
Understanding function expressions is important because they work differently from declarations in key ways — especially around hoisting — and they're the foundation of anonymous functions, callbacks, and IIFEs.
Basic Example
const greet = function (name) {
return `Hello, ${name}!`;
};
console.log(greet("Riya"));
console.log(greet("Arjun"));Hello, Riya! Hello, Arjun!
The function is stored in the variable greet. You call it just like any other function.
Anonymous vs Named Function Expression
Anonymous Function Expression (no name after function):
const square = function (n) {
return n * n;
};
console.log(square(5));25
Named Function Expression (has a name, but only visible inside itself):
const factorial = function computeFactorial(n) {
if (n <= 1) return 1;
return n * computeFactorial(n - 1); // can call itself by name
};
console.log(factorial(5));
// console.log(computeFactorial(5)); // ❌ ReferenceError – name not in outer scope120
Why use named function expressions?
- Better stack traces in debugging
- Can reference itself recursively
- The function name appears in error messages
The Critical Difference: Hoisting
This is the most important distinction between function expressions and declarations.
Function Declaration — Hoisted Completely:
// ✅ Works! Declaration is hoisted
console.log(add(2, 3));
function add(a, b) {
return a + b;
}5
Function Expression — NOT Hoisted (only variable is):
// ❌ Fails! `multiply` is undefined at this point
console.log(multiply(2, 3)); // TypeError: multiply is not a function
const multiply = function (a, b) {
return a * b;
};TypeError: multiply is not a function
How Hoisting Works with Function Expressions:
WHAT JS ENGINE SEES:
var multiply; ← variable hoisted (undefined for var)
← const/let hoisted but in "temporal dead zone"
console.log(multiply(2, 3)); ← multiply is undefined → TypeError
multiply = function(a, b) { return a * b; }; ← assigned hereMemory Diagram – Function Expression in Memory
Step-by-Step Execution Trace
const double = function (n) {
return n * 2;
};
const result = double(7);
console.log(result);14
Real World Analogy
Function declarations are like a hardcoded button on your TV remote — always there, always ready (hoisted). Function expressions are like a programmable button — you first need to program it (assign the function), and only then can you use it. If you press the programmable button before programming it, nothing happens (or you get an error).
Function Expressions as Callbacks
Function expressions are ideal as callbacks — passed as arguments to other functions.
[1, 2, 3, 5, 8, 9]
[2, 4, 6]
Function Expressions in Object Properties (Methods)
const calculator = {
value: 0,
add: function (n) {
this.value += n;
return this;
},
subtract: function (n) {
this.value -= n;
return this;
},
result: function () {
return this.value;
}
};
const answer = calculator.add(10).add(5).subtract(3).result();
console.log(answer);12
Conditional Function Assignment
Function expressions allow you to conditionally assign different logic to the same variable.
hello world
You can't do this with function declarations (they'd both be defined regardless).
Common Mistakes
❌ Mistake 1: Calling before assignment (hoisting trap)
// WRONG
const result = multiply(4, 5); // ReferenceError or TypeError
const multiply = function (a, b) {
return a * b;
};// CORRECT – always call after assignment
const multiply = function (a, b) {
return a * b;
};
const result = multiply(4, 5);
console.log(result);20
❌ Mistake 2: Using var with function expression (partial hoisting)
// Using var – hoists the variable as undefined
console.log(fn); // undefined (not an error, but not the function!)
console.log(fn()); // TypeError: fn is not a function
var fn = function () {
return 42;
};undefined TypeError: fn is not a function
Use const or let for function expressions to make the TDZ error obvious.
❌ Mistake 3: Thinking anonymous means unreachable for recursion
// WRONG – anonymous function can't call itself
const countDown = function (n) {
if (n <= 0) return;
console.log(n);
countDown(n - 1); // works via variable name, but fragile
};
countDown(3);// BETTER – named function expression for recursion
const countDown = function countdown(n) {
if (n <= 0) return;
console.log(n);
countdown(n - 1); // safer – uses internal name
};
countDown(3);3 2 1
❌ Mistake 4: Forgetting to assign to a variable
// This is a function DECLARATION (starts with `function`)
function sayHi() { console.log("Hi"); }
// This is a function EXPRESSION (assigned to variable)
const sayHello = function () { console.log("Hello"); };The starting token determines the type. If function is the first word of a statement, it's a declaration. Otherwise it's an expression.
Function Expression vs Declaration vs Arrow – Quick Reference
| Declaration | Expression | Arrow Expression | |
|---|---|---|---|
| Hoisted | ✅ Fully | ❌ No | ❌ No |
| Anonymous | ❌ No | ✅ Optional | ✅ Default |
| Named | ✅ Always | ✅ Optional | Via variable |
this | Dynamic | Dynamic | Lexical |
Can use new | ✅ Yes | ✅ Yes | ❌ No |
| As callback | ✅ Works | ✅ Works | ✅ Best |
| Conditional assign | ❌ No | ✅ Yes | ✅ Yes |
Interview Questions
Q1. What is a function expression in JavaScript?
A function expression assigns a function (anonymous or named) as a value to a variable, property, or parameter. Unlike declarations, it is not hoisted.
Q2. What is the difference between function declaration and function expression?
Declarations are fully hoisted; expressions are not. Declarations always have a name; expressions can be anonymous. Expressions can be conditionally assigned; declarations cannot.
Q3. What is a named function expression and why use it?
A named function expression has a name after the function keyword. Benefits: better stack traces in errors, can reference itself recursively, name is visible in debuggers.
Q4. Why does calling a function expression before its declaration throw an error?
Because only the variable is hoisted (as undefined for var, or in TDZ for let/const). The function value is not assigned until that line executes.
Q5. Can function expressions be used as methods in objects?
Yes. Assigning a function expression to an object property creates a method. The this keyword inside will refer to the object when called as obj.method().
Q6. When would you choose a function expression over a declaration?
- When you need to conditionally assign different function logic
- When passing as a callback argument
- When you want to prevent accidental early calling (no hoisting)
- When defining methods in objects or class-like patterns
Q7. What is the temporal dead zone (TDZ) for const/let function expressions?
let and const are hoisted but not initialized. Accessing them before their declaration line throws a ReferenceError, making bugs more obvious than var.
Q8. How do function expressions enable the module pattern?
2
Key Takeaways
- ✅ Function expressions assign a function as a value to a variable
- ✅ They are NOT hoisted — must be defined before use
- ✅ Can be anonymous (no name) or named (name visible inside only)
- ✅ Named expressions are better for recursion and debugging
- ✅ Ideal for callbacks, conditional logic, object methods, and IIFEs
- ✅
const/letmake hoisting bugs obvious via TDZ - ✅ Arrow functions are a shorter form of function expressions
- ✅ Use
constto prevent accidental reassignment of function variables
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript Function Expression Tutorial – Anonymous, Named & Assigned.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, functions, function, expression
Related JavaScript Master Course Topics