11 Things About JavaScript Functions that .NET Developers Should Know: Part 1

I have often seen .NET developers struggle with JavaScript. They try to compare C# functions with JavaScript functions and usually make some minor but conceptual mistakes while using it. We can all agree that JavaScript functions are the backbone of the JavaScript programming language, and if one has a good understanding of the function, then using JavaScript is easier. So in this two parts series, I will focus some important concepts of JavaScript functions.

In this part of the series, we will cover the following six topics:

  1. JavaScript functions as an expression
  2. JavaScript functions as a statement
  3. Return statements in JavaScript functions
  4. Parameters in JavaScript functions
  5. The Arguments object in JavaScript functions
  6. Varargs JavaScript functions

JavaScript functions can be an expression

A JavaScript function can be an expression, as seen below:

var add = function Add(num1, num2) 
{
    var result = num1 + num2;
    return result;
};
 

A function expression creates an instance of the function object. It can be passed as an argument to a function, it can be returned from a function, and it can be assigned to a variable or an array. A function expression can be created with the name as shown here:

var add = function Add(num1, num2) 
{
    var result = num1 + num2;
    return result;
};
var s = add(34, 67);
console.log(s);
 

A function expression can be created without the name as shown here:

var sub = function (num1, num2) 
{
    var result = num1 - num2;
    return result;
};
var r = sub(5, 9);
console.log(r);


We cannot use a function expression before it has been created. So if in above code snippet, we call the sub function before it’s created as shown below:

var s = sub(34, 67);
console.log(s);
var sub = function (num1, num2) 
{
    var result = num1 - num2;
    return result;
};
 

We will get an exception as shown below:

To understand why we are getting the above exception, let’s try to understand how var works in the JavaScript. When you assign something to var using an assignment, JavaScript first creates var on the top of the function with the value undefined in it. Essentially var statements get converted in two parts. For every var, at the top of the function, JavaScript will create a variable with undefined value assigned to it. Later the real value will be assigned to the variable.

This is the reason when we try to invoke a function expression before it was created, we got the exception that undefined is not a function.

JavaScript functions can be a statement

A JavaScript function can be created as a statement too, as shown below:

function Factorial(n) 
{
    if (n <= 1) {
        return 1;
    }
    return n * Factorial(n - 1);
}

When we create a JavaScript function as statement, it is mandatory to give a name to the function. When we create a function statement, JavaScript creates an object and assigns that to the variable. So usually, when you create a function statement, JavaScript creates a variable with the same name as the function. Unlike the function expression, a function statement can be invoked before it is defined. As you see below, the code will not throw any exceptions.

var result = Add(9, 8);
console.log(result);

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

Function statements are moved to the top of the script, so they can be invoked before they are defined.

Return statements in JavaScript functions

A JavaScript function may or may not have a return statement. By default, a JavaScript function returns value undefined. Explicitly you can return an expression from the JavaScript function. If there is no expression, then the JavaScript function is returned as undefined.

We have seen that the JavaScript function can return an expression as shown below:

function Add(num1, num2) 
{
    return num1 + num2;
}
var result = Add(1, 2);
console.log(result);
 

And you can also have a JavaScript function without a return statement as shown below:

function Foo() 
{
    // function body 
}
var result = Foo();
console.log(result);

The value undefined will be printed on the console because the JavaScript function does not return any value. Another scenario may give you an expressionless return statement in the function. In this case an undefined value will also be returned from the JavaScript function. The function defined below will also return an undefined value.

function Foo() 
{
    // function body 
    return;
}
var result = Foo();
console.log(result);
 

Keep in mind that a JavaScript function constructor, by default, returns the invoking object; not the undefined value.

Parameters in JavaScript functions

JavaScript does not:

  1. Type-check the parameters
  2. Check the number of parameters being passed

However, you can essentially pass any type or number of parameters in a JavaScript function. You can pass fewer parameters than declared or more parameters than declared, and when you invoke a function with less parameters than are declared, the additional parameter values are set to undefined. Let’s see this in action.

Here we have a JavaScript function Add which takes two parameters. However, we are passing only one parameter while invoking the function:

function Add(num1, num2) 
{
    console.log(arguments.length);
    console.log(arguments[0]);
    console.log(arguments[1]);
    var result = num1 + num2;
    return result;
}
var result = Add(8);
console.log(result);
 

As a result, you will see that arguments.length prints 1 and arguments[1] prints undefined, so you can pass less parameters than declared parameters. Additional parameters will have an undefined value. Note: we will discuss the arguments object in my next post.

On the other hand, you can pass more parameters than there are declared, and you can access those additional parameters using the arguments object. There is no way you can refer to additional parameters with a named argument; you can access it only using the arguments object:

function Add(num1, num2) 
{
    var result = num1 + num2 + arguments[2];
    return result;
}
var result = Add(8, 9, 10);
console.log(result);
 

As the output of the above snippet, you will get 27 printed. JavaScript functions support a variable number of parameters. By default, it will pass undefined for all parameters whose value is not passed, and will simply ignore any additional parameters passed.

The arguments object in JavaScript functions

When we invoke a JavaScript function, along with parameters, the arguments object also gets passed to the function. Let us consider the Add function as defined below:

function Add(num1, num2) 
{
    console.log(arguments.length);
    return num1 + num2;
}
var result = Add(1, 2);
console.log(result);
 

As you’ll see, inside the Add function, we are printing length of the arguments. Since we are passing two parameters to the function, 2 will be printed for the length of the arguments object. In JavaScript, along with the parameters, the arguments object also gets passed. It allows us to access the parameters with the number rather than the parameter’s name. Using the arguments object, the Add function can be rewritten as shown below, and it will print the exact output.

function Add(num1, num2) 
{
    console.log(arguments.length);
    return arguments[0] + arguments[1];
}
var result = Add(1, 2);
console.log(result);
 

The arguments is an array-like object, but it is not a JavaScript array. Any JavaScript array operations on the arguments object will throw an exception. For example, the push and pop method will throw exception. It’s very likely that the code snippet below will throw an exception because that object does not have a pop or push method.

function Add(num1, num2) 
{
    console.log(arguments.length);
    var a = arguments.pop();
    arguments.push(45);
    return arguments[0] + arguments[1];
}
var result = Add(1, 2);
console.log(result);
 

You can use the arguments object to throw an exception when the user does not pass the expected number of parameters. Let’s say in the add function, you want to throw an exception when users pass less or more than two parameters while invoking the function. This can be done using the arguments object as listed below:

function Add(num1, num2) 
{
    if(arguments.length !=2)
    {
    	throw new Error("Pass exactly two parameters");
    }
    return num1+num2; 
}
var result = Add(1,2,3);
console.log(result);
 

The arguments object is very useful to fetch additional parameters being passed and restricted to invoke the function with specified numbers of parameters.

Varargs JavaScript function

Varargs functions are those functions which work on any number of parameters. Using the arguments object, all the passed parameters can be iterated and used. Let’s consider the listing shown below, where the add function takes a variable number of parameters and returns a summation of all the passed parameters:

function Add(/* pass any number of parameters */) 
{
    var sum = 0;
    for (var i = 0 ; i < arguments.length; i++)
     {
        sum = sum + arguments[i];
     }
    return sum;
}
var result = Add(7, 8, 9);
console.log(result);

var result1 = Add(5, 6, 78, 93, 5);
console.log(result1);
 

In the Add function, we are passing a different set of parameters and using the arguments object, adding the passed parameters and returning the summation. The Add function is a varargs JavaScript function.

Summary

In this part of the series, we covered the following six topics:

  1. JavaScript functions as an expression
  2. JavaScript functions as a statement
  3. Return statements in JavaScript functions
  4. Parameters in JavaScript functions
  5. The Arguments object in JavaScript functions
  6. Varargs JavaScript functions

The topics we’ve discussed here are vital when using JavaScript functions, and in the next part of this series we’ll cover invocation patterns, high level functions and more.


Tags /

Comments  (7 )

LUIS LEDESMA
on Mon, Feb 16 2015 5:07 PM

Very clear explanation. Thanks for sharing.

Korea Evangelist
on Mon, Feb 16 2015 11:56 PM

안녕하세요. 한 주간의 마이크로소프트의 개발 관련 주요 소식들을 정리합니다. 관련 영상 : This Week on Channel 9 - TouchDevelop, Microsoft

Dhananjay Kumar
on Tue, Apr 14 2015 4:02 AM

This is the second part of the series in 11 Things about JavaScript Functions that .NET Developers Should

hamzath kp
on Wed, May 6 2015 12:54 AM

Nice

hamzath kp
on Wed, May 6 2015 12:55 AM

Nice

hamzath kp
on Wed, May 6 2015 12:55 AM

Nice

Dhananjay Kumar
on Mon, Dec 21 2015 3:20 PM

On December 11th we hosted a webinar titled “ JavaScript for C# Developers ” for the Indian region and

Add a Comment

Please Login or Register to add a comment.