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;};
......
...... 
}
user1871528
  • 1,655
  • 3
  • 27
  • 41

2 Answers2

2

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

function foo( x, y, opt ){
    if( typeof opt === 'undefined' ){ 
        opt = 1;
    }
    ...
}
JJJ
  • 32,902
  • 20
  • 89
  • 102
1

In javascript you can add default values like this:

function foo(x,y,opt){
 if(typeof(opt)==='undefined') opt = 1;
 //your code
}
Linga
  • 10,379
  • 10
  • 52
  • 104