JavaScript: Your guide to understanding functions.
Tags: javascript, webdev, programming, tutorial
Published: 2023-08-22 17:17:37

Functions are reusable blocks of code that perform specific tasks. They allow programmers to lessen code repetition and keep their code organized. 

Think of Functions as Machines used in a factory, where each machine performs a specific task and together they create a product.

In this article we're going to cover: 
1. [Function Declaration](#declare)
     - [Parameters and Arguments](#param-arg)
     - [Default parameter](#default)
     - [Rest Parameter and Spread Operator](#rest-spread)
     - [Return statement](#return)
2. [Function expression](#expression)
3. [Scope and Closure](#scope-closure)
4. [Arrow Functions](#arrow)
5. [Hoisting](#hoist)
6. [Immediately Invoked function expression or IIFE](#iife)

## <a id="declare">Function Declaration</a>
We declare a function by using the reserved keyword `function` along with a name of your choice and parentheses. 

```javascript
function sayHello() {
}
```
Consider this syntax the blueprint for functions.

Inside the function, we write a code that will perform a task.
```javascript
function sayHello(){
  console.log("Hello, I am a Function!");
}
```
In this example, we created a function named `sayHello` that prints out "Hello, I am a Function!" to the console after invoking it. 

The function above will not output anything to the console at the moment because it has not been invoked. 

**How do we invoke a function?**
We simply call the function by its name followed by parentheses. 

```javascript
function sayHello(){
  console.log("Hello, I am a Function!");
}

sayHello(); // Hello, I am a Function!
```

### <a id="param-arg">Parameters and Arguments</a>
Parameters are placeholders for values that a function can accept when creating it. Arguments are the values passed to the function when invoking it. 
```javascript
 function sayHello(name) {
  console.log(`Hello, I am ${name}`);
}

sayHello("John"); //Hello, I am John
```
In the example above, the parameter `name` is a placeholder for the value passed as an argument. You can pass your name for example as an argument to the function and it will print out your name instead of "John".

In Other words, parameters are like blank spaces that expect to be filled with values when you're about to use the function. Arguments are the actual values you want to pass that will replace these blank spaces.

### <a id="default">Default parameter</a>
A default parameter is a parameter that was assigned a value when declaring a function. This is useful when a user does not pass an argument to the function. The assigned value of the parameter will act as an argument. Think of it as a backup argument.

```javascript
function sayHello(name="User"){
  console.log(`Hello, ${name}`);
}

sayHello("John"); // Hello, John
sayHello(); //Hello, User
```
### <a id="rest-spread">Rest Parameter and Spread Operator</a>
The rest parameter is important, it helps you pass an unlimited number of parameters to a function instead of using multiple parameters.

Here's an example of a function with multiple parameters:
```javascript
function names(a,b,c,d,e) {
    console.log(`My students names:, ${a}, ${b}, ${c}, ${d}, ${e}`);
}

names("John", "Jane", "Todd", "Michael", "Lenny");
//My students names:, John, Jane, Todd, Michael, Lenny

```
This function takes 5 arguments that are the names of students and displays them.
But what if we have more than 5 students?
What if we have 10 or 15 students?
We could give our function 10 or 15 parameters but there's a better way to do it and that is by using the rest operator.

```javascript
function names(...name) {
    console.log(`My students names: ${name}`);
}

names("John", "Jane", "Todd", "Michael", "Lenny", "Draco", "Harry", "Ginny");
//My students names: John,Jane,Todd,Michael,Lenny,Draco,Harry,Ginny
```
### <a id="return">Return Statement</a>
`return` is a reserved keyword that will tell the function to stop executing. When `return` is used inside a function, the function will have a value, otherwise its value will be `undefined`.

```javascript
function names(a,b,c,d,e) {
    console.log(`My students names:, ${a}, ${b}, ${c}, ${d}, ${e}`);
}

names("John", "Jane", "Todd", "Michael", "Lenny");

console.log(names("John", "Jane", "Todd", "Michael", "Lenny")); //undefined.
```
In this example we did not use the `return` keyword, meaning this function returns a value of undefined. _Note that if you want your function to give back a meaningful result please specify a return statement_

```javascript
function sayHello() {
  return "Hello, I am a function";
}

console.log(sayHello()); //Hello, I am a function
```
Keep in mind the return statement will not print out anything to the console unless `console.log()` is used.

The return statement can be assigned to  variable and used in another part of your code to complete a task. Remember the machine example.

## <a id="expression">Function expression</a>
A function expression is when you define a function by assigning it to a variable which allow us to use the returned value in other parts of our code.

```javascript
const calculateRectangleArea = function(width, height) {
    return width * height;
};

const width = 5;
const height = 8;
const area = calculateRectangleArea(width, height);

console.log(`The area of the rectangle is: ${area}`); //The area of the rectangle is: 40
```
## <a id="scope-closure">Scope and Closure</a>
When a variable is declared or accessed, the term "scope" is used. It specifies how variables are visible and usable throughout your code. JavaScript has two  scope types:
- Global Scope: global scope variables are declared outside of any function. they are also accessible anywhere inside the code, including functions.

```javascript
const globalVar = "I'm in the global scope";

function printGlobalVar() {
    console.log(globalVar); 
}

printGlobalVar(); //I'm in the global scope
``` 
- Local Scope: local scope variables are variables declared inside a block of code such as inside a function, or loops which we'll be seeing later in this series.

```javascript
function greeting() {
    const message = "Hello, from the local scope!";
    console.log(message);
}

greeting(); // Hello, from the local scope!
```
- Closures involve a combination of functions that work together.  Imagine it as a tiny bubble that wraps around other functions. inside this bubble,  All of the bubble's variables and parameters are stored inside of it and can still be used after the outer functions (the bubble) have finished.

```javascript
function outer() {
    const outerVar = "I'm from the outer function";

    function inner() {
        console.log(outerVar); // inner function has access to outerVar
    }

    return inner;
}

const closureFunction = outer(); // outer function has finished executing, but inner still remembers outerVar
closureFunction(); // Output: "I'm from the outer function"

```

## <a id="arrow">Arrow functions</a>
Arrow functions make it easy and efficient to define functions. They were first introduced in ES6 and provide a more concise syntax for creating functions than traditional function expressions. In other words it's a shorthand to define a function. Just like a regular function it can also receive parameters. In the body of the arrow function you can omit the curly braces `{}` and the `return` statement .

```javascript
const sum = (a, b) => a+b

console.log(sum(1, 2)); //3
```
this
if the function has one parameter the parentheses can be omitted 

```javascript
 const printName = (name) => console.log(`My name is: ${name}`);

printName("John");// My name is: John
```

## <a id="hoist">Hoisting</a>
The concept of hoisting is when function invocations are moved to the top of the source code. This means you can use functions before they are declared in your code. 

```javascript
sayHello(); // Output: "Hello!"
function sayHello() {
    console.log("Hello!");
}
```
This concept is also applies to variables. 
```javascript
console.log(name); //undefined
let name= "john";
console.log(name);  //john
```
the first `console.log()` statement will print undefined, and then the variable is assigned the value of john.

## <a id="iife">Immediately invoked function expression</a>

Immediately invoked function expression or `iife` for short is a function that is defined in parentheses that wrap around it and followed by another pair of parentheses that immediately invoke it.

```javascript
(function() {
    const secretMessage = "This is an iife!";
    console.log(secretMessage);
})(); //This is an iife!
```
This type of function is used when you want to isolate variables from the outer scope or write modular code without affecting the global scope.