/    Sign up×
Community /Pin to ProfileBookmark

Setting a default value for a function variable

Here’s the function:

[code=php]function GetEl(ele, fltr){
var el, type = ele.substr(0,3), name = ele.substr(6), num = ele.substr(4,1);
if(type==’_el’){
var elal = document.getElementsByTagName(name);
if(num != ‘l’){
el = elal[num];
} else if(fltr){
var slot = lp = 0, el = new Array();
while(lp < elal.length){
if(elal[lp].className.match(fltr)){
el[slot] = elal[lp];
slot++;
}
lp++;
}
} else {
el = elal;
}
} else {
el = document.getElementById(ele);
}
return el;
}[/code]

How do I set [i]fltr[/i] to [b]false[/b] by default?

to post a comment
JavaScript

6 Comments(s)

Copy linkTweet thisAlerts:
@FangJun 01.2008 — var fltr = fltr || false;
Copy linkTweet thisAlerts:
@Mr_Initial_ManauthorJun 01.2008 — where would I put that?
Copy linkTweet thisAlerts:
@mrhooJun 01.2008 — It is already [I]undefined [/I]by default, and will return the same boolean [I]as false [/I]would in the [COLOR=#000000][B][COLOR=#007700]else if([/COLOR][COLOR=#0000bb]fltr[/COLOR][/B][COLOR=#007700][B]){[/B] test.

[/COLOR]
[/COLOR]
Copy linkTweet thisAlerts:
@Mr_Initial_ManauthorJun 02.2008 — In other words, I don't need to set it to false?
Copy linkTweet thisAlerts:
@FangJun 02.2008 — In this simple example you shouldn't have a problem with [I]if[/I] statement.

JavaScript uses type coercion, i.e.[I] undefined -> false[/I], so a [I]typeof[/I] check could be required for more rigorous checking.
Copy linkTweet thisAlerts:
@Declan1991Jun 02.2008 — And if you put that type of code first thing in the function,[code=php]function a(par1){
par1 = par1||false;
}[/code]

par1 will always be defined. I use it in a getElementsByClassName all the time:[code=php]function getElementsByClassName(class,tag){
document.getElementsByTagName(tag||"*");
}[/code]
×

Success!

Help @Mr_Initial_Man spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...