Javascript Functions

Javascript Functions

Introduction

Functions are one of the fundamental building blocks in JavaScript. Functions help modularize the code by splitting them up. All functions in JavaScript return a value. Even those that do not have a return statement. If you call a function that has no return statement, the returned value would be undefined.

Returning a value explicitly,

function info(){
    return "Hello World";
}
var a = info();
console.log(a);// Prints `Hello world`

No return statement, but returns undefined anyway,

function info(){
    console.log("Hello world");
}
// The info function prints `Hello world` and returns undefined
var a = info();
console.log(a);// undefined

Types of functions

Function declaration

If the keyword function is the 1st thing in a statement, that is a function declaration. The ‘hello’ function here is a function declaration.

function hello(){
    return "Hello";
}

Take a look at another example. hello is a function declaration. So is world.

function hello(){
    var a = world();

    function world(){
        return "World!";
    }
    return "Hello" + a;
}
console.log(hello()); // HelloWorld!

Function expression

A function expression has the same syntax as a function declaration, except that we can save a function expression in a variable and pass around in the code. A function expression looks like this,

var myFunction = function namedFunction(){
    statements
}

An example for this would be,

let greeting = function(){
    return "Hello Coder!"
};

The function expression defined above is an anonymous function expression. It is called like that because it has no name after the keyword function. We can not create a function declaration without a name. But for a function expression, we can.

We can also create a named function expression.

var greeter = function hello(){
    return "Hello, how do you do?";
}
greeter(); // Hello, how do you do?

The variable name greeter and the function expression’s name hello can be different. The variable greeter here, simply holds the reference to the actual function which may have a name or may not have a name in the case of an anonymous function. Also the function hello can be assigned to any number of variables. It’s name won’t change.

The advantage of a named function expression is that during the debugging or checking the stack trace of an error, the name of the function will be available. It will become easier to track down the error with a named function expression. It is a best practice to use the named function expression.

As you can see, the function expressions do not start with the keyword function, but with a variable name. In our case above, they have started with let greeting and var greeter. This is the cue for a function expression.

Immedietely invokable function expression (IIFE)

We can create one-time usable functions. They are invoked as soon as they are declared. They look like this,

(function(){
    statements
})();

An example,

(function(){
    console.log("I am IIFE");
})();

We can also pass arguments

(function(name){
    console.log("Hello",name); // prints "Hello Alan"
})("Alan");

A function declaration inside this (...)() is an IIFE. The IIFE above is an anonymous IIFE. We can create a named IIFE too.

(function process(task){
    console.log("Executing the task",task);
})("Run forrest, RUN!!");

Instead of creating an IIFE like this (function(parameters){...})(arguments) we can put the last set of parentheses inside too. Like (function(parameters){...}(arguments)). The following code is same as above,

(function process(task){
        console.log("Executing the task",task);
}("Run forrest, RUN!!"));

If you have a named function declaration, you can execute that by simply adding a parentheses at the end.

function tryMe(arg){
    console.log(arg);
}("Hello there!");

But trying to do the same with an anonymous function expression will result in syntax error.

Parameters and arguments

Parameters are the variables used when defining a function. In the code below num1, num2 are parameters. We usually use them interchangeably, but there is a distinction.

function testMe(num1, num2){

}
testMe(10,20);

Arguments are the values that a function receives from the parameters. In the example above, the arguments are 10 and 20. By default every function has an array-like object built-in to that. All the arguments that are passed to a function is available in the arguments object.

function info(num1, num2){
    console.log(arguments);
}
info("Hello","World");// prints {'0':'Hello','1':'World'}

The arguments object is extremely helpful when we want inspect all the values of the parameters.

Functions as objects

In JavaScript functions are also considered to be objects. Check the example below

function getStudent(){
    var studentObj = {
        name:"Harry",
        age:13,
        school:"Hogwarts"
    };
    return studentObj;
}
var obj = getStudent();
console.log(obj);//{ name: 'Harry', age: 13, school: 'Hogwarts' }
  • The getStudent function returns an object.
  • We store this in a variable named obj and then print it.
  • Now we are able to return an object and further process it. In our case we are simply printing it, but we can do things like adding more properties or changing the values or pass it another function.
  • We can do those things with functions too. We can return a function from another function, store it in a variable or treat it pretty much like any other object or variable.

    function getSandwichMaker(){
    return function sandwichMaker(type, size){
        console.log("Preparing a delicious, "+size+", "+type+" sandwich");
    }
    }
    let createSandwich = getSandwichMaker();
    // Prints 'Preparing a delicious, large, Cheese sandwich'
    createSandwich("Cheese","large");
    // Prints 'Preparing a delicious, medium, Vegetable sandwich'
    createSandwich("Vegetable","medium");
    

When a function is also treated like a variable in a programming language, that programming language is said to have first-class function support.

In the getSandwichMaker example above, we are returning the function sandwichMaker from the getSandwichMaker, we are storing it in the createSandwich variable and we repeatedly use the function by calling it with different arguments.

Another example, using the built-in setTimeout function. setTimeout is a function that is part of the global object. We can pass a function as an argument to it and specify a time in milliseconds after which the function that we have passed will be called. This code will create an alert box after 3 seconds.

var alertMsg = function alertFunction(){
    alert("Hello there!!!");
}
setTimeout(alertMsg,3000);

One more example, which shows that we can pass around functions and resue them when needed.

function titleMaker(gender){
    let manTitle = "Mr.";
    let womanTitle = "Mrs.";

    if(gender==="man")
        return function(name){
            return manTitle+name;
        }
    else
        return function(name){
            return womanTitle + name;
        }
}
let formatManName = titleMaker("man");
formatManName("Tagore"); // Mr.Tagore
formatManName("Gandhi"); // Mr.Gandhi
let formatWomanName = titleMaker("woman");
formatWomanName("Curie"); // Mrs.Curie
formatWomanName("Sarojini");// Mrs.Sarojini

The typeof operator returns function for Function objects (i.e.) for all the function.

var func1 = function(){
    return "101";
}
console.log(typeof func1);// prints `function`
var func2 = func1;
console.log(func2===func1);// 'true'

To check if a variable is a function

var product = function(val){
    return val * val;
}
// Check if the product variable is a function and call if it is
if(typeof product === 'function'){
    product(10);// prints 100
}

Now this is also an example for the first-class function support in JavaScript.

This post touches the basics of functions in JavaScript. Check out this MDN documentation for an in-depth coverage.