This content originally appeared on DEV Community and was authored by Joanna
In a previous post, we've learned what are functions, their syntax and why they're used. If you need a refresher please refer to this lesson JavaScript Tutorial Series: Functions.
In this post we're going to explain what function expressions are through some examples.
What are function expressions
Function expressions are a strong and useful component of JavaScript. They allow programmers to define functions in a flexible manner, allowing the creation of reusable and dynamic code.
A function expression's fundamental objective is to define a function as a value that can be assigned to a variable or used as an argument by another function. This is distinct from a function declaration, which uses the function keyword to define a named function.
Let's look at an example.
const greetings = function(username) {
console.log(`Hello, ${username}!`);
};
In this example, a variable called greetings
is given the function expression. The greeting is logged to the console using this function, which takes a parameter username
.
Anonymous functions
Function expressions have the advantage of allowing the creation of anonymous functions, which is when a function is only needed once or acts as a callback.
const numbers = [10, 20, 30, 40, 50];
const square = numbers.map(function(number) {
return number * number;
});
console.log(square); //[100,400,900,1600,2500]
In this example an array of numbers is used as the input for the map function. An anonymous function is passed as the second argument to the map function, and it returns the square of each number it receives from the array.
Creating higher-order functions
It is also possible to create higher-order functions using function expressions. These are the functions that accept arguments from other functions and return arguments as their output. JavaScript Tutorial Series: Higher order functions.
function repeat(func, nTimes) {
for (let i = 0; i < nTimes; i++) {
func();
}
}
const greet = function() {
console.log("Greetings");
};
repeat(greet, 3);
/*
Greetings
Greetings
Greetings
*/
In this example, the repeat function's first argument is a different function func
, and its second argument is the number of times the function should be repeated nTimes
. The func
function is then called a specified number of times by the repeat function. The repeat function receives an argument from the greet function, which is defined using a function expression.
Do not forget to try these snippets while reading their explanations to get a better grasp of the concept
This content originally appeared on DEV Community and was authored by Joanna
Joanna | Sciencx (2023-02-25T21:11:50+00:00) JavaScript Tutorial Series: Function expressions. Retrieved from https://www.scien.cx/2023/02/25/javascript-tutorial-series-function-expressions/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.