Learn
Functions
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:
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:
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:
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.
Instructions
Declare a function expression named greetName
that takes one parameter name
.
Inside the greetName
function, use console.log
to print the message:
Sign up to start coding
Already have an account?
Sign In