handling on no argument in javascript functions
internet-explorer-8, javascript, jquery-1.7
Solution
JavaScript functions allow you to call them with less parameters than specified.
What you're trying to accomplish is possible doing something like the following:
function foo(a , b){
if(typeof b === "undefined"){
b=3;
}
return a + b;
}
foo(5);//return 3;
I strongly suggest that you check for `undefined` and not rely on the `||` operator. I've spent hours debugging code that made that assumption and failed when passing `0` or another falsy value. The JavaScript type system can get really tricky, for example `"0"` is falsy.
ECMAScript Harmony (the next version) allows default parameters like in those other languages using the following syntax
function foo(a , b=3){
return a + b;
}
This does not work in IE8 like the first version though.
Problem
I have little experience in javascript but in other programming languages the following is possible, to set a default value for a missing parameter in a function. For instance lets say i have a function ``` function foo(a , b) return a + b { ``` I would like to be able to call the above function with 1 parameter or with 2 parameters one parameter case: ``` foo(2) //a =2 and b would be automatically set to a default no argument value, ``` two parameter case: ``` foo(1,2) // a = 1 , b = 2 => 3 ``` Is this possible in javascript that is IE 8 compatible or using Jquery 1.7.2?