0

Possible Duplicate:
Is there a better way to do optional function parameters in Javascript?
Default value for function parameter?

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.

3
  • dam, I searched for some time around stachoverflow and could not find that, Sorry Commented Aug 10, 2012 at 16:57
  • Obviously it is not possible, otherwise you wouldn't get a syntax error ;) Commented Aug 10, 2012 at 17:02
  • Trust me, we wish it were that simple, but it's not. Commented Aug 10, 2012 at 17:07

5 Answers 5

3
function somename(variableone){
    if(typeof variableone === "undefined")
        variableone = "content"
    return variableone;
}
Sign up to request clarification or add additional context in comments.

Comments

2
function somename(variableone) {
    variableone = arguments.length < 1 ? "content" : variableone;
    return variableone;
}

Comments

0

You'll need to use a condition:

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

Comments

0
function someName(somevar){

  somevar = somevar || "content";

  console.log(somevar);

}

someName();

This will set somevar to itself if it is not undefined, or (|| is or) "content".

Comments

0
function somename(variableone){
    return variableone = variableone ? variableone  : 'content'
}

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.