Defining a Javascript Function
How To Define a JavaScript Function
There are a few different ways to declare a function in Javascript applications. I’ve laid out 4 ways below so choose the method that best fits your use case! Function declarations are great for named functions, whereas arrow functions are excellent for callbacks and shorter functions.
Using Function Declaration
/** Function Declaration */
function functionName(parameters) {
// code to be executed
return value;
}
// Example
function greet(name) {
return "Hello, " + name + "!";
}
console.log(`My name is ${greet("Alice")}`); // "Hello, Alice!"
Using Function Expression
/** Function Expression */
const functionName = function(parameters) {
// code to be executed
return value;
};
// Example
const multiply = function(a, b) {
return a * b;
};
console.log(`5 * 3 = ${multiply(5, 3)}`); // 15
Using Arrow Functions (ES6)
/** Arrow Function (ES6) */
const functionName = (parameters) => {
// code to be executed
return value;
};
// Examples with different syntax
const square = (x) => {
return x * x;
};
console.log(`Square of 4: ${square(4)}`); // 16
// Implicit return (for single expressions)
const squareRoot = x => x ** 0.5;
console.log(`Square Root of 8: ${squareRoot(8)}`);
// Multiple parameters
const add = (a, b) => a + b;
console.log(`2 + 3 = ${add(2, 3)}`); // 5
// No parameters
const title = () => "Math";
console.log(`The page title is "${pageTitle()}"`);
Using the Function Constructor
/** 4. Function Constructor (less common) */
const functionName = new Function("parameters", "function body");
// Example
const divide = new Function("a", "b", "return a / b;");
console.log(divide(10, 2)); // 5