Functions In JavaScript

Functions In JavaScript

Prerequisites

You should be familiar with some fundamental JavaScript concepts such as variables, expressions, and conditional statements to follow along with this article.

What is a Function in JavaScript?

A function is a block of reusable code written to perform a specific task. You can think of a function as a sub-program within the main program. A function consists of a set of statements but executes as a single unit.

In JavaScript, we have some browser built-in functions like alert(), prompt(), and confirm(). You have probably used these in your project before, right? But you can still create your custom (own) functions.

There are several ways to define a function. Most commonly, we have function declaration and function expression.

Define a Function using Function Declaration

You write a function declaration like this:

function nameOfFunction() {
    //some code here....
}

Let's break it down:

  • Function keyword

  • The name of the function

  • Parentheses (which can take in parameters, or also be empty)

  • The body of the function (wrapped in curly braces).

Here's an example:

function sayHello() {
    console.log("Hello world"); 
}

This function won't do a thing – in this case, output Hello world – unless you call it. The term for this is invoking the function.

Here’s how to call the function:

sayHello();

//output: Hello world

Parameterized Function

Here’s Example:

function sum(num1, num2){
    return num1 + num2;
}

To invoke this function, we call it like this:

sum(1, 2);

//output: 3

You can see a slight difference between our first function above example and the second (parametrized).

If you guessed that it's the content within the parenthesis of the second function, then you’re right!

The function sum() took in two parameters when we defined it – num1, and num2. And when we call it, we passed in two values – the arguments, 1 and 2. Let me explain what these two terms (parameters and arguments) mean.

A parameter is a variable you pass to a function when you declare it.

Suppose you want your function to be dynamic so that it applies the function’s logic to different sets of data at different times. That’s where parameters come in handy. This way, your function doesn’t just output the same result repeatedly. Instead, its result is dependent on the data you pass in.

An argument, on the other hand, is the value equivalent to the parameter that you pass to the function when you call it.

So the syntax for declaring a function with parameters will look like this:

function nameOfFunction(parameters){
    //function body.....
}

And to invoke it:

nameOfFunction(arguments)

How to Use the Return Keyword in a Function

To create a function that will resolve to a value after the function is invoked, you use the return keyword. You write this within the body of the function.

return is a directive that returns a value to the function after the code within it has been executed.

Here’s an example of a function that returns a value, in this case, the sum of two numbers:

function sum(a, b){
    return  a * b;
}

sum(10, 20);

//output will be 200

Using return inside a function makes it easy to manipulate the data the function returns, by either passing it as a value to, say, another function or performing additional operations on it.

Arrow Functions in JavaScript

Arrow functions are yet another notation of a function expression but they have a shorter syntax. They were introduced in ES6 and help us write cleaner code.

Here, the function keyword is excluded and we use an arrow symbol (=>) instead. The syntax looks like this:

let nameOfFunction = (parameters) => {
    //function body
}

If the function body within the curly braces contains only a single statement, then the braces can be omitted. An arrow function with curly braces must include the return keyword.

Example:

let hello = "";

hello = () => {
  return "Hello World!";
}

Hoisting Of Functions

Hoisting in JavaScript is a behavior in which a function or a variable can be used before declaration. For example,

// program to print the text
greet();

function greet() {
    console.log('Hi, there.');
}

Output

Hi, there

Immediately Invoked Function Expressions (IIFEs)?

IIFE is another function expression notation (explicitly an anonymous function) that works in isolation and is independent of any other code. It gets invoked immediately where it is defined.

The syntax is as follows:

(function (){
    //function body
})();

A use case of IIFE would be to enclose a variable that you may likely not use again inside your code. So, as soon as the function is executed, the variable ceases to exist.

Example:

(function()  
 {  
 console.log("Hello World");   
})();

Output:

Hello World

Takeaway

You have learned what functions in JavaScript are all about and how you can write your custom(own) functions.

With functions, you can organize your code by grouping everything into separate blocks that perform different tasks.

That's it for the day see you in the next blog until then...

Keep Writing Code ❤️