Week 8: Functions - The Power of Reusability
Learn how to define and use functions to write organized, reusable, and efficient JavaScript code.
Explore Chapter 8Returning Values from Functions.
Functions often compute a value and need to send it back to the part of the code that called them. This is done using the return statement.
The return Statement
When a return statement is executed, the function immediately stops executing and sends the specified value back to the caller.
function multiply(a, b) {
return a * b; // Returns the product of a and b
// Any code after the return statement in the same block is unreachable
console.log("This won't execute");
}
let product = multiply(6, 7); // The returned value (42) is stored in 'product'
console.log(product); // Output: 42
Returning Multiple Values
While a function can only have one return statement execute, you can return multiple values by returning them within an array or an object.
// Returning multiple values using an array
function getCoordinates() {
let x = 10;
let y = 25;
return [x, y]; // Return an array
}
let coords = getCoordinates();
let xPos = coords[0]; // 10
let yPos = coords[1]; // 25
console.log(`Position: x=${xPos}, y=${yPos}`);
// Returning multiple values using an object
function getUserData() {
return { username: 'Dave', id: 102 }; // Return an object
}
let userData = getUserData();
console.log(`Username: ${userData.username}, ID: ${userData.id}`);
Returning undefined
If a function doesn't have an explicit return statement, or if it has a return; statement with no value, it implicitly returns undefined.
function logMessage(msg) {
console.log(msg);
// No return statement here
}
let returnValue = logMessage("Testing"); // Logs "Testing" to console
console.log(returnValue); // Output: undefined
Arrow Functions (ES6+).
Arrow functions provide a more concise syntax for writing function expressions. They are especially useful for simple, inline functions.
Syntax Variations
// 1. Basic syntax with multiple parameters
const add = (x, y) => {
return x + y;
};
// 2. If only one parameter, parentheses are optional
const square = x => {
return x * x;
};
// 3. If the function body is a single expression,
// curly braces and 'return' can be omitted (implicit return)
const double = num => num * 2;
// 4. No parameters requires empty parentheses
const getRandom = () => Math.random();
console.log(add(5, 4)); // Output: 9
console.log(square(6)); // Output: 36
console.log(double(10)); // Output: 20
console.log(getRandom()); // Output: (a random number between 0 and 1)
Key Differences from Regular Functions
- Concise Syntax: Often shorter to write.
- No arguments object: Arrow functions don't have their own arguments object (use rest parameters ...args instead).
- this binding: Arrow functions do *not* have their own this context. They inherit this from the surrounding (lexical) scope where they were defined. This is a significant difference and often helpful in avoiding this-related confusion, especially with callbacks and methods. We'll revisit this in more detail later.
// Example showing 'this' difference (conceptual - more relevant in Week 10/OOP)
/*
let myObject = {
value: 10,
regularMethod: function() {
console.log(this.value); // 'this' refers to myObject
setTimeout(function() {
// console.log(this.value); // 'this' here is different (often window/global), causes error or undefined
}, 100);
},
arrowMethod: function() {
console.log(this.value); // 'this' refers to myObject
setTimeout(() => {
console.log(this.value); // Arrow function inherits 'this' from arrowMethod scope, logs 10
}, 100);
}
};
myObject.arrowMethod();
*/
Arrow functions are widely used in modern JavaScript, especially with array methods like map, filter, and forEach.