DEV Community

Cover image for A Simple Guide to JavaScript Functions - Native, Arrow and Shorthand.
Ayobami Ogundiran
Ayobami Ogundiran

Posted on • Edited on

A Simple Guide to JavaScript Functions - Native, Arrow and Shorthand.

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:

function name(parameter1, parameter2, etc) {
    //function body
}
Enter fullscreen mode Exit fullscreen mode

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:

name(argument1, argument2, etc);
Enter fullscreen mode Exit fullscreen mode

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

name();
Enter fullscreen mode Exit fullscreen mode

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

function sum(firstNumber, secondNumber) {
    const total = firstNumber + secondNumber;
    console.log(total);
}
Enter fullscreen mode Exit fullscreen mode

Let's call it now as in:

sum(4, 4); // we should see 8 in the console.
Enter fullscreen mode Exit fullscreen mode

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:

let multiply = function (firstNumber, secondNumber) {
    return firstNumber * secondNumber;
}
Enter fullscreen mode Exit fullscreen mode

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:

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

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:

let multiply = (firstNumber, secondNumber) => firstNumber * secondNumber;
multiply(4, 5) // 20
Enter fullscreen mode Exit fullscreen mode

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:

let add = (firstNumber, secondNumber) => firstNumber + secondNumber;
add(2,3)// 5
Enter fullscreen mode Exit fullscreen mode

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:

const add = (firstNumber, secondNumber) => {
    return firstNumber + secondNumber;
}
add(5, 4) // 9
Enter fullscreen mode Exit fullscreen mode

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:

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

// define sum()
function sum (firstNumber, secondNumber) {
    return firstNumber + secondNumber;
}
Enter fullscreen mode Exit fullscreen mode

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:

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

//call sum()
sum(5, 7) // 12
Enter fullscreen mode Exit fullscreen mode

Hey, stop teaching nonsense!

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

See it with your eyes in:

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

//define sum()
const sum = (firstNumber, secondNumber) => firstNumber + secondNumber;
Enter fullscreen mode Exit fullscreen mode

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:

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

person.sayName() // My name is
Enter fullscreen mode Exit fullscreen mode

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:

var name = "Biden";

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

console.log(person.sayName()) // My name is Biden
Enter fullscreen mode Exit fullscreen mode

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:

let name = "Biden";

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

person.sayName() // My name is undefined
Enter fullscreen mode Exit fullscreen mode

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:

const add = () => arguments;
add(); Uncaught ReferenceError: arguments is not defined
Enter fullscreen mode Exit fullscreen mode

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


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

person.sayName() // My name is Ayobami
Enter fullscreen mode Exit fullscreen mode

class object example


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

const person = new Person('Ayobami');
person.sayName('Ayobami'); // Ayobami
Enter fullscreen mode Exit fullscreen mode

Instantly Invoking Function Expression (IIFE)

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

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

Enter fullscreen mode Exit fullscreen mode

Basic things you should know about a function

  1. A good function/method does one thing as in:
const sayHello = (name) => `Hello, ${name}`;
console.log(name);
Enter fullscreen mode Exit fullscreen mode
  1. A good function/method name describes what it does as in:
const add = (firstNumber, secondNumber) => firstNumber + secondNumber;
add(5, 6);//11
Enter fullscreen mode Exit fullscreen mode
  1. Each of the function parameters can have default values as in:
const add = (firstNumber = 2, secondNumber = 3) => firstNumber + secondNumber;
add();// 5
Enter fullscreen mode Exit fullscreen mode
  1. A regular function needs to use the return keyword to return a value or "undefined" will be returned as in:
function multiply(firstNumber, secondNumber) {
   firstNumber * secondNumber;
}
multiply(6,7) // undefined
Enter fullscreen mode Exit fullscreen mode

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

function multiply(firstNumber, secondNumber) {
   return firstNumber * secondNumber;
}
multiply(6,7) // 42
Enter fullscreen mode Exit fullscreen mode

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

Top comments (6)

Collapse
 
lucassperez profile image
Lucas Perez • Edited

I'm very new to JS, so I'm probably missing something, but is there an advantage to using a function expression instead of a regular function declaration? Assuming we're not using the arrow.
I mean, between:

function add(number1, number 2) {
    return number1 + number2;
}
Enter fullscreen mode Exit fullscreen mode

And

const add = function (number1, number2) {
    return number1 + number2;
}
Enter fullscreen mode Exit fullscreen mode

Are there practical differences?
Maybe I can hoist the second if I use a var declaration and that is desirable?

Collapse
 
codingnninja profile image
Ayobami Ogundiran • Edited

I like this question because it feels like what I should have explained in the write-up.

Function expressions are not hoisted even when we use them with "var";

Thanks for raising the question.

The practical differences could be:

  1. We can't define or declare a regular functions in a conditional statement like if it is necessary to do so (but it is rarely necessary if not impossible), in that case we have to use function expression.
(function() {
  'use strict';
  if (true) {
    function going() {
      return 'yes';
    }
  } else {
    function notGoing() {
      return 'no';
    }
  }
  console.log(typeof going === 'undefined'); // => true
  console.log(going()); // Throws "ReferenceError: going is not defined"
})();
Enter fullscreen mode Exit fullscreen mode

We will use function expression to make it work.

Note: Declaring a function in a conditional statement is not recommended or should be avoided.

2 . It is easy to pass a function expression around so it is used to create modules without worrying about polluting the global scope before the introduction of import and export.

Collapse
 
lucassperez profile image
Lucas Perez

Thanks very much! Very nice text (:

Collapse
 
dafazakhulhaq27 profile image
Dafa Zakhulhaq

great post

Collapse
 
codingnninja profile image
Ayobami Ogundiran

Thanks.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.