How to Use Function Arguments Wisely in JavaScript

In JavaScript function arguments are untyped and are not mandatory to be provided when we call the function.

function sum(a, b, c) {
  return a + b + c;
}

So we can call function sum like these:

console.log(sum(10));
console.log(sum(20, 10));
console.log(sum(20, 10, 30));
console.log(sum(20, 10, 30, 5));

Surprisingly all of these are valid and never lead in a runtime error!
And on the 4th call, 5 will be ignored by our code.

Those arguments who which are not provided will be assigned by 'undefined'. So we can check any argument in the body of the function to see if it is provided or not like this:

function sum2(a, b, c) {
  if (a != undefined && b != undefined && c != undefined) {
    return a + b + c;
  } else {
    return 0;
  }
}

In the function of sum2 we expect the user to provide all 3 arguments, otherwise we return 0.
There is a special object called arguments available to all JavaScript functions which is working like an array containing all passed arguments.

So we can rewrite our function like this in order to work with any number of arguments:

function sum() {
  var result = 0;

  for (var i = 0; i < arguments.length; ++i) {
    result += arguments[i];
  }

  return result;
}

No comments:

Post a Comment