2

Is it possible to set default parameter values for functions in JavaScript like with PHP?

function phpFunc($param='defvalue'){
    echo $param;
}

phpFunc();

Would result in 'defvalue' being outputted...

Is this possible in javascript?

Thanks.

2 Answers 2

6

No, it's not possible. You would have to do something like this :

function jsFunc(param) {
  param = typeof param == 'undefined' ? 'defvalue' : param;
  return param;
}

alert( jsFunc() );               // shows defvalue
alert( jsFunc('Hello, world!');  // shows Hello, world!

Hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

excellent! i was thinking about using a lack of passed param as a default value. thank you kindly!
1

Or just:

function jsFunc(param){
     param = param || defValue;
     return param;
 }

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.