Jump to content
Sign in to follow this  
tobeyt23

Declare a variable

Recommended Posts

Can you set a variable like so:

 

Function something(bob = true) {

 

}

Share this post


Link to post
Share on other sites

Yes that is possible. its called a default value. The only rule is that parameters with default values come after parameters without.

 

 

//wrong

function something($a = 'cool', $b)

{

}

 

//right

function something($a, $b = 'cool')

{

}

 
Edited by Frank_b

Share this post


Link to post
Share on other sites

Considering this topic is in the Javascript forum, the correct answer is no, you cannot. Javascript has no concept of default values for function parameters. What you have to do is check whether the parameter was defined and if not, set the default.

 

function someFunction(bob){
   if (bob === undefined){ bob = true; }

   //...
}

Share this post


Link to post
Share on other sites

You can also do:

function someFunction(bob){
  bob = bob || true;

   //...
}

Share this post


Link to post
Share on other sites

That depends of course on what kind of value you expect for bob. If you expect a boolean value it wont work properly since false || true = true. A strict test against undefined is best for simple types. For objects using || is convenient.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.