Jump to content


Photo

Setting argument defaults for a function?


  • Please log in to reply
2 replies to this topic

#1 Kris

Kris
  • Staff Alumni
  • Advanced Member
  • 2,755 posts
  • LocationThe Internet

Posted 22 October 2006 - 10:29 AM

When creating a function in PHP, you can set default values for arguments within a function like so:
my_function($name="unknown",$age) {
    echo "Hello, my name is $name, I am $age";
}

I am trying to do the same for a function in JavaScript, but don't appear to be having much luck - Google isn't being very helpful either...

Thanks guys

#2 fenway

fenway
  • Staff Alumni
  • MySQL Si-Fu / PHP Resident Alien
  • 16,199 posts
  • LocationToronto, ON

Posted 22 October 2006 - 09:25 PM

Such an option doesn't exist... in fact, I've never seen anything like this.  Generally, it's preferable to simply default the values at the top of the subroutine; so for JS:

function my_function( name, age ) {
   if( name == null ) name = "unknown";
   alert( 'Hello, my name is ' + name + ', I am ' + age );
}

Seriously... if people don't start reading this before posting, I'm going to consider not answering at all.

#3 Kris

Kris
  • Staff Alumni
  • Advanced Member
  • 2,755 posts
  • LocationThe Internet

Posted 22 October 2006 - 11:29 PM

*Slaps forehead*

I was overlooking the obvious there! Many thanks Fenway :)




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users