How optimized ar eif-statements in JS

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • K Viltersten

    How optimized ar eif-statements in JS

    In the code at our company i see the following.

    if (someStuff != null) {
    if (someStuff != "") {
    doThatThing ();
    }
    }

    While it's fully correct and valid, i'd like to rewrite it
    as follows.

    if (someStuff != null && someStuff != "")
    doThatThing ();

    I know that some languages will evaluate the first condition
    of the conjunction and, provided that it fails, conclude
    that the statement is not to be performed. I'd like to
    assume so in this case as well, but wishing not to show
    arrogance and know-better-ism, i'd like to check with more
    experienced programmers first.

    Will JS evaluate the whole konjunction or will it be
    intelligent enough to stop as the first partial condition
    fails? Is it depending on the platform used?

    --
    Regards
    Konrad Viltersten
  • =?ISO-8859-15?Q?=22=C1lvaro_G=2E_Vicario=22?=

    #2
    Re: How optimized ar eif-statements in JS

    K Viltersten escribió:
    if (someStuff != null && someStuff != "")
    [...]
    Will JS evaluate the whole konjunction or will it be
    intelligent enough to stop as the first partial condition
    fails? Is it depending on the platform used?
    It'll stop as soon as it has a definitive result:



    See the "Short-Circuit Evaluation" header.



    --
    -- http://alvaro.es - Álvaro G. Vicario - Burgos, Spain
    -- Mi sitio sobre programación web: http://bits.demogracia.com
    -- Mi web de humor al baño María: http://www.demogracia.com
    --

    Comment

    • Henry

      #3
      Re: How optimized ar eif-statements in JS

      On May 22, 9:46 am, K Viltersten wrote:
      In the code at our company i see the following.
      >
      if (someStuff != null) {
      if (someStuff != "") {
      doThatThing ();
      }
      >
      }
      >
      While it's fully correct and valid, i'd like to rewrite it
      as follows.
      >
      if (someStuff != null && someStuff != "")
      doThatThing ();
      It is very widely considered good style when writing javascript to
      never omit the braces of a block statement from around the code
      executed in - if/else - branches. It is extremely common to have a
      single statement conditionally executed and then to realise that a
      second statement will need to be added to that branch. With the braces
      already in place all you do is add the statement, but without the
      braces you often get fooled by the indentation into adding the
      statement at the existing level of indentation and not seeing that
      only one statement is going to conditionally executed and any that
      follow it will be unconditionally executed. The usual result is a
      confusing and hard to track down bug.
      I know that some languages will evaluate the first
      condition of the conjunction and, provided that it
      fails, conclude that the statement is not to be
      performed. I'd like to assume so in this case as
      well, but wishing not to show arrogance and
      know-better-ism, i'd like to check with more
      experienced programmers first.
      >
      Will JS evaluate the whole konjunction or will it
      be intelligent enough to stop as the first partial
      condition fails? Is it depending on the platform
      used?
      The language specification requires short circuiting, and no
      implementations have been observed to fail to correctly implement the
      specification in this regard.

      However, your simplification looks like it probably still falls short
      of an optimum outcome. The first test, - someStuff != null -, will be
      false for null and undefined values, so those two values are excluded
      by the first test. The second test, - someStuff != "" -, will be false
      for boolean false, numeric zero and empty strings. So the values that
      can pass the combined test are all[*1] objects (including functions),
      non-zero numbers (including NaN), non-empty strings, and boolean true.

      [*1] Actually not all objects will pass the - someStuff != "" - test
      because the comparison with a string implies type-conversion so an
      object with a - toString - method that returned the empty string would
      be equal to the empty string primitive. That is -
      alert({toString :function(){ret urn '';}} == ''); - alerts "true".

      An alternative test could be:-

      if(someStuff){
      doThatThing ();
      }

      - where the value of - someStruff - is implicitly type-converted to
      boolean and since the empty string, boolean false, numeric zero and
      NaN, the undefined value and null all type-convert to boolean false
      the only practical differences between that test and your previous one
      is that the NaN numeric value will not pass the test (which is
      probably a good idea) and that all objects would pass regardless of
      how they type-convert to primitive values. While the type-converting
      to boolean test is shorter simpler and faster than the original (which
      includes at least one implicit type-conversion to boolean anyway).

      Comment

      • K Viltersten

        #4
        Re: How optimized ar eif-statements in JS

        >In the code at our company i see the following.
        >>
        >if (someStuff != null) {
        > if (someStuff != "") {
        > doThatThing ();
        > }
        >}
        >>
        >While it's fully correct and valid, i'd like to rewrite it
        >as follows.
        >>
        >if (someStuff != null && someStuff != "")
        > doThatThing ();
        >
        It is very widely considered good style when writing javascript to
        never omit the braces of a block statement from around the code
        executed in - if/else - branches. It is extremely common to have a
        single statement conditionally executed and then to realise that a
        second statement will need to be added to that branch. With the braces
        already in place all you do is add the statement, but without the
        braces you often get fooled by the indentation into adding the
        statement at the existing level of indentation and not seeing that
        only one statement is going to conditionally executed and any that
        follow it will be unconditionally executed. The usual result is a
        confusing and hard to track down bug.
        I forgot to add the braces, otherwise i'm always putting
        them in by copmany requirement. The extra pointers and
        suggestions are ALWAYS appreciated, of course. Thanks!

        With risk of getting into something very nasty - the
        argument about braces "already there when one needs them"
        doesn't hold, in my opinion.

        1. At some point of time one needs to put them in so
        if it happens frequently that one'll need to put more
        things there, it's not MORE work to do so. At best,
        not much less (or much less, when lucky).

        2. Unless one isn't a hard-core-never-seen-anything-else
        Python programmer, one shouldn't confuse indentation and
        scoping. At least i've never had that problem but perhaps
        i'm a genius, i can admit. :)

        Please enlighten me if i'm missing anything and please
        keep in mind that the above are only my personal views,
        hence subject to change, if needed.
        >Will JS evaluate the whole konjunction or will it
        >be intelligent enough to stop as the first partial
        >condition fails? Is it depending on the platform
        >used?
        >
        The language specification requires short circuiting, andno
        implementations have been observed to fail to correctlyimplem ent the
        specification in this regard.
        >
        However, your simplification looks like it probably stillfalls short of
        an optimum outcome.
        <snippage>
        An alternative test could be:
        >
        if (someStuff) { doThatThing (); }
        To be perfectly sure i got it right - i can skip the test
        in the original post and simply test "is someStuff the
        case"?! That would be awsomely simplifying! In fact, that
        could just make me appreciate JavaScript, hehe. :)

        --
        Regards
        Konrad Viltersten

        Comment

        • rf

          #5
          Re: How optimized ar eif-statements in JS

          Henry <rcornford@rain drop.co.ukwrote in news:18129482-c1c5-4d41-888e-
          888d1ebe1a37@d7 7g2000hsb.googl egroups.com:
          >if (someStuff != null && someStuff != "")
          > doThatThing ();
          It is very widely considered good style when writing javascript to
          never omit the braces of a block statement from around the code
          executed in - if/else - branches.
          Bullshit.

          --
          Richard
          Killing all google groups posts
          The Usenet Improvement Project: http://improve-usenet.org

          Comment

          • Henry

            #6
            Re: How optimized ar eif-statements in JS

            On May 22, 1:47 pm, rf wrote:
            Henry wrote in news:18 ... @d77g2000hsb.go oglegroups.com:
            ^^^^^^^^^^^^ ^^^
            >
            >>if (someStuff != null && someStuff != "")
            >> doThatThing ();
            >It is very widely considered good style when writing
            >javascript to never omit the braces of a block statement
            >from around the code executed in - if/else - branches.
            >
            Bullshit.
            <snip>
            Killing all google groups posts
            ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^

            Hypocrisy.

            Comment

            • Gregor Kofler

              #7
              Re: How optimized ar eif-statements in JS

              rf meinte:
              Henry
              >It is very widely considered good style when writing javascript to
              >never omit the braces of a block statement from around the code
              >executed in - if/else - branches.
              >
              Bullshit.
              Since I always do it the way recommeneded by Richard, I'm sure you can
              elaborate on that.

              Gregor


              --
              http://photo.gregorkofler.at ::: Landschafts- und Reisefotografie
              http://web.gregorkofler.com ::: meine JS-Spielwiese
              http://www.image2d.com ::: Bildagentur für den alpinen Raum

              Comment

              • Henry

                #8
                Re: How optimized ar eif-statements in JS

                On May 22, 1:35 pm, K Viltersten wrote:
                >>In the code at our company i see the following.
                >
                >>if (someStuff != null) {
                >> if (someStuff != "") {
                >> doThatThing ();
                >> }
                >>}
                >
                >>While it's fully correct and valid, i'd like to rewrite it
                >>as follows.
                >
                >>if (someStuff != null && someStuff != "")
                >> doThatThing ();
                >
                >It is very widely considered good style when writing
                >javascript to never omit the braces of a block statement
                >from around the code executed in - if/else - branches.
                >It is extremely common to have a single statement
                >conditionall y executed and then to realise that a second
                >statement will need to be added to that branch. With the
                >braces already in place all you do is add the statement,
                >but without the braces you often get fooled by the
                >indentation into adding the statement at the existing
                >level of indentation and not seeing that only one statement
                >is going to conditionally executed and any that follow it
                >will be unconditionally executed. The usual result is a
                >confusing and hard to track down bug.
                >
                I forgot to add the braces, otherwise i'm always putting
                them in by copmany requirement. The extra pointers and
                suggestions are ALWAYS appreciated, of course. Thanks!
                >
                With risk of getting into something very nasty - the
                argument about braces "already there when one needs them"
                doesn't hold, in my opinion.
                >
                1. At some point of time one needs to put them in so
                if it happens frequently that one'll need to put more
                things there, it's not MORE work to do so. At best,
                not much less (or much less, when lucky).
                The amount of work isn't really the point. It is about avoiding
                introducing bugs. There is a very high correlation between the use of
                braces in javascript source code and (sensible) indentation, such that
                it becomes very easy to see indentation and mentally imply the braces.
                Most of the time that would not be a problem because there braces
                would actually be there, and so that re-enforces the subconscious
                assumption that they will be there. And so on the relatively rare
                occasions were there is indentation without braces it becomes very
                easy to make the addition to the indented code and never observe that
                there were no braces around it.
                2. Unless one isn't a hard-core-never-seen-anything-else
                Python programmer, one shouldn't confuse indentation and
                scoping.
                Javascript is not block scoped so indentation and scoping are not that
                related most of time.
                At least i've never had that problem but perhaps
                i'm a genius, i can admit. :)
                But didn't you say that you would normally include the braces by
                "company requirement"? That means you will not have much opportunity
                to make the mistakes that occur when they are missing.
                Please enlighten me if i'm missing anything and please
                keep in mind that the above are only my personal views,
                hence subject to change, if needed.
                If all else fails time will enlighten you.
                >>Will JS evaluate the whole konjunction or will it
                >>be intelligent enough to stop as the first partial
                >>condition fails? Is it depending on the platform
                >>used?
                >
                >The language specification requires short circuiting, andno
                >implementation s have been observed to fail to correctlyimplem ent
                >the specification in this regard.
                >
                >However, your simplification looks like it probably stillfalls
                >short of an optimum outcome.
                ><snippage>
                >An alternative test could be:
                >
                >if (someStuff) { doThatThing (); }
                >
                To be perfectly sure i got it right - i can skip the test
                in the original post and simply test "is someStuff the
                case"?!
                The test is more 'does someStuff's value have truness', but if that is
                the discrimination that fits the situation (and it certainly appears
                to be from the incomplete fragment posted) then the simpler test will
                do the job.
                That would be awsomely simplifying!
                Where does this go in the next decade? If simple things are already
                being ladled as awe inspiring what superlatives are going to be left
                for the things that are really worth pointing out?
                In fact, that
                could just make me appreciate JavaScript, hehe. :)

                Comment

                • rf

                  #9
                  Re: How optimized ar eif-statements in JS

                  Henry <rcornford@rain drop.co.ukwrote in news:fb90e2f3-c5c9-41bb-a794-
                  1350a54d7860@w7 g2000hsa.google groups.com:
                  On May 22, 1:47 pm, rf wrote:
                  >Henry wrote in news:18 ... @d77g2000hsb.go oglegroups.com:
                  ^^^^^^^^^^^^ ^^^
                  >>
                  >>>if (someStuff != null && someStuff != "")
                  >>> doThatThing ();
                  >>It is very widely considered good style when writing
                  >>javascript to never omit the braces of a block statement
                  >>from around the code executed in - if/else - branches.
                  >>
                  >Bullshit.
                  <snip>
                  >Killing all google groups posts
                  ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^
                  >
                  Hypocrisy.
                  >
                  I delve in now and again, just to see what the supid bloody buggers are up
                  to. This one I could not resist replying to as it has no foundation at all.

                  I also can't be arsed to change my sig just for the occasional foray.

                  --
                  Richard
                  Killing all google groups posts
                  The Usenet Improvement Project: http://improve-usenet.org

                  Comment

                  • Henry

                    #10
                    Re: How optimized ar eif-statements in JS

                    rf wrote:
                    Henry wrote:
                    >rf wrote:
                    >>Henry wrote:
                    <snip>
                    >>>It is very widely considered good style when writing
                    >>>javascript to never omit the braces of a block statement
                    >>>from around the code executed in - if/else - branches.
                    >
                    >>Bullshit.
                    <snip>
                    This one I could not resist replying to as it has no
                    foundation at all.
                    In "JavaScript :The Good Parts", Douglass Crockford writes:" An if or
                    while or do or for statement can take a block or a single statement.
                    The single statement form is another attractive nuisance. It offers
                    the advantage of saving two characters, a dubious advantage. It
                    obscures the program's structure so that subsequent manipulators of
                    the code can easily insert bugs." (and unsurprisingly JSLint will not
                    pass code that omits the braces).

                    My assertion that "It is very widely considered good style ..." is not
                    without foundation.

                    Comment

                    • K Viltersten

                      #11
                      Re: How optimized ar eif-statements in JS

                      >I forgot to add the braces, otherwise i'm always putting
                      >them in by copmany requirement. The extra pointers and
                      >suggestions are ALWAYS appreciated, of course. Thanks!
                      >>
                      >With risk of getting into something very nasty - the
                      >argument about braces "already there when one needs them"
                      >doesn't hold, in my opinion.
                      >>
                      >1. At some point of time one needs to put them in so
                      >if it happens frequently that one'll need to put more
                      >things there, it's not MORE work to do so. At best,
                      >not much less (or much less, when lucky).
                      >
                      The amount of work isn't really the point. It is about avoiding
                      introducing bugs. There is a very high correlation between the use of
                      braces in javascript source code and (sensible) indentation, such that
                      it becomes very easy to see indentation and mentally imply the braces.
                      Most of the time that would not be a problem because there braces
                      would actually be there, and so that re-enforces the subconscious
                      assumption that they will be there. And so on the relatively rare
                      occasions were there is indentation without braces it becomes very
                      easy to make the addition to the indented code and never observe that
                      there were no braces around it.
                      In my experience (not JS-related, of course but still from
                      programming), the bugs are not so commonly introduced due
                      to that. Also, i find it's not very rare at all to have
                      one line long statements. In fact, in my case, it seems to
                      be rather common. Please note, it's my personal opinion
                      only and i haven't proof/disproof either way. I'm not
                      claiming you're wrong. I'm saying that i don't recognize
                      the case from MY experience, hence being careful.
                      >2. Unless one isn't a hard-core-never-seen-anything-else
                      >Python programmer, one shouldn't confuse indentation and
                      >scoping.
                      >
                      Javascript is not block scoped so indentation and scopingare not that
                      related most of time.
                      The point was that by seeing an indentation made nicely, i
                      never had any errors introduced by forgetting the braces.
                      But didn't you say that you would normally include thebraces by "company
                      requirement"? That means you will nothave much opportunity to make the
                      mistakes that occur whenthey are missing.
                      I won't have problems with polar bears either. Neither is
                      due to the coding standard i'm following, however. I can't
                      remember a single occasion when i've forgot to add braces
                      when needed... My opinion is that it's an urban legend but,
                      let me remind, i might be mistaken.
                      >Please enlighten me if i'm missing anything and please
                      >keep in mind that the above are only my personal views,
                      >hence subject to change, if needed.
                      >
                      If all else fails time will enlighten you.
                      I see somebody else responded by reference to fornicates
                      of the cowly type. It wasn't me and since i'm sensing a
                      bit of irritation, i'm suggesting to drop the subject. :)
                      Where does this go in the next decade? If simple things are already
                      being ladled as awe inspiring what superlatives are going to be left
                      for the things that are really worth pointing out?
                      I've checked Wikipedia for "universal judge of what's
                      simple thing" but sadly they haven't updated the database
                      with your name yet, so let's just say that what's "simple
                      thing" to you, perhaps is a new concept to someone else.

                      I'm here to ask questions and learn. Not to get insulted!
                      I'm thankful for the advices and suggestions you (and
                      others) are offering but that doesn't entitle you to be
                      impolite or deminishing. I can be that too. I choose not
                      to and i'd appreciate if others could follow. Thank you.

                      --
                      Regards
                      Konrad Viltersten

                      Comment

                      • RoLo

                        #12
                        Re: How optimized ar eif-statements in JS

                        On May 22, 8:47 am, rf <r...@x.invalid wrote:
                        Henry <rcornf...@rain drop.co.ukwrote in news:18129482-c1c5-4d41-888e-
                        888d1ebe1...@d7 7g2000hsb.googl egroups.com:
                        >
                        if (someStuff != null && someStuff != "")
                           doThatThing ();
                        It is very widely considered good style when writing javascript to
                        never omit the braces of a block statement from around the code
                        executed in - if/else - branches.
                        >
                        Bullshit.
                        >
                        --
                        Richard
                        Killing all google groups posts
                        The Usenet Improvement Project:http://improve-usenet.org
                        lol... you read my mind!

                        Comment

                        • Thomas 'PointedEars' Lahn

                          #13
                          Re: How optimized ar eif-statements in JS

                          Henry wrote:
                          On May 22, 9:46 am, K Viltersten wrote:
                          >In the code at our company i see the following.
                          >>
                          >if (someStuff != null) {
                          > if (someStuff != "") {
                          > doThatThing ();
                          > }
                          >>
                          >}
                          >>
                          >While it's fully correct and valid, i'd like to rewrite it
                          >as follows.
                          >>
                          >if (someStuff != null && someStuff != "")
                          > doThatThing ();
                          >
                          It is very widely considered good style when writing javascript to
                          never omit the braces of a block statement from around the code
                          executed in - if/else - branches.
                          I think I know what you mean and I concur as for if-else; however, it
                          should be noted that there is no block statement if there are no braces.


                          PointedEars
                          --
                          Use any version of Microsoft Frontpage to create your site.
                          (This won't prevent people from viewing your source, but no one
                          will want to steal it.)
                          -- from <http://www.vortex-webdesign.com/help/hidesource.htm>

                          Comment

                          • Henry

                            #14
                            Re: How optimized ar eif-statements in JS

                            On May 22, 3:10 pm, K Viltersten wrote:
                            <snip>
                            >>With risk of getting into something very nasty - the
                            >>argument about braces "already there when one needs them"
                            >>doesn't hold, in my opinion.
                            >
                            >>1. At some point of time one needs to put them in so
                            >>if it happens frequently that one'll need to put more
                            >>things there, it's not MORE work to do so. At best,
                            >>not much less (or much less, when lucky).
                            >
                            >The amount of work isn't really the point. It is about
                            >avoiding introducing bugs. There is a very high correlation
                            >between the use of braces in javascript source code and
                            >(sensible) indentation, such that it becomes very easy
                            >to see indentation and mentally imply the braces. Most
                            >of the time that would not be a problem because there
                            >braces would actually be there, and so that re-enforces
                            >the subconscious assumption that they will be there. And
                            >so on the relatively rare occasions were there is
                            >indentation without braces it becomes very easy to make
                            >the addition to the indented code and never observe that
                            >there were no braces around it.
                            >
                            In my experience (not JS-related, of course but still from
                            programming), the bugs are not so commonly introduced due
                            to that.
                            <snip>

                            And in my JS related experience (and I did explicitly qualify the
                            recommendation with "when writing javascript") bugs of that type are
                            sufficiently commonly introduced that it is worth having a formal
                            practice that avoids them.

                            <snip>
                            >>Please enlighten me if i'm missing anything and please
                            >>keep in mind that the above are only my personal views,
                            >>hence subject to change, if needed.
                            >
                            >If all else fails time will enlighten you.
                            >
                            I see somebody else responded by reference to fornicates
                            of the cowly type.
                            But nothing tangible supporting that assertion.
                            It wasn't me and since i'm sensing a
                            bit of irritation, i'm suggesting to drop the subject. :)
                            >
                            >Where does this go in the next decade? If simple things
                            >are already being ladled as awe inspiring what superlatives
                            >are going to be left for the things that are really worth
                            >pointing out?
                            >
                            I've checked Wikipedia for "universal judge of what's
                            simple thing"
                            Why? There is no universal judgment involved, just a judgement of the
                            relative simplicity/complexity of aspects of a single programming
                            language.
                            but sadly they haven't updated the database
                            with your name yet, so let's just say that what's "simple
                            thing" to you, perhaps is a new concept to someone else.
                            A concepts being new does not preclude the possibility that it is also
                            simple.
                            I'm here to ask questions and learn. Not to get insulted!
                            What insult? I am just worried about your health; if you react to
                            javascript's type-conversion rules with awe you will have died of
                            shock before you stand a chance of understanding its closures.
                            I'm thankful for the advices and suggestions you (and
                            others) are offering but that doesn't entitle you to be
                            impolite or deminishing. I can be that too. I choose not
                            to and i'd appreciate if others could follow. Thank you.
                            There is no point in trying to dictate here.

                            Comment

                            • K Viltersten

                              #15
                              Re: How optimized ar eif-statements in JS

                              >In my experience (not JS-related, of course but still from
                              >programming) , the bugs are not so commonly introduced due
                              >to that.
                              <snip>
                              >
                              And in my JS related experience (and I did explicitly qualify the
                              recommendation with "when writing javascript") bugs of that type are
                              sufficiently commonly introduced that it is worth having a formal
                              practice that avoids them.
                              If you say so. My limited experience doesn't let me
                              discuss the subject. Not saying i agree, though. :)
                              >I see somebody else responded by reference to fornicates
                              >of the cowly type.
                              >
                              But nothing tangible supporting that assertion.
                              Yes, the post was rather short. Nevertheless, my point
                              was that i didn't say that so any ennoyance due to that,
                              need to be taken elsewhere. Otherwise we run the risk of
                              me starting to use that language as well and that's not
                              a flathering scenario.
                              >I've checked Wikipedia for "universal judge of what's
                              >simple thing"
                              >
                              Why? There is no universal judgment involved, just ajudgement of the
                              relative simplicity/complexity of aspectsof a single programming
                              language.
                              I don't agree. "It is simple" is universal. "According to me,
                              it is simple", would be more humble and appropriate, in my
                              opinion. After all, it was only an opinion, right?
                              >but sadly they haven't updated the database
                              >with your name yet, so let's just say that what's "simple
                              >thing" to you, perhaps is a new concept to someone else.
                              >
                              A concepts being new does not preclude the possibility thatit is also
                              simple.
                              It doesn't imply that either. In this case, it was new AND
                              difficult. To me, that is.
                              >I'm here to ask questions and learn. Not to get insulted!
                              >
                              What insult?
                              If i state X is difficult for me and you claim "no, it's
                              easy" (as opposed to "to me, it's easy") then you do
                              insult my capabilities. That's how i feel.
                              I am just worried about your health; if you react to
                              javascript's type-conversion rules with awe you will have died of
                              shock before you stand a chance of understanding its closures.
                              I seriously doubt that you care about my condition. Nor do
                              you believe in me going to die because of that, i think.
                              >I'm thankful for the advices and suggestions you (and
                              >others) are offering but that doesn't entitle you to be
                              >impolite or deminishing. I can be that too. I choose not
                              >to and i'd appreciate if others could follow. Thank you.
                              >
                              There is no point in trying to dictate here.
                              I expressed thankfulness and asked for something i'd
                              appreciate. That's hardly dictating, in my view but
                              if you took it that way, please accept my appology.

                              --
                              Regards
                              Konrad Viltersten

                              Comment

                              Working...