473,808 Members | 2,775 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
Jun 27 '08 #1
21 1197
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:

http://developer.mozilla.org/en/docs...ical_Operators

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
--
Jun 27 '08 #2
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).
Jun 27 '08 #3
>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
Jun 27 '08 #4
rf
Henry <rc*******@rain drop.co.ukwrote in news:18129482-c1c5-4d41-888e-
88**********@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
Jun 27 '08 #5
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.
Jun 27 '08 #6
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
Jun 27 '08 #7
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. :)
Jun 27 '08 #8
rf
Henry <rc*******@rain drop.co.ukwrote in news:fb90e2f3-c5c9-41bb-a794-
13**********@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
Jun 27 '08 #9
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.
Jun 27 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1241
by: Tim Reynolds | last post by:
I am using EIF to write event log entries to my application. By first creating my Event Source and then raising my event via the Event Source, I do see my entries in the Application Event Log. I want to create a custom Event log and have my log messages go there instead of to the Application Log. If not using EIF, I know I could do it using System.Diagnostics.EventLog.CreateEventSource ("Source1", "CustomLog");
0
1180
by: rob_c | last post by:
Hi, I've been working with the EIF for a few days now. One of the default event sinks provided is the WMI. I've played around a bit and can send events to the WMI. My question here centers on performance counters and the WMI. Is there any way to increase a performance counter in the WMI through the EIF or am I barking up the wrong tree (I know that .NET has other classes which allow you to manipulate performance counters)?
0
938
by: Innes | last post by:
I'm using the Enterprise Instrumentation Framework to write windows trace files. Unfortunately, when viewing them, using the sample 'Trace Log Reader' supplied with EIF, the output is not sorted chronologically. I am using the 'circular buffer' writing mode. Trace Log Reader uses the WinSDK function ProcessTrace to read the trace log. The documentation for the Windows SDK function ProcessTrace says that "the function sorts the events...
133
8613
by: Gaurav | last post by:
http://www.sys-con.com/story/print.cfm?storyid=45250 Any comments? Thanks Gaurav
3
1420
by: Janus Knudsen | last post by:
Hello there... Can somebody point me to a tutorial or article in using MOM together with EIF? Kind regards Janus
1
1422
EIF
by: Dan | last post by:
All, I am having a problem using the Logging Application Block and EIF with a Windows Service I am writing. If I run the Service under an admin account all works fine. However, If i run it under a normal user account I get the following error message in the EventLog Error loading an Event Sink of type 'Microsoft.ApplicationBlocks.Logging.EventSinks.LogEventSink, Microsoft.ApplicationBlocks.Logging.EventSinks, Version=1.0.0.0,...
1
1588
by: Bob | last post by:
The raging question that is going on currently is about log4net vs. EIF. I feel that EIF is complex and incomplete at this point. By incomplete, I mean MS is still fiddling with it. log4net is based on log4j which has been around longer and is less complex. Other than WMI, log4net accomplishes the same tasks. The question is, can you do WMI in log4net? If so, how?
10
2148
by: Mike | last post by:
Is it still true that the managed C++ compiler will produce much better opimizations than the C# compiler, or have some of the more global/aggressive opimizations been rolled into the 2005 compiler? Are simple common sub-expressions and loop invariants optimized out in the current optimizer? thanks, m
17
2122
by: Grizlyk | last post by:
Hello. What can be optimised in C++ code and how i can garantee stable behaviour below 1. Are expression "auto volatile" can deny removing as "unused temporary" like this: auto volatile const class_name tmp;
7
5634
by: bonk | last post by:
I have a c# project as part of a larger VS 2005 solution that always gets build optimized and I therefore can not evaluate any values while debugging through the code ("Cannot evaluate expression because the code of the current method is optimized."). This happens alltough the checkbock "optimize code" in the project settings is switched off. My question here is what are possible conditions that would make an assembly be build as optimized...
0
9600
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10631
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10374
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10114
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9196
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7651
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5686
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4331
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3859
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.