Wednesday, 21 September 2016

how to add a default value to a javascript function variable?











I can I do this on javascript (jQuery) function




function somename(variableone = "content"){
return variableone;
}


Now to access that function:



alert(somename()) //this should alert "content"
alert(somename("hello world"); //this should return "hello world"



but I get this error Uncaught SyntaxError: Unexpected token =



If this is not possible, is there a way to achieve the same result? OR most importantly is this a good (correct) practice.


Answer



function somename(variableone){
if(typeof variableone === "undefined")
variableone = "content"
return variableone;

}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...