SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Addict
    Join Date
    Oct 2004
    Location
    NYC
    Posts
    306
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Using Ternary operators instead of if statement, is it possible?

    Hello,

    I would appreciate all the help. I would like to write a function which would take couple of parms such name and address. Can I use ternary operators instead of IF STATEMENT to validate the function arguments:

    PHP Code:
    function(name)
    {
      if(!
    name)
      {
      
    document.write("Name: <br>");
      }
      else
      {
      
    document.write("Name: " name "<br>");
      }


    So pretty much I would like to write:

    var name = (name == ' ') ? 'name' : ' ';

    I am not sure if this is the write syntax. Appreciate all the help.

    Thanks a lot.

  2. #2
    Non-Member
    Join Date
    Aug 2006
    Location
    Kansas City
    Posts
    98
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yeah, you have it right....

    var test = 110

    var isItRight = (test == 110) ? alert(You are right!) : alert(you are wrong!);

    or....

    function TestMe(number)
    {

    var isItRight = (number == 110) ? alert(You are right!) : alert(you are wrong!);

    Hope it helps;

  3. #3
    SitePoint Addict
    Join Date
    Oct 2004
    Location
    NYC
    Posts
    306
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks a bunch KCChiefs...

  4. #4
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The ternary will return the first or the second value. So you can write your logic like this:
    Code:
      document.write("Name: " + (name ? name : '') + "<br>");


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
  •