[JavaScript] Functions

In JavaScript, a function is a really unique feature. In general, you can use it as a global module. Define it and use it anywhere you want. But JavaScript functions are much more than that. Let’s find out what they are.

1. Features of a Function

JavaScript function is a group of statements that can be run as a single unit. It has the following features

  • can have parameters
  • returns a value
  • each invocation has a context value – can be access by “this

A function can be assigned to the property of an object, it is called a method. The invocation context of a method is an object. Therefore, the “this” keyword inside a method refers to the object itself.

Functions can also be designed to create objects. They are called constructors.

 

2. Functions as Objects

In JavaScript, a function is also an object. You can freely assign functions to variables or properties in objects. Interestingly, you can even add properties or methods to functions (rarely used though).

var calculator = {
  x: 0,
  y: 0,
  add: function () { return this.x + this.y; }
};
calculator.x = 10;
calculator.y = 20;
alert(calculator.add());

 

3. Declaring Functions

Functions are defined by using the keyword “function” followed by name, parameters, and statements. When functions are declared as part of an expression, the name of the function is usually omitted.

$(document).ready(function () {
  var nums = [1, 2, 3, 4, 5];
  alert(nums.reduce(function(r, v) { return r+v; }, 0)); // 15
});

 

4. Invoking Functions

There are a couple of ways to invoke or call functions:

  • as a function
  • as a method
  • as a constructor
  • indirectly using the “call()” or “apply()” methods

 

5. Constructor Invocation

When you call a function with the “new” keyword, a new object is created. Constructors are used to initialize the properties of objects.

var now = new Date();
alert(now.toString());

The following example shows how a constructor is used to create a custom object.

function Calculator(x, y) {
  this.op1 = x;
  this.op2 = y;
}
Calculator.prototype.add = function () {
  return this.op1 + this.op2;
}

$(document).ready(function () {
  var calculator = new Calculator(10, 20);
  alert(calculator.add());
});

 

6. Indirect Invocation

Indirect invocation is used when you want to call a function as if it is a method of an object. You know each function has its own invocation context and can be accessed by “this“. What if you want to call a function with the specific object context? That is what indirect invocation is for.

Function.prototype” defines the “call()” and “apply()” methods.

  • apply(thisArg, argsArray)
  • call(thisArg, arg1, arg2, …)

Two methods do the same task. The difference is how to pass arguments to a function. You need to use an array to the “apply()” method.

function calculateTax(rate, deduction) {
  var tax = (this.amount - deduction) * rate;
  return tax > 0 ? tax : 0.0;
}

When you call the “calculateTax()” function directly, you will get an error because the invocation context does not have an amount property.

function calculateTax(rate, deduction) {
  var tax = (this.amount - deduction) * rate/100;
  return tax > 0 ? tax : 0.0;
}
function Product(price) {
  this.amount = price;
}

$(document).ready(function () {
  var food = new Product(10);
  var truck = new Product(40000);
  alert(calculateTax.apply(food, [10, 100])); // 0
  alert(calculateTax.call(truck, 10, 10000)); // 3000
});

You can think of indirect invocation as a temporary method.

var truck = new Product(40000);
truck.calTax = calculateTax; // temporary method
alert(truck.calTax(10, 10000)); // 3000
delete truck.calTax; // remove it

 

7. Optional Parameters

You can invoke functions with fewer arguments than declared parameters. The important part is how to check whether the argument is passed or not.

When the arguments are not passed, matching parameters are set to “undefined“.

function add(x, y) {
  if (y === undefined) {
    y = 0;
  }
  if (x === undefined) {
    x = 0;
  }
  return x + y;
}
alert(add(10,20)); // 30
alert(add(10)); // 10
alert(add()); // 0

 

8. Variable Length Arguments and Variadic Functions

You can even pass more arguments than the number of parameters. And then how can we access the arguments? Actually, all arguments can be accessed through the “arguments” array-like object (It is not an array, which can be a language design mistake).

By using this “arguments” variable, you can create a function that can accept any number of arguments. This kind of function is called a variadic function.

function add() {
  var result = 0;
  for (var i = 0; i < arguments.length; i++) {
    result += arguments[i];
  }
  return result;
}
alert(add(1,2,3,4,5,6,7,8,9,10)); // 55

 

9. Return Values

In JavaScript, functions always return values. There is no “void” type. If you do not return a value in a function, the return value is “undefined“.

function dummy() {
};

var result = dummy();
alert( typeof result ); // "undefined"

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s