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!

    1
    • excellent! i was thinking about using a lack of passed param as a default value. thank you kindly!CommentedAug 31, 2011 at 8:56
    1

    Or just:

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

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.