Appearance
Functions
JavaScript provides several ways to define functions. Each syntax has its own use cases and subtle differences in how the function behaves. Understanding these differences is key to writing idiomatic JavaScript code. Like everything else in JavaScript, functions are objects and can have properties and be passed around like any other value.
Function Statement
The most traditional way to define a function is with the function statement. These statements are hoisted, which means the JavaScript engine moves the function definition to the top of its scope. This allows you to call the function even before its definition appears in your source code.
js
// We can call it before it's defined
console.log(add(1, 2)); // 3
function add(a, b) {
return a + b;
}Function Expression
Functions can be assigned to variables. Unlike function statements, function expressions are not hoisted. They must be defined before they can be used, just like any other variable assignment.
js
// This would fail with "Cannot access 'add' before initialization"
// console.log(add(1, 2));
const add = function(a, b) {
return a + b;
}
// must call after function is defined and assigned to the variable
console.log(add(1, 2)); // 3Arrow Functions
Modern JavaScript introduced a more concise syntax using =>. Arrow functions are particularly useful for short functions:
js
// Implicit return when one line
const add1 = (a, b) => a + b;
console.log(add1(1, 2)); // 3
// With multiple lines, use { } and explicit return
const add2 = (a, b) => {
const sum = a + b;
return sum;
};
console.log(add2(1, 2)); // 3Arrow functions have some special behavior with this binding, which we'll explore when we cover objects and classes.
💡 Arrow functions are commonly used in array methods and callbacks, which we'll see later.
External Resources