Function Expression : JavaScript

Suneet Agrawal
2 min readMay 18, 2023

JavaScript is a dynamic and versatile programming language that allows developers to create complex and dynamic applications. One of the key features of JavaScript is its ability to use functions as first-class citizens. This means that functions can be assigned to variables, passed as arguments to other functions, and even returned as values from functions. In this article, we’ll take a closer look at function expressions in JavaScript and explore how they can be used in your code.

This post was originally posted at https://agrawalsuneet.github.io/blogs/function-expression-javascript/ and later reposted on Medium.

Function Expressions

A function expression is a type of function that is defined as part of an expression. In other words, it’s a function that is defined on the fly, rather than being defined in advance as a named function. Here’s an example of a function expression:

let multiply = function(a, b) {
return a * b;
}

In this example, we’ve created a function expression that takes two arguments, a and b, and returns their product. We’ve assigned this function expression to a variable called multiply. This means that we can call the multiply function just like we would any other function:

let result = multiply(5, 10);
console.log(result); // Output: 50

As you can see, we’ve passed the values 5 and 10 as arguments to the multiply function, and it has returned their product, 50.

Anonymous Function

One of the advantages of using function expressions is that they can be anonymous. This means that you don’t have to give them a name, which can be useful in certain situations. For example, if you want to create a function that you’ll only use once, you can define it as an anonymous function expression:

let result = (function(a, b) {
return a * b;
})(5, 10);

console.log(result); // Output: 50

In this example, we’ve defined an anonymous function expression that takes two arguments, a and b, and returns their product. We’ve then immediately called this function expression with the values 5 and 10. The result of the function is assigned to a variable called result, which is then logged to the console.

Function as Arguments

Another advantage of using function expressions is that they can be used as arguments to other functions.

Please continue reading at https://agrawalsuneet.github.io/blogs/function-expression-javascript/

That’s all for now. You can read my other interesting blogs here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--