1. Function Declaration

Probably the most common way to declare a function. Let’s look at its syntax:

Syntax for Function Declarations

Function Declaration comprises of the keyword function followed by the mandatory name of the function and then the parameter within a pair of parenthesis (you can also define a function without an argument). Finally, within a pair of curly braces is the body of the function, which performs an actual task.

It’s important that you know the difference between parameter and argument of a function. A parameter is a variable when defining a function. When a function is called, the arguments are the actual data you pass into the functions parameters.

First, let's look at a simple example:

A function named hello is declared with an argument name , which logs a message in the console. As you can see from the example, since no type is specified on the argument it works for both string and number. But what if I just want my function to greet a name, not a number? Sadly there is no pre-built method of doing this in Javascript, so we have to manually check the type of the argument that’s passed in the function like this:

By default, functions return undefined. To return any other value, the function must have a return statement that specifies the value to return.

What is Hoisting in the Function Declaration?

Simply put, it means no matter where you declare functions or variables when the code is executed, they’re moved to the top of their scope. This is known as hoisting.

Let's take a look at an example:

Hoisting in Function Declaration

Here I called the function before I even declared — this is hoisting.