Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

This is so simple I forgot how to do it. I've always passed variables to a function hence it's param's were pre-set, now I need to set the param's when declaring the function, but don't remember the setup.

I'm looking for the working version of this:

function(a,b=4){return a-b;}

Where the b param' of the function is set when the function is declared.

If I remember rightly it's like setting a default for b if the function has no second argument:

function(a,b){b=b || 4; return a-b;}

EDIT

Thanks for all your help but it seems it's impossible in js without ECMAScript 6. Your answers are getting a bit off topic though... I really needed the values set in the paren's.

To keep it on topic... my initial problem is sending parameters to a setTimeout function. Ok so I have a <div> with a .gif background, when clicked it's background changes, this second animation runs for exactly 8 seconds and then the background changes again to a final .gif. so it's a 3 stage animation, simple... thing is the 8sec gap, I figured a setTimeout would work but I can't pass any param's to the 'sto' function to reference said <div>.

If you know of any timer events that can help then be my guest, this is as far as I've got. My original code is below... it fails at function(p = cha).

for(var i = 0; i < 5; i++){
    var cha = document.createElement('div');
    $(cha).css('background','url(img/stand.gif)');
    cha.addEventListener('click',function(){
        $(cha).css('background','url(img/walk.gif)');
        setTimeout(function(p = cha){
            $(p).css('background','url(img/walk.gif)');
        },8000);
    });
}
share|improve this question
5  
This is very new in javascript. You probably remember doing it in PHP. – Denys Séguret Jun 19 at 12:47
    
@DenysSéguret: cheers!? probably was... I'lll check... – LostInCyberSpace Jun 19 at 12:48
    
@DenysSéguret: fifrefox support only in js, must have been php, cheers for the heads up. – LostInCyberSpace Jun 19 at 12:53
    
nice didnt know they added this. might be some browsers dont support it yet. use if (typeof b === 'undefined') for now – Sarfaraaz Jun 19 at 12:54
1  
It's not in the least impossible in JS without ECMAScript 6. Babel transpiles the default argument value syntax to ES5 every day. – torazaburo Jun 21 at 15:42

1 Answer 1

function(a,b){b=b || 4; return a-b;}

This is the typical way to default params in ES5. However I would advise changing this to check b's typs a little more strictly, because 0 will be considered a falsey value by the || operator

function(a,b){
  b = typeof b === 'undefined' ? 4 : b;
  return a-b;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.