Code highlights logo



Function Expressions

A function expression is a way to define a function by assigning it to a variable. This allows us to create anonymous functions, pass functions as arguments to other functions, and even return functions from other functions. Function expressions provide us with more flexibility and control in our code.

Syntax of a Function Expression

Here's the basic syntax for a function expression:

1let myFunction = function() {
2 // code goes here

The function() keyword is followed by parentheses, which can optionally include any parameters that the function needs. The function body is enclosed in curly braces {}, where we write our code.

Anonymous Functions

Function expressions are commonly used to create anonymous functions - functions without a name. Anonymous functions are useful when we only need to use the function once or when we want to create a function dynamically at runtime. Here's an example of an anonymous function:

1let greet = function() {
2 console.log("Hello!");

In this example, the function greet is created using a function expression. We can call this function using the variable name greet.

Passing Functions as Arguments

One of the powerful features of function expressions is the ability to pass functions as arguments to other functions. This allows us to create higher-order functions - functions that operate on other functions. Here's an example:

1function doMath(operation, num1, num2) {
2 return operation(num1, num2);
5let add = function(a, b) {
6 return a + b;
9let result = doMath(add, 5, 10);
10console.log(result); // Output: 15

In this example, the doMath function takes an operation (a function) as its first argument, and two numbers as the other arguments. The operation function is then called with the given numbers to perform the desired mathematical operation.



Declare a function expression named greetName that takes one parameter name.


Inside the greetName function, use console.log to print the message:

1"Hello, " + name

Sign up to start coding

Already have an account?

Sign In

Course content