Important Methods For Defining Functions In JavaScript

A function is a sequence of instructions or a “subprogram” that can be invoked by the code that is external to that function. Generally, functions “encapsulate” a specific task. Functions are fundamental building blocks in JavaScript, and truly understanding functions can help to handle some of JavaScript’s oddities.

Functions in JavaScript-

JavaScript Functions

Note that functions in JavaScript are first- class objects. This basically implies functions in JavaScript can be dealt with like some other JavaScript object and can be referenced as other variables or passed as arguments to a function. Functions can even have properties and also different methods, much the same as some other JavaScript object. The main difference between a function and other objects is that a function can be invoked (or called).

Each function in JavaScript is a Function object. You can go into the console and try this out:

function typeCheck() {};
typeCheck instanceof Function // Logs True

The Function object has a some specific methods and properties, like apply, call, bind, isGenerator, and so forth, that are not available with other objects.

There are some different ways in which a function can be defined in JavaScript, and the way in which it is defined influences function behavior. Let us see each way.

Methods for defining functions in JavaScript-

1. Function declaration-

This might be the most natural approach to define a function. A function declaration consists of a name preceded by the necessary function keyword and followed by an optional list of parameters inside a required pair of parentheses ().

function sum(param1, param2) {
  return param1 + param2;
}

Two important things to note about this type of defining a function are:

  • A variable that holds the function object is created in the current scope with the same identifier as the function name provided- in our example, sum.
  • The variable is hoisted to the top of the current scope.

To understand this, let’s look at an example:

console.log(notYetDeclared()); // Logs 'Here!'
function notYetDeclared() {
  return 'Here';
}

We were able to invoke the function notYetDeclared before we defined it.

2. Function expression-

A function expression has similar syntax to a function declaration. The main difference is that a function expression does not need a function name.

let sum = function(param1, param2) {
  return param1 + param2;
};

Function expressions are a part of another statement. In the example above, the function expression is a part of the sum variable assignment.

Unlike function declaration, function expressions are not hoisted.

console.log(notYetDeclared); // Logs 'undefined'

let notYetDeclared = function() {
  return 'Here';
}

An interesting use case for function expressions is their ability to create IIFEs, or Immediately Invoked Function Expressions. Sometimes we should define a functions and invoke it directly after the definition, but never again.

Surely, it can be done with function declaration, however to make it more readable, and also to ensure that our program doesn’t accidently access it, we use an IIFE. Consider this example

function callImmediately(foo) {
  console.log(foo);
}
callImmediately('foo'); // Logs 'foo'

We create a function called callImmediately, which takes an argument and logs it, and afterward we quickly call it. A similar result can be achieved by doing this:

(function(foo) {
  console.log(foo);
})('foo'); // Logs 'foo'

The key difference is that in the first case, the function declaration dirties the global namespace, and the named function callImmediately stays nearby long after it is required. The IIFE is anonymous and hence can’t be called in the future.

3. Arrow functions-

Arrow functions are meant to be a syntactically compact alternative to function expressions. These Arrow functions are defined using a brackets pair containing a list of parameters, followed by a fat arrow => and afterward the function statements with curly brackets {}.

let sum = (param1, param2) => {
  return param1 + param2;
};

Since one of the important motivation behind the arrow function is syntax compactness, if the only statement in the arrow function is return, we can remove both the curly brackets and the return keyword, as so:

let sum = (param1, param2) => param1 + param2;

Also, the parens can be removed if we have just a single parameter being passed to the arrow function:

let double = param1 => param1 * 2;

Here are some key things to note in this form of function definition are:

1. An arrow function doesn’t have its very own this, and also it uses this value of the enclosing lexical scope. You can get more information about this here.

  let foo = {
    id: 10,
    logIdArrow: () => { console.log(this.id) },
    logIdExpression: function() {
      console.log(this.id);
    }
  }
  
  foo.logIdArrow(); // Logs 'undefined'
  foo.logIdExpression(); // Logs '10'


In the above example, we have an arrow function and function expression that logs foo.id using this.

2. An arrow function does not have the prototype property.

let foo = () => {};
      console.log(foo.prototype); // Logs 'undefined'

3. The arguments object is not available in an arrow function. 

4. Function constructor-

As referenced before, each function in JavaScript is a Function object, so to define a function, we can directly call the constructor of the Function object.

let sum = new Function('param1', 'param2', 'return param1 + param2');

The arguments are passed as a list of comma- separated strings ‘param1’, ‘param2’, …, ‘paramN’, and the last argument is the function body passed in as a string.

As per performance, this way of defining a function is less efficient than function declaration or function expression. Functions defined by using the Function constructor are parsed each time the constructor is called. Because the function body string should be parsed each time, in contrast to others, which are parsed with the rest of the code.

One use case for defining functions just like this is a way to access the global object in Node or the window object in the browser. These functions are constantly made in the global scope and also don’t have access to the current scope.

Final words-

Here you have seen some important methods that you can use for defining functions in JavaScript. There can be fewer also. Selecting the best one according to the requirement is crucial act. If you are confused about how to do this, consult with Solace experts. Expert’s team is here to help you with new trends for JavaScript development. Connect with Solace team for effective development. We will be happy to help you.

Related Post