Beginner LevelJavaScript & TypeScript
What are the differences between function declarations, expressions, and arrow functions?
❓ Interview Prompt: Compare function declarations, function expressions, and arrow functions regarding hoisting, this binding, and arguments.
Function Declaration:
Hoisted completely — can be called before the declaration line. Has its own this context.
Function Expression:
Not hoisted (only the variable is hoisted if using var). Assigned to a variable.
Arrow Function (=>):
Short syntax. No own `this` — inherits this from the enclosing lexical scope. No arguments object. Cannot be used as constructors (new).
Code Implementation Example
javascript
// Function Declaration (hoisted)
greet('Alice'); // ✅ Works before declaration
function greet(name) { return `Hello, ${name}`; }
// Function Expression (NOT hoisted)
// sayHi('Bob'); // ❌ ReferenceError
const sayHi = function(name) { return `Hi, ${name}`; };
// Arrow Function (lexical this)
const add = (a, b) => a + b;
const square = x => x * x; // Single param: no parens needed
// Arrow functions inherit 'this'
class Timer {
constructor() {
this.seconds = 0;
setInterval(() => {
this.seconds++; // ✅ 'this' refers to Timer instance
}, 1000);
}
}💡Function declaration hoisting, expression assignment, and arrow function lexical this.
🎯 Interview Key Takeaway
Use arrow functions for callbacks and inline functions. Use function declarations for named, hoisted functions.
#Functions#Arrow Functions#this#Beginner
Back to all JavaScript & TypeScript Questions→