Javascript is different, you don't need to define everything, but you can, and if you do, the syntax is also different. And the word var is reserved, so you cannot use it as a variable name. There are several ways to handle it. The simplest is:
Code:
function example(myvar) {
myvar = myvar || 1;
return myvar;
}
If myvar is undefined, you will get 1. But you will also get 1 if myvar is 0. So if it's a number you're after and 1 is what you want if it's not a number:
Code:
function example(myvar) {
myvar = typeof myvar !== 'number'? 1 : myvar;
return myvar;
}
It's really kind of messy though, to equal PHP, you would do:
Code:
function example(myvar) {
myvar = typeof myvar === 'undefined'? 1 : myvar;
return myvar;
}
That way you will get whatever myvar is as long as it's not undefined.
But you almost never see that. Usually it's just assumed that myvar will be whatever's expected, and that if it isn't, the script will break and the author must trace back to where that happened and fix it. Alternatively you can test myvar in various ways, for what it's most likely to be, and as a result of that determine what to do next, that's also pretty common:
Code:
function example(myvar) {
if (typeof myvar === 'number') {do something;}
else if (typeof myvar === 'string') {do something else;}
else {do yet another thing;}
}
Bookmarks