The crazy world of javascript functions

connorholland54

Connor Holland

Posted on May 24, 2021

The crazy world of javascript functions

When I first began learning about javascript, the one thing that was by far the most confusing was the different types of functions that javascript has to offer.

The two key ways to declare functions is through function declarations and function expressions.

Let's begin by taking look at an example of a function declaration.

function greeting(name) {
return `Hello, ${name}!`
}

greeting("Tom")
// => "Hello, Tom!"
Enter fullscreen mode Exit fullscreen mode

Above is an example of a function declaration. We can see that the function is declared using the 'function' keyword. It is then followed by the name of the function, in this case 'greeting'. Next, we are taking in a argument 'name' which then will be interpolated into our return string. Thus, when we call greeting and passing in a name like 'Tom', we can fairly expect it to return "Hello, Tom!"

Next, let's take a look at function expressions. Functions have similar syntax to function declaration, however something to note is that function expressions are not hoisted. This means we cant call the function expression before we actually declare it. Function expressions can also be declared without a name. This is what is known as a anonymous function. A lot of time you may see function expressions that are anonymous written like this...

let sum = function(num1, num2) {
return num1 + num2
}

sum(1, 2)
// => 3
Enter fullscreen mode Exit fullscreen mode

We can see that we are creating a variable called sum and setting it to an anonymous function that takes in two numbers and then sums them. We then call this function expression by initializing the variable and passing in two numbers.

💖 💪 🙅 🚩
connorholland54
Connor Holland

Posted on May 24, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related