Problem Statement
What are the different ways to define functions in JavaScript? Compare function declarations, expressions, and arrow functions.
Explanation
JavaScript has three main ways to define functions.
Function declaration uses the function keyword followed by a name. It creates a named function that is fully hoisted and can be called before its definition. Good for top level functions and when you need hoisting.
Function expression assigns a function to a variable. It can be named or anonymous. It follows variable hoisting rules so cannot be called before assignment. Useful for conditional function creation or passing functions as values.
Arrow function introduced in ES6 provides shorter syntax. It does not have its own this binding and inherits from parent scope. Cannot be used as constructor with new. Has implicit return for single expressions. Ideal for callbacks, array methods, and when you want lexical this binding.
When to use what:
Use function declarations for main functions that need hoisting. Use function expressions for functions as values or conditional creation. Use arrow functions for callbacks and when you need lexical this. Choose based on your needs for hoisting, this binding, and syntax preference.
Code Solution
SolutionRead Only
// Function Declaration
function greet(name) {
return 'Hello ' + name;
}
// Hoisted - can call before definition
// Has own 'this'
// Can be used as constructor
// Function Expression
const sayHi = function(name) {
return 'Hi ' + name;
};
// Not hoisted - cannot call before
// Has own 'this'
// Anonymous or named
// Arrow Function
const welcome = (name) => {
return 'Welcome ' + name;
};
// Shorter version
const greetShort = name => 'Hello ' + name;
// Not hoisted
// Lexical 'this' from parent
// Cannot be constructor
// Implicit return for single expression
// Use cases
// Callbacks with arrow function
[1, 2, 3].map(n => n * 2);
// Method with regular function
const obj = {
name: 'Object',
greet: function() {
console.log(this.name); // Works
}
};
// Event handler needs this
button.addEventListener('click', function() {
console.log(this); // button element
});