Declaration and Calling a Function in JavaScript

To use a JavaScript Function, we first have to create it and then use it. The creation part is known as Function Declaration and the usage part is known as Function Calling or Invoking.

The basic syntax for a Function is explained in our JavaScript Functions lesson.


Declaring a JavaScript Function 🧙‍♂️

Function Declaration involves creating a function and deciding what it’s name will be, how many parameters (inputs) it will use and what will it do with it.

NOTE: For a better understanding, we are now just going to learn declaration and calling of a function in JavaScript without any params involved. We will learn later about parameters in our next lessons.

Example

function helloWorld() {
    console.log("Hello World! I am a cute little function.");
}

The above code is explained as follows:

  • The keyword function explains to JavaScript, that a function is being created.
  • The function’s name is helloWorld.
  • Inside the curly braces { }, we have written all our function’s logic or steps.
    i.e. “console.log(“Hello World! I am a cute little function.”);“.

Calling a JavaScript Function ☎

Above, we created a function called helloWorld but for us to actually use it, we have to call it.

Calling a JavaScript Function is easy. We just type the function’s name along with paranthesis ( ). Calling a function is also called Invoking or Executing a function.

Example

// Declaring a Function
function helloWorld() {
    console.log("Hello World! I am a cute little function.");
}

// Calling or Using or Invoking a function
helloWorld();

Output

Hello World! I am a cute little function.

We can also define and call multiple functions. The order of execution of a function depends upon which function you call first.

Example

// Function 1
function mrAlexander() {
    console.log("I am Alexander, The Great!");
}

// Function 2
function mrGenghis(){
    console.log("I am Genghis Khan. The emperor of Asia.");
}

// Calling Function 2 first.
mrGenghis();
mrAlexander();
// Reusing Function 2 again.
mrGenghis();

Output

I am Genghis Khan. The emperor of Asia.
I am Alexander, The Great!
I am Genghis Khan. The emperor of Asia.

In this way, we can create reusable logic and reuse them in a concise manner 😎. That’s what JavaScript Functions are – reusable blocks of code. We learned about function declaration and calling in JavaScript in this lesson.

In our next lesson, you will learn about parameters in functions.