Setting Javascript Function Parameters inside the function parenthesis

105 views Asked by At

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);
    });
}
1

There are 1 answers

0
PhilVarg On
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;
}