Functions
Tags: webdev, javascript, beginners, programming
Published: 2023-06-02 19:00:00

## What is a Function?

`function` is a block of code that can be defined and called by a name later in the code. Functions allow you to reuse and organize your code, and they are one of the most important concepts of every programming language.

You can define a function in JavaScript using the `function` keyword, followed by the name of the function, a list of parameters in parentheses, and a block of code in curly braces. Here is an example of a function that calculates the area of a rectangle:

```js title="Defining a function"
function calculateArea(width, height) {
	return width * height;
}
```

In this example, the function is named `calculateArea`, and it takes two parameters: `width` and `height`. The function calculates the area of the rectangle by multiplying the `width` by the `height`, and it returns the result using the return statement.

To call a function in JavaScript, you simply need to use the name of the function followed by a list of arguments in parentheses. For example:

```js title="Calling a function"
const area = calculateArea(10, 20);
console.log(area); // 200
```

In this example, the `calculateArea()` function is called with the arguments 10 and 20, and the result is stored in the variable area. The value of area is then printed to the console.

Functions can also accept an optional list of parameters, called `default parameters`, which are used if the caller does not provide a value for the parameter. Default parameters are specified using the `=` operator, like this:

```js title="Default parameters"
function calculateArea(width, height = 10) {
	return width * height;
}

const area = calculateArea(10);
console.log(area); // 100
```

In this example, the `height` parameter has a default value of 10. If the caller does not provide a value for `height`, the default value is used.

## What is parameter, argument, and return value?

### Parameter vs Argument

A **parameter** is a variable that is used to store the value of an argument. An **argument** is a value that is passed to a function when it is called. A **return value** is the value that is returned by a function when it is called.

For example, in the `calculateArea` function, the `width` and `height` parameters are used to store the values of the arguments that are passed to the function when it is called.

```js
function calculateArea(width, height) {
    return width * height;
}

const area = calculateArea(10, 20);
console.log(area); // 200
```

Here, 10 and 20 are the arguments that are passed to the `calculateArea()` function when it is called. The `width` and `height` parameters are used to store the values of the arguments.

### Return value

A function can return a value using the `return` keyword. The return value is the value that is returned by the function when it is called. For example:

```js
function calculateArea(width, height) {
    return width * height;
}

const area = calculateArea(10, 20);
console.log(area); // 200
```

## Types of Functions

There are several types of functions, depending on how they are defined and how they are used. Here are a few examples:

### Function declarations

These are the most common (old) way to define a function, and they are _hoisted_ to the top of the code. They have the following syntax:

```js title="Function declaration"
function functionName(parameters) {
	// code to be executed
}
```

Function declarations are hoisted, which means that you can call a function even before it is defined. For example:

```js title="Function declaration"
greet(); // This works, and prints 'Hello, world!'

//
function greet() {
	console.log("Hello, world!");
}

// This also works and prints 'Hello, world!'
greet(); 
```

In this example, the `greet()` function is called before it is defined, but it still works because function declarations are hoisted.

Note: What is hoisting?

You would read about in advanced section of JavaScript. Let's just briefly explain it here.

Hoisting is the mechanism that moves declarations to the top of the code before execution which means that you can call them before it is defined (or declared)

### Function Expressions

Function expressions are another way to define a function, in which a function is assigned to a variable. They have the following syntax:

```js title="Function expression"
const functionName = function (parameters) {
	// code to be executed
};
```

Function expressions are not hoisted, which means that you can't call a function before it is defined. For example:

```js
// This will error
greet(); // ReferenceError: Cannot access 'greet' before initialization

const greet = function () {
	console.log("Hello, world!");
};
```

In this example, the `greet()` function is called before it is defined, and it throws an error.

### Arrow Functions

Arrow functions are a concise way to define a function. It is available in modern browsers and in Node.js. They have the following syntax:

```js title="Arrow function"
const functionName = (parameters) => {
	// code to be executed
};
```

You can see no `function` keyword, and the arrow `=>` is used instead. Arrow functions are _not hoisted_, which means that you can't call a function before it is defined. For example:

```js 
// This will error
greet(); // ReferenceError: Cannot access 'greet' before initialization

const greet = (x) => {
	console.log("Hello, world!");
};
```

Here are a few examples of arrow functions:

A simple arrow function that returns the square of a number:

```js
const square = (x) => {
	return x * x;
};

console.log(square(10)); // 100
```

An arrow function that returns the sum of two numbers:

```js
const add = (x, y) => {
	return x + y;
};

console.log(add(10, 20)); // 30
```

An arrow function that returns the maximum of two numbers:

```js
const max = (x, y) => {
	if (x > y) {
		return x;
	} else {
		return y;
	}
};

console.log(max(10, 20)); // 20
```

If the body of the arrow function consists of a single statement that returns a value, omit the curly braces and the return keyword, like this:

```js
const square = (x) => x * x; // This will return x * x
const add = (x, y) => x + y; // This will return x * x
const max = (x, y) => (x > y ? x : y); // This will return x if condition is true, else y

console.log(square(10)); // 100
console.log(add(10, 20)); // 30
console.log(max(10, 20)); // 20
```

### Anonymous functions

Anonymous functions don't have a name, and they are mostly used as callbacks functions. They have the following syntax:

```js
function (parameters) {
  // code to be executed
}
```

Here are a few examples of anonymous functions:

An anonymous function that calculates the square of a number:

```js
const square = function (x) {
	return x * x;
};
```

An anonymous function that sorts an array in ascending order:

```js
const numbers = [3, 1, 2];

numbers.sort(
	// highlight-start
	function (a, b) {
		return a - b;
	}
	// highlight-end
);

console.log(numbers); // prints [1, 2, 3]
```

### IIFE (Immediately Invoked Function Expression)

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. They have the following syntax:

```js
(function () {
	// code to be executed
})();
```

IIFE functions are useful when you need to define a function that is used only once, and you want to avoid polluting the global namespace.

Here are a few examples of IIFE functions:

An IIFE function that prints a message to the console:

```js
(function () {
	console.log("Hello, world!");
})();
```

An IIFE function that calculates the square of a number:

```js
const square = (function (x) {
	return x * x;
})(10);

console.log(square); // prints 100
```

An IIFE function that sorts an array in ascending order:

```js
const numbers = [3, 1, 2];

numbers.sort(
	// highlight-start
	(function (a, b) {
		return a - b;
	})()
	// highlight-end
);

console.log(numbers); // prints [1, 2, 3]
```

IIFE functions are not very common in modern JavaScript code, but they are still useful when you need to define a function that is used only once, and you want to avoid polluting the global namespace.

Now what is global namespace?

Global namespace is the space where all the variables and functions are defined. It is the global scope. In JavaScript, the global scope is the default scope. This means that all variables and functions are defined in the global scope unless you specify the scope.

namespace is a collection of variables, functions, and objects. It is a container for variables and functions. In JavaScript, the global namespace is the global object. The global object is the default object of the global scope. In a browser, the global object is the window object. In Node.js, the global object is the global object.

## Conclusion

In this article, we learned about the different ways to define a function in JavaScript. We learned about function declarations, function expressions, arrow functions, anonymous functions, and IIFE functions.