Weird JavaScript Functions

In every programming language, functions are the main blocks of executing repetitive tasks. Functions are also helpful in dividing a big task into small ones. JavaScript already has a rich set of constructs for defining functions. Let us see how functions look like in JavaScript.

// simple_function.js
function myFunction(arg1, arg2, arg3){
  return arg1 + arg2 + arg3;
}

console.log(myFunction(1,2,3));
console.log(myFunction("Naren","Saikiran","Venky"));
$ node simple_function.js
6
NarenSaikiranVenky

If we see the function definition, it is plain simple. No return type and no signature for arguments. This creates ambiguity when we passs different values to the myFunction. Type Script address this issue by enforcing type signature for a function. There is one more situation where JavaScript functions acts weird way.

function multiplyFunction(){
 var args = Array.prototype.slice.call(arguments);
 args.reduce(function(previousValue, currentValue, currentIndex, array) {
  return previousValue * currentValue;
});
}

console.log(myFunction1(1,2,3,undefined));

This function is an optional argument example where any number of arguments can be passed. If no type check was there, the above function returns NaN for an undefined argument. In order to overcome that we should check each and every argument and then apply reduce on that. But using Type Script type check we can catch these errors at compile time. In the next section we will go into the syntax of Type Script functions and it's variations.