Table of Contents
Declaring a Function
This function, named `greeting`, prints “Hello, World!” when called.
Calling a Function
To execute the function, we need to call or invoke it. This is done by writing the name of the function followed by parentheses `()`. Let’s call the `greeting` function:
Function Parameters and Arguments
A function can also accept parameters. Parameters are a mechanism to pass values to functions. The function can then use these parameters to perform its task. Let’s look at an example:
Here, the function `greeting` accepts one parameter `name`. When we call the function, we pass the argument “Alice” to the `name` parameter.
A function can also return a value. The `return` statement stops the execution of a function and returns a value from that function. Here is an example:
In this example, the `square` function accepts a parameter `number` and returns the square of this number.
Function Expressions and Anonymous Functions
Here, an anonymous function is assigned to the variable `square`. We can then call `square` as if it’s a function, because it is!
Introduced in ES6, arrow functions offer a more concise syntax to write function expressions. They are also lexically bound, which means `this` value inside an arrow function is determined by its surrounding context. Here’s how you can define the `square` function as an arrow function:
Arrow functions are particularly useful when passing a function as an argument to another function. For instance:
In the above example, we pass an arrow function as an argument to the `map` method.
Higher-Order Functions and Callbacks
A callback function is a function that is passed as an argument to another function and is executed after some operation has been completed. Below is an example of a callback function:
In this example, `innerFunction` has access to variables in `outerFunction`’s scope, which is a demonstration of a closure.