How optimized ar eif-statements in JS

K

K Viltersten

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?
 
H

Henry

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(){return '';}} == ''); - 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).
 
K

K Viltersten

In the code at our company i see the following.
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.
The language specification requires short circuiting, andno
implementations have been observed to fail to correctlyimplement 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. :)
 
R

rf

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.
 
H

Henry

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.
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?
 
R

rf

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

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.
 
H

Henry

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.
 
K

K Viltersten

I forgot to add the braces, otherwise i'm always putting
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.
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.
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.
 
T

Thomas 'PointedEars' Lahn

K said:
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.

I see no insult against you. Sorry, if you already consider maybe
sarcastic general comments insulting to you, you are not tough enough
to survive on Usenet. BTW, in order to do that, it would also be best
not to remove the attribution lines. Probably someone has recommended
that to you before.


PointedEars
 
T

Thomas 'PointedEars' Lahn

Henry said:
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
 
K

K Viltersten

Where does this go in the next decade? If simple things are already
I see no insult against you. Sorry, if you already consider maybe
sarcastic general comments insulting to you, you are not tough enough
to survive on Usenet. BTW, in order to do that, it would also be best
not to remove the attribution lines. Probably someone has recommended
that to you before.


I believe it's far finer and harder to always be polite and mature
on Usenet but that's my standards. Not all follow them, sadly. As
for the being tough on the Usenet, please see this image. I
always take a look at it when feeling like responding "toughly".
http://www.uberh4x0r.org/~lethalp1mp/images/funny/retard.jpg

After i've taken a look at that image, i ALWAYS loose my steam
and reword my reply. I don't want to be that "tough on Usenet". :)
 
T

Tim Streater

I see no insult against you. Sorry, if you already consider maybe
sarcastic general comments insulting to you, you are not tough enough
to survive on Usenet. BTW, in order to do that, it would also be best
not to remove the attribution lines. Probably someone has recommended
that to you before.


I believe it's far finer and harder to always be polite and mature
on Usenet but that's my standards. Not all follow them, sadly. As
for the being tough on the Usenet, please see this image. I
always take a look at it when feeling like responding "toughly".
http://www.uberh4x0r.org/~lethalp1mp/images/funny/retard.jpg

After i've taken a look at that image, i ALWAYS loose my steam
and reword my reply. I don't want to be that "tough on Usenet". :)[/QUOTE]

I feel I should point out that "lose" is spelt "lose" and not "loose".
 
K

K Viltersten

Den 2008-05-23 11:17:11 skrev Tim Streater said:
I believe it's far finer and harder to always be polite and mature
on Usenet but that's my standards. Not all follow them, sadly. As
for the being tough on the Usenet, please see this image. I
always take a look at it when feeling like responding "toughly".
http://www.uberh4x0r.org/~lethalp1mp/images/funny/retard.jpg

After i've taken a look at that image, i ALWAYS loose my steam
and reword my reply. I don't want to be that "tough on Usenet". :)

I feel I should point out that "lose" is spelt "lose" and not "loose".[/QUOTE]

I thought it was: loose, loosing, lost, have lost...
Well, one learnes something new every day. Thanks.

lose, losing, lost, have lost...
lose, losing, lost, have lost...
lose, losing, lost, have lost...

Memorized!
 
T

Thomas 'PointedEars' Lahn

K said:
^^^^^^^^^^^^^^^^^^^
I believe it's far finer and harder to always be polite and mature
on Usenet but that's my standards. Not all follow them, sadly.

So much for that.
As for the being tough on the Usenet, please see this image. I
always take a look at it when feeling like responding "toughly".

It is about reading toughly, not replying.
http://www.uberh4x0r.org/~lethalp1mp/images/funny/retard.jpg

After i've taken a look at that image, i ALWAYS loose my steam
and reword my reply. I don't want to be that "tough on Usenet". :)

This is not funny (or relevant).


Score adjusted

PointedEars
 
H

Henry

On May 22, 3:10 pm, K Viltersten wrote:
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.

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. :)


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.
 
J

John G Harris

On Thu, 22 May 2008 at 06:36:59, in comp.lang.javascript, Henry wrote:

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.

I'm surprised he says that. It shows a surprising lack of knowledge.

The condition part of an if statement is followed by exactly one
statement. A block statement is just as much exactly one statement as is
a return statement or an expression statement.

The same is also true in Algol, Pascal, C, C++, Java, and C# so there's
not much excuse for not understanding this.

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."

It's a matter of taste and common sense. If curly brackets are hidden
away so it's difficult to notice them then obviously people risk not
noticing when they're absent.

On the other hand, if a block statement looks like a distinct statement,
which it is, then its absence will be noticed :

if (a < 0)
b = 2;

if (a < 0)
{
b = 2;
c = 4;
}

(and unsurprisingly JSLint will not
pass code that omits the braces).

It's a good rule if you hire programmers who are untidy, sloppy, and
don't really know what they are doing.

Otherwise, it hides the structure of the program and is rather
insulting.

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

A lot of things are very widely considered good - eval and monster
libraries for instance - but they aren't. Here, it's not bad but anyone
who says it's the one true way is wrong and a loudmouth.

John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top