简体   繁体   中英

Why does /* */ comment behave differently ? Javascript bug?

This is really weird. Why is fx2 returning 'undefined' while fx1, fx2 and fx3 correctly return 'true' ?

<script>

  function fx1(item) {
    return (item.a == 1)
        && (item.b == 1);
  }

  function fx2(item) {
    return /*(item.a == 1)
        && */(item.b == 1);
  }

  function fx3(item) {
    return true//(item.a= 1)
        && (item.b == 1);
  }

  function fx4(item) {
    return (item.b == 1);
  }

  alert(fx1({a: 1, b: 1}));
  alert(fx2({a: 1, b: 1}));
  alert(fx3({a: 1, b: 1}));
  alert(fx4({a: 1, b: 1}));

</script>

Try it online on http://www.codetuning.net/temp/commentedwherejsbug.html

This of course is a simplified version of my original code to just reproduce this single issue. Initially I had fx1, then I thought the fist condition (testing item.a) may not be needed and I commented it out as in fx2. Why is this not working ?? fx3 and fx4 work as expected, they all return true, except for fx2 which returns undefined.

Tested on IE11 and Chrome 47.

Can someone convince me this is not a bug in Javascript ?

function fx2(item) {
    return /*(item.a == 1)
        && */(item.b == 1);
  }

javascript will automatically put a ; after return . put all your return statements on the same line. like

 return (item.a == 1) && (item.b == 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM