Let’s understand functions in JavaScript

Let’s understand functions in JavaScript

A function is a code block that can perform tasks. They allow us to use the same code again and again with different parameters resulting in different outputs. Functions are considered the main building blocks of JavaScript. To use a function, we must define it somewhere in the scope where it is being called and executed. Let’s talk about how we can define functions in JavaScript.

Defining a Function

  1. Function declaration

    Declaration begins with function keyword followed by code content to be executed when calling the function in {} paranthesis. Let’s see an example,

     // parameter : side of square
     function areaOfSquare(side) {
       return side * side;
     }
    

    Parameters provided to functions are passed by value — so if the code within a function assigns a new value to a parameter, the change won’t be reflected globally or in the execution context of that function.

  2. Function expression

    While we can define a function using keyword, we can also created by a function expression. Let’s look at an example,

     let findArea = function(side) {
         return side * side
     };
    

A function expression is created when the execution reaches it and is usable from then onwards. A function declaration can be called earlier than it is defined. A global function declaration is visible across the whole script. When JavaScript prepares execution context while it’s in the initialization stage, it looks for global declarations first and creates functions.

Calling a function

Function declarations or expressions do not call it. Functions must be in scope when they are called. For the examples above, we can call as follows:

console.log(areaOfSquare(5))
// 25

There is a special keyword available in functions, arguments. It is available within non-arrow functions. It’s an array-like object which is accessible inside the function that contains the values of the arguments passed to that function.

function func1() {
  return arguements[0] * arguements[1]
}

func1(20, 40);

Scope of function

Variables inside a function cannot be accessed from outside, because the scope of a variable is defined by the scope of the function. However, we can access outside variables inside a function.

// variable defined in global scope
var name = 'John'

// Function defined in global scope
function greeting() {
    let action = 'Where are you going?'
    console.log(`Hey ${name}!, ${action}`)
}

greeting()
// returns Hey John!, Where are you going?

Conclusion

In this post, we learned what functions in JavaScript are all about and how we can write our own functions.

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

I hope you enjoyed reading this article. To learn more about functions, stay tuned!