Chapter 3. Functions
Functions are an important topic in JavaScript because the language has many uses for them. In their most basic form, they look like a PHP function:
// Works in both languagesfunctionsum($a,$b){return$a+$b;}sum(3,5);// 8
Default Parameters
There’s no syntax that allows you to have a default value of a function parameter, as is often done in PHP. This is scheduled for a future version of ECMAScript, but for now you have to take care of this yourself inside the body of your function. Let’s say you want the second parameter to default to 2:
// PHPfunctionsum($a,$b=2){return$a+$b;}
// JavaScriptfunctionsum(a,b){b=b||2;// Also sometimes written as// b || (b = 2)returna+b;}
This is a short syntax that works fine in many cases, but it’s a little naive in this particular example because b || 2 is a loose comparison for b. If you pass 0 as an argument, the comparison evaluates to false and b becomes 2:
sum(3);// 5sum(3,0);// 5, not what you'd expect
A longer version is to use typeof:
functionsum(a,b){b=typeofb==="undefined"?2:b;returna+b;}sum(3,0);// 3sum(3);// 5
Any Number of Arguments
You don’t have to pass all the arguments that a function expects, and JavaScript won’t complain. In other words, there are no required parameters. If you need to make a parameter required, you need to enforce this in the body of your function.
You can also pass more arguments than a function expects, and these are happily ignored without ...