SitePoint Sponsor

User Tag List

Results 1 to 5 of 5

Hybrid View

  1. #1
    SitePoint Guru D-flyer's Avatar
    Join Date
    Jan 2001
    Location
    Near a computer
    Posts
    782
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How to set a default value for a function

    Can't get this to work

    Code:
    function test(name = 'Boss'){
    alert("Name is:"+name);
    }
    
    function test(name ){
    if(name == ''){name='Boss'}
    alert("Name is:"+name);
    }
    How can I set a default value???

  2. #2
    SitePoint Guru D-flyer's Avatar
    Join Date
    Jan 2001
    Location
    Near a computer
    Posts
    782
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    nevermind this seems to work
    Code:
    function test(name) {
    if( name == undefined ) 
        name = 'Boss';
    alert("Name is:"+name);
    }

  3. #3
    SitePoint Wizard siteguru's Avatar
    Join Date
    Oct 2002
    Location
    Scotland
    Posts
    3,609
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    I don't think JS accepts default values within the function() declaration. (Unlike PHP, where you can do what you first posted).
    Ian Anderson
    www.siteguru.co.uk

  4. #4
    SitePoint Guru D-flyer's Avatar
    Join Date
    Jan 2001
    Location
    Near a computer
    Posts
    782
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    @siteguru, tx for your answer.

    I indeed thought I could do it the 'php' way.

  5. #5
    SitePoint Wizard Pepejeria's Avatar
    Join Date
    Jan 2005
    Location
    Too far up north
    Posts
    1,566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No need for an if statement
    Code:
    function test(name) {
        name = name || 'Boss';
    
        alert("Name is: " + name);
    }
    Name will default to "Boss" if not provided.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •