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.

Community
  • 1
  • 1
aurel
  • 3,082
  • 10
  • 44
  • 56

5 Answers5

3
function somename(variableone){
    if(typeof variableone === "undefined")
        variableone = "content"
    return variableone;
}
Oswaldo Acauan
  • 2,730
  • 15
  • 23
2
function somename(variableone) {
    variableone = arguments.length < 1 ? "content" : variableone;
    return variableone;
}
Esailija
  • 138,174
  • 23
  • 272
  • 326
0

You'll need to use a condition:

function somename(variableone){
    if (typeof(variableone) === "undefined") {
        variableone = "content";
    }
    return variableone;
}
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
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".

MoDFoX
  • 2,134
  • 2
  • 21
  • 22
0
function somename(variableone){
    return variableone = variableone ? variableone  : 'content'
}