DEV Community

Cover image for An overview to functions in JS
Deepak Kumar
Deepak Kumar

Posted on

An overview to functions in JS

Functions are one of the basic concepts in programming. As the name suggests, it performs a function. A function is a block of code that you can use whenever you need and wherever you need to avoid repeated code blocks. Once a function is written, it can be used over and over again. They usually take some input, perform some operations on it and produce some output.

In this article, we will learn about functions in JavaScript, different ways of defining functions, how hoisting and function scope works and a few more concepts regarding functions.

The function declaration

Functions are defined, or declared, with the function keyword. The declaration begins with the function keyword, followed by the name of the function then set of parentheses, which can be used for optional parameters. The code of the function is contained in curly braces.

function nameOfFunctionGoesHere (parameters) {
  // Things that you need to do goes here

  return "Something that you need to return";
}
Enter fullscreen mode Exit fullscreen mode

For example, If you are building a simple application which return multiplication of two numbers that is it will take two integers as input and return the product as output.

function product(numberOne, numberTwo) {
  return numberOne * numberTwo;
}
Enter fullscreen mode Exit fullscreen mode

The name of the function can be anything, and it follows the same rules as declaring variables. It's a best practice to tell what the function is doing by giving the function name a verb as a prefix. The function should perform only one task and have a single responsibility.

Function Parameters

Parameters are input that gets passed into functions as names and behave as local variables. A function can have multiple parameters or no parameters at all.

Let us assume you declared a parameter but forgot to pass an argument to it, so in that case your parameter would be undefined which is the default behaviour.

Return statement

A JavaScript function can have an return statement but it is completely optional and is only required if you want to return a value from a function.

The return statement should be last in a function as it stops the execution of a function and returns a value from that function. A function always returns a value, If the return value is not specified then undefined is returned.

Function expression & calling a function

A function expression looks similar to function declarations, except for the fact that function is assigned to a variable name.

const product = function (numberOne, numberTwo) {
  return numberOne * numberTwo;
}

// calling a function
product(10,20);      //output : 200
Enter fullscreen mode Exit fullscreen mode

Hoisting

Hoisting can be thought up as how execution contexts work in JavaScript. It means variable and function declarations are moved to the top of scope before execution which allows you to use a function before you declare it in your code.

Function declarations are hoisted but function expressions are not.

Functions defined in a function declaration are hoisted, which means that you can use the function although it's defined below the code using it. Hoisted functions are made available everywhere within the current scope.

For example

//function is invoked before the declaration
product(10,20);  //output : 200

function product(numberOne, numberTwo){
  return numberOne * numberTwo;
}
Enter fullscreen mode Exit fullscreen mode

As opposed to function declarations, function expressions are not hoisted and can therefore not be used before they're defined.

For example

product(10,20);  //output : TypeError: sum is not a function

var product = function (numberOne, numberTwo){
  return numberOne * numberTwo;
}
Enter fullscreen mode Exit fullscreen mode

Immediately Invoked Functions

Functions that are executed as soon as they are declared,
are known as Immediately Invoked Function Expressions or IIFEs. IIFEs follows a particular syntax as shown below.

(function (){ 
// code to be executed
})();
Enter fullscreen mode Exit fullscreen mode

Here are few important things about IIFEs:-

  • The variable within the expression can not be accessed from outside it.
  • IIFEs are very useful because they don’t pollute the global object, and they are a simple way to isolate variables declarations.
  • While creating a bunch of variables and functions in the global scope that no one uses outside your code, just wrap all of that in an IIFE and your code will continue to work, but now you are not polluting the global scope.

Arrow functions

Arrow functions are mainly syntactic sugar for defining function expressions. These allows us to write functions in a much shorter syntax and is one of the most popular features of ES6. We can now create more concise, cleaner, and more readable functions by using the => operator.

The syntax is as follows

()=>{ /*code to be executed*/ }
Enter fullscreen mode Exit fullscreen mode

Let's rewrite the product function that we wrote using arrow functions:-


//Normal function
function product(numberOne, numberTwo) {
  return numberOne * numberTwo;
}

//arrow function
const product = (numberOne, numberTwo) => numberOne * numberTwo

Enter fullscreen mode Exit fullscreen mode

The primary use case of arrow functions is for functions that get applied over and over again to items in a list.
For example, if you have an array of values that you want to transform using a map, an arrow function is ideal.

const numberArray= [10, 20, 30, 40, 50];
const squareOfNumbers = numberArray.map(item => item*item);

console.log(squareOfNumbers);
// output : [100, 400, 900, 1600, 2500]

Enter fullscreen mode Exit fullscreen mode

Some important things to remember about arrow functions:-

  • Just like function expressions, arrow functions aren't hoisted — only function declarations are.
  • Arrow functions cannot be named & they lexically bind the current this value. That means The treatment of this within an arrow function is different than within non-arrow function expressions.

There are a few more ways we can define functions, which aren't discussed in this article. The decision of which declaration type to choose depends on the situation.

Scope of function

When a variable is declared inside a function, it can be accessed only within that function and is not visible outside of the function.
For example:-

function printName(){
  var name = "Deepak";  //function scope
  console.log(name);
}

 printName();   // output : Deepak
 console.log(name);   // output : name is not defined
Enter fullscreen mode Exit fullscreen mode

Lexical scope

When a function is defined in another function then in that case the inner function has access to the outer function’s variables.
This behavior is called lexical scoping. However, the opposite is not true that is outer function does not have access to the inner function’s variables.

function name() {
  var userName = 'Deepak';

  function age() {
    var age = 23;
    console.log(`${userName} is ${age} years old.`);                
    //output : Deepak is 23 years old.
  }

  console.log(age) //output : Error, age is not defined
}

Enter fullscreen mode Exit fullscreen mode

So in this case when we access userName variable in age(), it works. But accessing the same age variable outside age() function throws an error.

Conclusion

So we learned what are functions, how to call them, the difference between parameters and arguments, different ways we can define functions, how hoisting and function scope works in JavaScript. And I hope you got a nice idea about functions in JavaScript.

That's it for now do connect with me on LinkedIn , Github ..

Top comments (0)