-
Functions prevent duplication by allowing you to reuse code multiple times.
-
Functions encapsulate logic, making code easier to read and maintain.
-
Breaking down tasks into smaller functions promotes better code organization.
-
Isolating logic inside functions simplifies the process of identifying bugs.
JavaScript functions
Key Takeaways
Functions encapsulate blocks of logic that can be reused multiple times, reducing duplication and promoting efficient code maintenance.
Parameters are the placeholders that are defined within the function. Arguments are actual values passed when the function is invoked. Functions can accept multiple arguments, and the same function can perform different tasks based on the inputs provided.
Anonymous functions are often used for callbacks or event handlers. They allow dynamic function assignment and are useful when functions are needed temporarily, such as in event listeners.
Arrow functions, also known as lambda functions, offer a more compact way to write functions. They maintain the
thiscontext from the surrounding scope, making them ideal for callbacks and asynchronous operations wherethisbehavior can be tricky.The
returnstatement is essential for sending computed values back to the caller and stopping the function’s execution. If a function returns a value, it can be assigned to a variable or used directly in expressions.
In JavaScript, functions play a critical role in making code reusable and modular. They act as subroutines, performing specific tasks when invoked. Understanding the different types of JavaScript functions, such as anonymous functions, arrow functions (lambda functions), and the principles behind function invocation, is crucial to writing efficient code.
Declare a function
To declare a JavaScript function, use the function keyword followed by the function name and its parameters. They contain a block of code wrapped within curly braces {}, executed when the function is called.
For example, the following code defines a function named helloWorld:
function helloWorld() {console.log("Hello World");}
The declaration above contains the following parts:
The
functionkeyword is used to create the function.The function name is
helloWorld, followed by parentheses().The function body contains the code that is executed when we call the function. It is enclosed within curly brackets
{}to define the scope of the function. In this example, it isconsole.log("Hello World");.
Implement JavaScript functions in a real-world application with this project, Web Crawling in JavaScript Using Cheerio.
Call a function
To call a function, we have to write the function name, helloWorld, followed by parentheses () and end the statement with a semicolon ;. Let’s call the function that we defined above:
function helloWorld() {console.log("Hello World");}helloWorld();
Parameters vs. arguments
For a JavaScript function, parameters are placeholders and arguments are actual values passed to the function when it is invoked. In our example below, name is the parameter, and "Educative" is the argument for the helloWorld() function.
function helloWorld(name) {console.log(`${name} says hello.`);}helloWorld("Educative");
We can also pass different arguments in each function call. Let's look at an example:
function helloWorld(name) {console.log(`${name} says hello.`);}helloWorld("Educative"); // passing "Educative" as an argumenthelloWorld("David"); // passing "David" as an argument
Learn more about JavaScript functions with hands-on practice with, Build a Microblogging App Using PHP, HTML, JavaScript, and CSS project.
Additionally, we can also pass multiple arguments to a single function. In the example below, we pass 2 and 4 as multiple arguments for the addition function. The value of the first argument, 2 is stored in n1 and the value of the second argument, 4 is stored in n2.
function addition(n1, n2) {let total = n1 + n2;console.log(`${total}`);}addition(2, 4);
The return statement
The return statement sends a value back to the caller and stops the function’s execution. It’s useful when you need to compute a value that will be used elsewhere in your code. Let's look at an example below:
function addition(num1, num2) {console.log("Code execution started.");return num1 + num2;console.log("This will not be executed.");}console.log(addition(2, 4));
In the example above, when the code is executed, the first console.log statement executes and logs the relevant message. The function then returns the sum of the parameters. The second console.log statement inside the function is not executed. This is because the function execution stops at the return statement.
Anonymous function
In JavaScript, we can make functions without a name called anonymous functions. Anonymous functions are often used when you don’t need to refer to the function by name. In the example below, the function that calculates the sum of two numbers is assigned to the addition variable. You can then use this variable to call the function expression by passing the relevant function arguments.
let addition = function(n1, n2) {return n1 + n2;};console.log(addition(2, 4));
Practice anonymous and lambda functions by attempting this project, Build a Custom Form Maker with MERN Stack.
Arrow functions
Lambda or arrow functions offer concise syntax for defining functions. These are commonly used for callbacks and situations where minimal function logic is required. These are especially useful for reducing verbosity and ensuring predictable behavior of the this keyword.
let addition = (num1, num2) => num1 + num2;console.log(addition(2, 4));
Note: Use arrow functions for short, single-use logic, but stick with regular functions for more complex logic.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
What are the benefits of using a function?
How are arrow functions different from regular functions?
Where are anonymous functions commonly used?
What is the difference between return and console.log?
Free Resources