A Simple Guide to JavaScript Functions - Native, Arrow and Shorthand.
Tags: javascript, webdev, beginners, codenewbie
Published: 2020-12-11 21:01:23

---
series: JavaScript For Total Novice or Beginners.
title: A Simple Guide to JavaScript Functions - Native, Arrow and Shorthand.
published: true
description: Learn and understand everything necessary to build a real-world application with Javascript functions (Native, arrow, shorthand and others)
tags: JavaScript, webdev, beginners, codenewbie
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/rdqbeby2nlmkvv7nsed4.png
---


Welcome to this lesson, in this lesson, we will discuss "Function" and we will cover:

- What is a function?
- How to declare a function.
- What is a function expression?
- What is an Arrow Function?
- What are Shorthand Method Definitions?
- What is an "Instantly Invoking Function Expression" (IIFE)?
- Basic Things you should Know about Functions.

# What is a "Function"?

A function is a subprogram created by grouping statements that perform specific tasks. A function can be maintained separately from the main program because it is self-contained.

Functions are very important in JavaScript because they reduce repetition of code in a program as they can be reused.

# Function Declarations. 


A function can be declared as in:

```js
function name(parameter1, parameter2, etc) {
    //function body
}
```

The "function" keyword is used and the name of the function comes after the "function" keyword. Then, we have a parenthesis that contains parameters and the body of the function is between the curly braces.

# Then, how do we call a function?

A function is called by its name followed by a parenthesis () that contains arguments that are optional like this:


```js
name(argument1, argument2, etc);
```

If it has no parameter, we can just call it like this:

```js
name();
```

Now, let's make this a real function as in:

```js
function sum(firstNumber, secondNumber) {
    const total = firstNumber + secondNumber;
    console.log(total);
}
```

Let's call it now as in:

```js
sum(4, 4); // we should see 8 in the console.
```

Yeah! It works.

We have declared and called a function.

Now, let's talk about function expression.

# What is a function expression?

A function expression is any function that is passed as a value to a variable as in:

```js
let multiply = function (firstNumber, secondNumber) {
    return firstNumber * secondNumber;
}
```

An anonymous function, that is a function without a name, is passed to the variable named "multiply". And boom, that is what is called a function expression.

After a function expression has been stored in a variable, the variable can be used as a function.  They are always invoked (called) using the variable name as in:

```js
let multiply = function (firstNumber, secondNumber) {
    return firstNumber * secondNumber;
}
multiply(3, 5) // 15 is seen in the console.
```

Yeah! That is a function expression.

What is an Arrow Function?

An arrow function – also called “fat arrow” function is a more concise syntax for writing function expressions. It utilizes the arrow (=>) that looks like a fat arrow. Arrow functions are anonymous and change the way "this" and "bind" work in functions.

You can use an arrow function as in:

```js
let multiply = (firstNumber, secondNumber) => firstNumber * secondNumber;
multiply(4, 5) // 20
```

This arrow function is similar to the regular function we declared earlier but arrow function makes it to be more concise.

Yeah! That is cool.

Let's quickly talk about the basic things you have to know about the arrow function.

### 1. The arrow function doesn't need curly braces and "return" keyword if its body is a statement.

This is what we mean:

```js
let add = (firstNumber, secondNumber) => firstNumber + secondNumber;
add(2,3)// 5
```

You can see we do not use any curly braces and the "return" keyword but we could have used them if we want to. We don't need them since the body of our arrow function is a statement or a line.

If the body of the arrow function has more than a statement or a line, we would have to use the curly braces and the "return" keyword as in:

```js
const add = (firstNumber, secondNumber) => {
    return firstNumber + secondNumber;
}
add(5, 4) // 9
```

In short, curly braces and the "return" keyword are not needed if the body of the arrow function is a line ( a statement).

What is the difference between the regular function and the arrow function?

One is fat but the other is not!

Oh, Sorry! I am kidding.

### 1. The regular function  is hoisted, that is, it can be called before it is defined as in:

```js
//call sum();
sum(5, 7); // 12

// define sum()
function sum (firstNumber, secondNumber) {
    return firstNumber + secondNumber;
}
```

It is possible to call the function before it is declared as in above because the regular function is hoisted at the top of the current scope. 

Hoisting in this case means the JavaScript engine always defines the regular function first before it is called regardless of whether you call it before defining it as in the above example. 

But you must define an arrow (=>) function before you call it as in:

```js
//define sum()
const sum = (firstNumber, secondNumber) => firstNumber + secondNumber;

//call sum()
sum(5, 7) // 12
```

Hey, stop teaching nonsense!

What will happen if I call an arrow function before it is defined?

See it with your eyes in:

```js
//call sum()
sum(5, 7) // Uncaught ReferenceError: Cannot access 'sum' before initialization

//define sum()
const sum = (firstNumber, secondNumber) => firstNumber + secondNumber;
```

Oops! It throws an error.

### 3. The regular function has "This" context but the arrow function doesn’t have it

An arrow function is not suitable for methoths in an object or class because it doesn't have "this" context as in:

```js
const person = {
    name: "Ayobami",
    sayName: () => `My name is ${this.name}`,
}

person.sayName() // My name is
```

Oops!

There is a problem. "this.name" is not available in the arrow function because it doesn’t have it. It makes use of the "this" context of its parent scope as in:

```js
var name = "Biden";

const person = {
    name: "Ayobami",
    sayName: () => `My name is ${this.name}`,
}

console.log(person.sayName()) // My name is Biden
```

Oops!

"this.name" returns "Biden" instead of "Ayobami" because the arrow function's context is the context of its parents. 

The "this" context of an object in JavaScript is the window object and that is why "Biden" is returned instead of "Ayobami" because a variable declared with a "var" is accessible from the window objects.

If we change "var" in the example above to const or let, "undefined" or an empty string will be returned depending on browser as in:

```js
let name = "Biden";

let person = {
    name: "Ayobami",
    sayName: () => `My name is ${this.name}`,
}

person.sayName() // My name is undefined
```
Oops! That happens because variable made with let or const are not accessible from the global scope, that is, the window object.  

The arrow function is anonymous - it can't have a name. It is effective for a concise expression and it is useful whenever "this" context is not needed. Also, the arrow function doesn’t have the "arguments" keyword as in:

```js
const add = () => arguments;
add(); Uncaught ReferenceError: arguments is not defined
```

Do you see that?

# What are shorthand method definitions?

They are used to define methods in an object or a class without a property name as in:

### Literal object example
```js

const person = {
    name: "Ayobami",
    sayName() {
        return `My name is ${this.name}`;
    }
}

person.sayName() // My name is Ayobami
```

### class object example
```js

class Person {
    constructor(name){
        this.name = name;
    }
    sayName() {
        return `My name is ${this.name}`;
    }
}

const person = new Person('Ayobami');
person.sayName('Ayobami'); // Ayobami
```

# Instantly Invoking Function Expression (IIFE)

It is a way of making a function call itself as it is defined in:

```js
( function () {
    return "Involked";
})();

```

# Basic things you should know about a function

1. A good function/method does one thing as in:

```js
const sayHello = (name) => `Hello, ${name}`;
console.log(name);
```

2. A good function/method name describes what it does as in:

```js
const add = (firstNumber, secondNumber) => firstNumber + secondNumber;
add(5, 6);//11
```

3. Each of the function parameters can have default values as in:

```js
const add = (firstNumber = 2, secondNumber = 3) => firstNumber + secondNumber;
add();// 5
```
4. A regular function needs to use the return keyword to return a value or "undefined" will be returned as in:

```js
function multiply(firstNumber, secondNumber) {
   firstNumber * secondNumber;
}
multiply(6,7) // undefined
```

To correct the error above, we need to add "return" keyword to it as in:

```js
function multiply(firstNumber, secondNumber) {
   return firstNumber * secondNumber;
}
multiply(6,7) // 42
```
Yeah! Those are the basic things you have to know about functions in JavaScript as a total novice.

We will talk about their differences practically later in this course. 

See you in the next lesson. In the next lesson, we will talk about operators.

# One more thing

Are you having difficulties to learn and understand JavaScript and build projects with it? ***JavaScript for a Total Novice*** teaches JavaScript and Project Making Fundamentals with simple illustrations and examples that make everything so easy. You can now handle any difficult projects without fear.

Don't trust me, get a free previous to judge by yourself: https://bit.ly/3o3TMyg