DEV Community

Cover image for JavaScript Functions Broken Down
Joel P. Mugalu
Joel P. Mugalu

Posted on • Edited on

JavaScript Functions Broken Down

A comprehensive introduction to JavaScript functions

Functions are a very important concept in JavaScript. Functions can be compared to building blocks. So Understanding them is one step toward true JavaScript mastery. In this article i am going to go over the basics of functions.

What is a Function?

Think of functions as vocabulary in human language. Different vocabularies help us to avoid repeating the same words. For example, Instead of saying “human being between the age of 13 and 19”. You can use one vocabulary, teenager. That gives you the freedom to use the word teenager to form different sentences without having to confuse yourself.

Functions follow a similar pattern, they allow us to wrap a whole program into one single expression. We can then call this expression our new vocabulary. We can then use it anywhere in our program to do different things.

Why Use Functions?

The ability to wrap a whole program into one single expression is very powerful.

  • It can make our code readable and maintainable.
  • In case we have to make changes we can do that in only one place. The place where we defined what the function should do and not where we used it.
  • Functions help us to avoid repetition. We define once and use in different places. This can save us from lots of bugs.

Function Declarations

JavaScript allows us to declare functions using the function keyword. This is then followed by the name of the function.

function functionName(parameter) {
    // Your Code Here
};
Enter fullscreen mode Exit fullscreen mode

Functions accept parameters and arguments. Think of parameters as the ingredients of the function. These ingredients are what we tell the function to receive. Then inside the curly braces ({}) we define what the function does with these ingredients. Parameters are only assigned a value during the function call. The values that a function receives when being called are then the arguments.

When the return keyword is used inside a function, the function stops execution at that point. The result of the function execution is then assigned to the function caller. Functions without the return keyword are assigned the value undefined. The function is then called or invoked by typing the function name with parentheses.

function testFunction() {
    return "Hello World";
};
testFunction(); // returns hello world

function addTen(number) {
   return number + 10;
};
addTen(20) // returns 30
Enter fullscreen mode Exit fullscreen mode

In the above examples the testFunction does not accept any arguments. It simply returns the string Hello World. It is called by typing the function name and using parenthesis after that.

The second function addTen accepts one argument and adds 10 to it. Functions can accept an unlimited number of parameters.

When a function receives more arguments than preset parameters, it uses the received arguments and ignores the rest. When it receives less, it assigns undefined to the parameters that did not receive arguments.

We can do different things with functions. For example we can assign them to variables and we can also use variables as parameters.

function isLegal (name, age) {
    if (age >= 18) {
        return `Hey ${name}, You're Legal`
    } 
  return `Hey ${name}, You're still a kid`;
};

let johnLegal, janeLegal;
johnLegal = isLegal("John", 25);
janeLegal = isLegal("Jane", 14);

johnLegal; // returns "Hey John, You're Legal"
janeLegal; // returns "Hey Jane, You're still a kid"
Enter fullscreen mode Exit fullscreen mode

The example demonstrates a function isLegal which accepts two arguments. Pay particular attention to how the functions were assigned to the variables. Also look out for ow the variables were passed as function parameters. I suggest you try this out on your own.

Function Expressions

Function expressions is another way of creating functions in JavaScript.
Consider the following example.

const greeting = function (name) {
return `Howdy ${name}`;
};
let greetJohn = greeting("John");
greetJohn; // returns Howdy John
Enter fullscreen mode Exit fullscreen mode

The example above demonstrates a function expression.The variable greeting is assigned the value of a function. This time we did not use the function keyword. Rather we declared a variable and assigned it the value of a function.

Arrow Functions

ES6 or ES2015+ introduced a new way of creating functions. This form is function expression is quite different. Instead of using the function keyword. We use an equal sign (=) after the function name then declare the function parameters. We then use a equal sign (=) and a greater than sign (>) together such as (=>). The following block is where we define what the function will do.

const functionName = parameters => {
    // Execute this code
}
Enter fullscreen mode Exit fullscreen mode

Its can be thought of as “This function takes these parameters and executes this code”
Consider the following example

const isLegal = (name, age) => {
    if (age >= 18) {
        return `Hey ${name}. You're Legal`
    } 
return `Hey ${name}. You're not Legal`
};

let denisLegal = isLegal("Denis", 21);
denisLegal; // returns Hey Denis. You're Legal
Enter fullscreen mode Exit fullscreen mode

One plus with arrow functions is that they provide a shorter way of writing functions. They can allow us to omit the parentheses after the equal sign if the function takes only one argument. The return keyword can also be omitted if the function returns something immediately.

const weatherCondition = weather => `It is currently ${weather}`;
Enter fullscreen mode Exit fullscreen mode

There is one main difference between function declarations and function expressions. Function declarations begin with the function keyword. But, function expressions are functions assigned to a variable.

Hoisting

Hoisting means that variable and function declarations are taken on top of their scope before execution. This makes them available to be used before the execution phase.

In JavaScript, all function declarations and arguments are stored in one object. The Variable object. This object is created before code execution, during the creation phase. During the creation phase all function declarations and arguments are stored into memory.

The creation phase happens in three steps

  • Code is ran line by line for function declarations and function arguments.
  • The variable object is then created. All the function declarations and arguments in the program are stored inside this object.
  • The function declarations then stored in the variable object point to the function.

Hoisting is step 2 and 3. Hoisting makes it possible for us to use function declarations and define the function later. Once the function is defined anywhere in the program it is stored in memory. So it’s available even before the program starts executing. It’s important to remember that hoisting only works for function declarations. With function expressions, we must define the function first then use it.

The following example demonstrates hoisting of functions.

let fullName = "Thanos";
let age = 33;
introduction(fullName, age); // returns Hey everyone. I'm Thanos and I'm 33
function introduction(name, age) {
    return `Hey everyone. I'm ${name} and I'm ${age}`
};
Enter fullscreen mode Exit fullscreen mode

Notice how we were able to use the introduction function before declaration. That is because the function was hoisted.

Good Practices

By now you must be very excited to start using functions right away. But there are some safe practices when using functions.

A good rule of thumbs is to try and keep your functions as short as 10–15 lines. Try to write functions that complete only one task.

Remember functions are like vocabulary, their to avoid repetition. So if you find yourself repeating one thing twice then consider writing a function for it.

Conclusion

Functions are a very powerful programming paradigm in JavaScript. Practice is key in understanding them and how they work. Try solving algorithmic challenges with functions. That’ll help for sure. If you’d like to connect with me i am very active on Instagram and Twitter. Do reach out.

Top comments (6)

Collapse
 
thisdotmedia_staff profile image
This Dot Media

Really organized and helpful article Joel!

Collapse
 
codingknite profile image
Joel P. Mugalu

Thank you...really Appreciate

Collapse
 
thisdotmedia_staff profile image
This Dot Media

Anytime :)

Collapse
 
kachinonye profile image
Kachinonye

Very helpful. Thank you!!

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