0

so I want to write a function that takes 3 parameters, 3rd one being optional. I want something to check that if optional does not exist then give it a default value. IS there a IF Not way of doing it? if not then whats the best way of doing it?

This is what i want

foo.(x,y, opt){
if (!opt){opt = 1;}
......
...... 
}

This is what I have:

foo.(x,y, opt){
if (opt){}
else {opt = 1;};
......
...... 
}
1
  • 2
    Your two versions are equivalent I think. Commented Apr 6, 2013 at 5:34

2 Answers 2

2

If the parameter is not passed to the function, it's undefined.

function foo( x, y, opt ){
    if( typeof opt === 'undefined' ){ 
        opt = 1;
    }
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

In javascript you can add default values like this:

function foo(x,y,opt){
 if(typeof(opt)==='undefined') opt = 1;
 //your code
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.