Functions: Creating Reusable Code Blocks
Functions enable us to write reusable and maintainable code by grouping functionality into blocks that can be executed multiple times. In this blog, we’ll explore what functions are, how to define them, and the key concepts related to them.
Function declaration
Section titled “Function declaration”A function is a block of code designed to perform a particular task. Functions are executed when they are invoked or called.
They are defined using the function
keyword followed by the function name and parentheses.
function sayHello() { console.log("Hello, World!");}
Here, we’ve created a sayHello
function that prints out a message to the console. You can call this function as follows:
sayHello(); // Hello, World!
Parameters, Arguments, and Return Values
Section titled “Parameters, Arguments, and Return Values”Often, you’ll want your function to perform operations based on inputs. For this, functions use parameters.
- Parameters are placeholders in the function definition.
- Arguments are values passed to a function when it is called.
- Return Value functions can also return a result using the
return
keyword.
function add(a, b) { return a + b; // sum will be a + b}const sum = add(5, 7);console.log(sum); // 12
In this example:
Parameters -> a
and b
Arguments -> 5
and 7
Return Value -> 12
Function Expressions
Section titled “Function Expressions”In JavaScript, functions can also be defined as expressions. These are often assigned to a variable.
const greet = function (username) { return `Hello, ${username}!`;};console.log(greet("Don Joe")); // Hello, Don Joe!
Arrow Functions
Section titled “Arrow Functions”Arrow functions provide a concise syntax for creating functions. Introduced in ES6, they are particularly useful for shorter functions.
const multiply = (x, y) => x * y;console.log(multiply(3, 4)); // 12
Arrow functions have a more compact syntax and are often used in modern JavaScript development. For single-line expressions, you can omit the return
keyword as shown above.