By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,966 Members | 1,923 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,966 IT Pros & Developers. It's quick & easy.

If Else format

P: n/a
On page 90 of my O'Reilly "Javascript The definitive guide" 3rd edition
there is an example of an If/Else construct: (some text removed)

If (username != null)
alert("Hello " + username);
else {
username = prompt("What is your name?");
alert("Hello " + username);
}
Should I erase the first ";" from the second line?

It certainly works better in my tests that way, but I don't know if this
is an error in the book, a change in the way JavaScript works, or a flaw
in my browser.

--
Steve Swift
http://www.swiftys.org.uk/swifty.html
http://www.ringers.org.uk
Sep 19 '08 #1
Share this Question
Share on Google+
21 Replies


P: n/a

Steve Swift schreef:
On page 90 of my O'Reilly "Javascript The definitive guide" 3rd edition
there is an example of an If/Else construct: (some text removed)

If (username != null)
alert("Hello " + username);
else {
username = prompt("What is your name?");
alert("Hello " + username);
}
Should I erase the first ";" from the second line?
No. Why should you?
It is the end of a command, and for clarities sake, use a semicolon.
>
It certainly works better in my tests that way, but I don't know if this
is an error in the book, a change in the way JavaScript works, or a flaw
in my browser.
How does it work better without the semicolon???

Erwin Moller

--
============================
Erwin Moller
Now dropping all postings from googlegroups.
Why? http://improve-usenet.org/
============================
Sep 19 '08 #2

P: n/a
On Sep 19, 8:17*am, Steve Swift <Steve.J.Sw...@gmail.comwrote:
On page 90 of my O'Reilly "Javascript The definitive guide" 3rd edition
there is an example of an If/Else construct: (some text removed)

If (username != null)
* *alert("Hello " + username);
else {
* *username = prompt("What is your name?");
* *alert("Hello " + username);

}

Should I erase the first ";" from the second line?
I'd wrap that alert in curly braces:

If (username != null) {
alert("Hello " + username);
} else {
username = prompt("What is your name?");
alert("Hello " + username);
}

--
Jorge.
Sep 19 '08 #3

P: n/a
SAM
Steve Swift a écrit :
On page 90 of my O'Reilly "Javascript The definitive guide" 3rd edition
there is an example of an If/Else construct: (some text removed)

If (username != null)
no ... : if ( blah )
(lowercase)
alert("Hello " + username);
else {
username = prompt("What is your name?");
alert("Hello " + username);
}
Should I erase the first ";" from the second line?
The ';' in end of line is optional in JS
function hello() {
if(typeof username == 'undefined' || username == null)
username = prompt('What is your name?')
alert('Hello ' + username)
}

works as well as :

function hello() {
if(typeof username == 'undefined' || username == null) {
username = prompt('What is your name?');
}
alert('Hello ' + username);
}

But ... it's much better to code correctly.

--
sm
Sep 19 '08 #4

P: n/a
Jorge wrote:
I'd wrap that alert in curly braces:

If (username != null) {
alert("Hello " + username);
} else {
username = prompt("What is your name?");
alert("Hello " + username);
}
Yes, but those curly braces are redundant in the case of the single
statement above, and in the example. And your ";" is now inside the
curly braces, so terminating the alert() statement. In my O'Reilly book,
it seems to be terminating the "If" statement.

My difficulty is that I don't know if an if/else combination is a single
statement (in which case the ";" shouldn't have been in the example) or
two separate statements (in which case I'm wondering why it doesn't work
in any browser that I've tried).

The evidence is stacked heavily in favour of an error in the book, but
stranger things have happened.

--
Steve Swift
http://www.swiftys.org.uk/swifty.html
http://www.ringers.org.uk
Sep 19 '08 #5

P: n/a
Steve Swift wrote on 19 sep 2008 in comp.lang.javascript:
Jorge wrote:
>I'd wrap that alert in curly braces:

If (username != null) {
alert("Hello " + username);
} else {
username = prompt("What is your name?");
alert("Hello " + username);
}

Yes, but those curly braces are redundant in the case of the single
statement above, and in the example. And your ";" is now inside the
curly braces, so terminating the alert() statement. In my O'Reilly
book, it seems to be terminating the "If" statement.
Don't take O'Reilly as a standard.
Perhaps do not use it at all.
My difficulty is that I don't know if an if/else combination is a
single statement (in which case the ";" shouldn't have been in the
example) or two separate statements (in which case I'm wondering why
it doesn't work in any browser that I've tried).
No, the Q is if the

alert("Hello " + username);

is a single statement.
The evidence is stacked heavily in favour of an error in the book, but
stranger things have happened.
No, that is not strange, the archive of this NG reports many such errors.

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Sep 19 '08 #6

P: n/a
On Fri, 19 Sep 2008 07:17:31 +0100, Steve Swift wrote:
On page 90 of my O'Reilly "Javascript The definitive guide" 3rd edition
there is an example of an If/Else construct: (some text removed)

If (username != null)
alert("Hello " + username);
else {
username = prompt("What is your name?"); alert("Hello " + username);
}
I think that just about everyone in this group will agree with the
recommendation of: Always use {} in ifs and loops.

Just solves a lot of headaches.

if (username != null)
alert("Hello " + username);
else
username = prompt("What is your name?"); alert("Hello " + username);

is actually the same as:

if (username != null) {
alert("Hello " + username);
} else {
username = prompt("What is your name?");
}
alert("Hello " + username);

and
if (username != null)
alert("Hello " + username)
;
else
username = prompt("What is your name?"); alert("Hello " + username);

is the same as:
if (username != null) {
alert("Hello " + username);
}
;
else {
username = prompt("What is your name?"); alert("Hello " + username);
}

Sep 19 '08 #7

P: n/a
On 2008-09-20 01:45, Jeremy J Starcher wrote:
I think that just about everyone in this group will agree with the
recommendation of: Always use {} in ifs and loops.
No argument there.
if (username != null)
alert("Hello " + username)
;
else
username = prompt("What is your name?"); alert("Hello " + username);

is the same as:
if (username != null) {
alert("Hello " + username);
}
;
else {
username = prompt("What is your name?"); alert("Hello " + username);
}
.... but argument here.

Your second example is a syntax error, and thus not the same as the
first. You can omit the curly braces if - and ONLY if - they contain
only a single statement or expression. If you do use the braces, you
cannot insert anything between the closing curly of the if-branch and
"else" (except for comments and an optional "else if" branch, of
course), not even an empty statement like ";".

To answer the OP's question,

| In my O'Reilly book, it seems to be terminating the "If" statement.

It does not. This is a special syntactic case in which you're allowed to
leave the curly braces out, for one branch, but that doesn't mean that's
the end of the conditional statement.

When you're in doubt, always use curly braces. Even when there are no
doubts - you don't really save a lot of space when you write

if (condition)
do_something();
else
eh_dont();

instead of

if (condition) {
do_something();
} else {
eh_dont();
}

In my personal opinion, the only time when omitting the curlies is OK is
when you're doing something like this:

if (flag_blah) arg += 1;
if (flag_bloh) arg += 2;
if (flag_blim) arg += 4;

Anything more complicated than that - use curlies. And by the way,
always use the semicolon too, even if it's not technically necessary.
- Conrad
Sep 20 '08 #8

P: n/a
Jeremy J Starcher wrote on 20 sep 2008 in comp.lang.javascript:
I think that just about everyone in this group will agree with the
recommendation of: Always use {} in ifs and loops.
I think not.

It depends on the complexity, the need for change by others, and most
important the mood of the programmer, "you" or "me".

Moreover I think "think that just about everyone in this group" is
incorrect, because you did not research it with an open Q,
and even then most will not bother to answer, as it is just their own
business.

Why not simply say you personally recommmend the use of {},
in stead of surmizing uncoroborated facts?

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Sep 20 '08 #9

P: n/a
On Sep 20, 3:50*am, Conrad Lender <crlen...@yahoo.comwrote:
In my personal opinion, the only time when omitting the curlies
is OK is when you're doing something like this:

if (flag_blah) arg += 1;
if (flag_bloh) arg += 2;
if (flag_blim) arg += 4;

Anything more complicated than that - use curlies.(...)
Geekish (?) :

javascript:if (1) alert('1'), alert('2');
javascript:if (0) alert('1'); alert('2');

.... or evil ?

Predictable :

javascript:if (1) { alert('1'), alert('2'); }
javascript:if (0) { alert('1'); alert('2'); }

I always use {}.

--
Jorge.
Sep 20 '08 #10

P: n/a
Evertjan. wrote:
Jeremy J Starcher wrote on 20 sep 2008 in comp.lang.javascript:
>I think that just about everyone in this group will agree with the
recommendation of: Always use {} in ifs and loops.

I think not.

It depends on the complexity, the need for change by others, and most
important the mood of the programmer, "you" or "me".

Moreover I think "think that just about everyone in this group" is
incorrect, because you did not research it with an open Q,
and even then most will not bother to answer, as it is just their own
business.

Why not simply say you personally recommmend the use of {},
in stead of surmizing uncoroborated facts?
You have an interesting opinion.

I believe that Jeremy expressed a useful opinion.

If I say :

1) ' My opinion is A, and I believe the frequency of this
opinion is B % among group G'

then I transmit more information about my opinions than

2) 'My opinion is A'

If we allow beliefs and opinions here, why should we not
allow expressing beliefs about frequencies, probabilities, numbers?

I agree with Jeremy, using common human language,
not syntactically strict
computer language as in some standards:

' I also believe that almost all in
this group think it is good recommendation to use {} in ifs and loops'.

If one puts a socially blind syntax checker robot to find errors in
the above statement, one gets a long list of error messages.



Sep 20 '08 #11

P: n/a
> if (username != null)
> alert("Hello " + username)
;
else
username = prompt("What is your name?"); alert("Hello " +
username);

is the same as:
if (username != null) {
alert("Hello " + username);
}
;
else {
username = prompt("What is your name?"); alert("Hello " +
username);
}

... but argument here.

Your second example is a syntax error, and thus not the same as the
first. You can omit the curly braces if - and ONLY if - they contain
only a single statement or expression. If you do use the braces, you
cannot insert anything between the closing curly of the if-branch and
"else" (except for comments and an optional "else if" branch, of
course), not even an empty statement like ";".
Ouch, mis-understood the specs on that one.
Sep 20 '08 #12

P: n/a
optimistx wrote on 20 sep 2008 in comp.lang.javascript:
Evertjan. wrote:
>Jeremy J Starcher wrote on 20 sep 2008 in comp.lang.javascript:
>>I think that just about everyone in this group will agree with the
recommendation of: Always use {} in ifs and loops.

I think not.

It depends on the complexity, the need for change by others, and most
important the mood of the programmer, "you" or "me".

Moreover I think "think that just about everyone in this group" is
incorrect, because you did not research it with an open Q,
and even then most will not bother to answer, as it is just their own
business.

Why not simply say you personally recommmend the use of {},
in stead of surmizing uncoroborated facts?

You have an interesting opinion.

I believe that Jeremy expressed a useful opinion.

If I say :

1) ' My opinion is A, and I believe the frequency of this
opinion is B % among group G'

then I transmit more information about my opinions than

2) 'My opinion is A'

If we allow beliefs and opinions here, why should we not
allow expressing beliefs about frequencies, probabilities, numbers?

I agree with Jeremy, using common human language,
not syntactically strict
computer language as in some standards:

' I also believe that almost all in
this group think it is good recommendation to use {} in ifs and loops'.
You miss the word "all".

Then he could be wrong,
and he is wrong, in my view.
If one puts a socially blind syntax checker robot to find errors in
the above statement, one gets a long list of error messages.


--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Sep 21 '08 #13

P: n/a
optimistx wrote on 21 sep 2008 in comp.lang.javascript:
>>>>I think that just about everyone in this group will agree with the
recommendation of: Always use {} in ifs and loops.
...
>>' I also believe that almost all in
this group think it is good recommendation to use {} in ifs and
loops'.

You miss the word "all".

Then he could be wrong,
and he is wrong, in my view.

all? Where?
.... good recommendation to use {} in ALL ifs and loops' ...

I do not agree with that.
'about everyone' might not be correct official English, but I
as a foreigner understand that meaning 'almost all'. And how many
percent of all that might be? at least 51%? at least 75 %? at least 90%?
You were on the wrong track.

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Sep 21 '08 #14

P: n/a
Evertjan. wrote:
optimistx wrote on 21 sep 2008 in comp.lang.javascript:
....
... good recommendation to use {} in ALL ifs and loops' ...

I do not agree with that.
>'about everyone' might not be correct official English, but I
as a foreigner understand that meaning 'almost all'. And how many
percent of all that might be? at least 51%? at least 75 %? at least
90%?

You were on the wrong track.
Yes, I was, thanks for the correction.

If we consider everyday language expression

'...good recommendation to use {} in all ifs and loops'

we may ask :' if it is not a good recommendation, what is it? Bad?'.

http://jslint.com recommends:

--- start of quote ---
'
Required Blocks
JSLint expects that if and for statements will be made with blocks {that is,
with statements enclosed in braces}.

JavaScript allows an if to be written like this:

if (condition)
statement;That form is known to contribute to mistakes in projects where
many programmers are working on the same code. That is why JSLint expects
the use of a block:

if (condition) {
statements;
}Experience shows that this form is more resilient.'

---end of quote ---

and I believe that this IS a good recommendation and I believe most other
writers in this newsgroup agree with that :).


Sep 21 '08 #15

P: n/a
optimistx wrote on 21 sep 2008 in comp.lang.javascript:
Evertjan. wrote:
>optimistx wrote on 21 sep 2008 in comp.lang.javascript:
...
>... good recommendation to use {} in ALL ifs and loops' ...

I do not agree with that.
>>'about everyone' might not be correct official English, but I
as a foreigner understand that meaning 'almost all'. And how many
percent of all that might be? at least 51%? at least 75 %? at least
90%?

You were on the wrong track.

Yes, I was, thanks for the correction.

If we consider everyday language expression

'...good recommendation to use {} in all ifs and loops'

we may ask :' if it is not a good recommendation, what is it? Bad?'.

http://jslint.com recommends:

--- start of quote ---
'
Required Blocks
JSLint expects that if and for statements will be made with blocks
{that is, with statements enclosed in braces}.

JavaScript allows an if to be written like this:

if (condition)
statement;That form is known to contribute to mistakes in projects
where
many programmers are working on the same code. That is why JSLint
expects the use of a block:

if (condition) {
statements;
}Experience shows that this form is more resilient.'

---end of quote ---
The idea's or experiences of jslint do not prove anything.

I concede it is more resilient,
but that does not warrant a general advisory rule.

Example:

Not using javascript is very resilient.
It even is a good advice in cases where html only get you as or more
easily to the same end.
and I believe that this IS a good recommendation and I believe most
other writers in this newsgroup agree with that :).
I do not attack your believes. I attack the advice with "always".
I think it is wrong to advice such semantics.

Example:

I love nicely indented code,
but there are situations it does not add to the usefullness,
but instead is even harmfull.

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Sep 21 '08 #16

P: n/a
Evertjan. meinte:
Example:

I love nicely indented code,
but there are situations it does not add to the usefullness,
but instead is even harmfull.
Harmful? When?

And what are the advantages of not using curly braces - apart from
saving say 4 to 5 bytes each time they are omitted?

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
Sep 22 '08 #17

P: n/a

Evertjan. schreef:
optimistx wrote on 21 sep 2008 in comp.lang.javascript:
>Evertjan. wrote:
>>optimistx wrote on 21 sep 2008 in comp.lang.javascript:
...
>>... good recommendation to use {} in ALL ifs and loops' ...

I do not agree with that.

'about everyone' might not be correct official English, but I
as a foreigner understand that meaning 'almost all'. And how many
percent of all that might be? at least 51%? at least 75 %? at least
90%?
You were on the wrong track.
Yes, I was, thanks for the correction.

If we consider everyday language expression

'...good recommendation to use {} in all ifs and loops'

we may ask :' if it is not a good recommendation, what is it? Bad?'.

http://jslint.com recommends:

--- start of quote ---
'
Required Blocks
JSLint expects that if and for statements will be made with blocks
{that is, with statements enclosed in braces}.

JavaScript allows an if to be written like this:

if (condition)
statement;That form is known to contribute to mistakes in projects
where
many programmers are working on the same code. That is why JSLint
expects the use of a block:

if (condition) {
statements;
}Experience shows that this form is more resilient.'

---end of quote ---

The idea's or experiences of jslint do not prove anything.

I concede it is more resilient,
but that does not warrant a general advisory rule.

Example:

Not using javascript is very resilient.
It even is a good advice in cases where html only get you as or more
easily to the same end.
>and I believe that this IS a good recommendation and I believe most
other writers in this newsgroup agree with that :).

I do not attack your believes. I attack the advice with "always".
I think it is wrong to advice such semantics.

Example:

I love nicely indented code,
but there are situations it does not add to the usefullness,
but instead is even harmfull.
Oh come on, this is a nondiscussion.

I'll settle it for you, once and for all ;-)

1) Always use {} for all your logical block (if/then/else, foreach, etc)
2) Always end a command with semicolon ;

That way your code is understandable (syntaxwise) for any other programmer.

IMHO it is a designmistake that {} and ; are allowed to be omitted in
certain situations.

Erwin Moller

--
============================
Erwin Moller
Now dropping all postings from googlegroups.
Why? http://improve-usenet.org/
============================
Sep 22 '08 #18

P: n/a
On Sep 22, 7:56*am, Erwin Moller
<Since_humans_read_this_I_am_spammed_too_m...@spam yourself.comwrote:
I'll settle it for you, once and for all ;-)

1) Always use {} for all your logical block (if/then/else, foreach, etc)
2) Always end a command with semicolon ;

That way your code is understandable (syntaxwise) for any other programmer.

IMHO it is a designmistake that {} and ; are allowed to be omitted in
certain situations.

Yes, I agree completely. Unfortunately, at my shop, we have tons on
ASP pages ('mixin' of server-side VBScript and client-side JScript)
where not one semicolon can be found.

However, now that we've decided that {} should always be used, we need
to decide where. Should the opening curly bracket be on the same line
as the conditional,function etc. or on the next line?

if (blah) {
}

or

if (blah)
{
}

The readability of the second case is considered superior, however in
some cases it can cause program errors. As Crockford points out in
"javascript: The Good Parts",

return
{
status: true
};

returns undefined, whereas

return {
status: true
};

returns true.
Bob
Sep 22 '08 #19

P: n/a
On Sep 22, 2:34 pm, beegee wrote:
<snip>
if (blah) {

}

or

if (blah)
{

}

The readability of the second case is considered superior,
<snip>

Not universally. Personally I find the first more readable.

I would want to see any instance on one or the other (and/or the other
variations) accompanied by some genuine (peer reviewed) research into
their relative readabilities. Otherwise it is just personal opinion.

(I also _always_ put braces around if/else, with, while, do and for
blocks regardless of whether they are strictly required.)
Sep 22 '08 #20

P: n/a
beegee wrote:
On Sep 22, 7:56 am, Erwin Moller
<Since_humans_read_this_I_am_spammed_too_m...@spam yourself.comwrote:
>I'll settle it for you, once and for all ;-)

1) Always use {} for all your logical block (if/then/else, foreach, etc)
2) Always end a command with semicolon ;

That way your code is understandable (syntaxwise) for any other programmer.

IMHO it is a designmistake that {} and ; are allowed to be omitted in
certain situations.

Yes, I agree completely. Unfortunately, at my shop, we have tons on
ASP pages ('mixin' of server-side VBScript and client-side JScript)
where not one semicolon can be found.
Non sequitur. ASP is an (IIS-based) application framework that supports
both VBScript and JScript, among other programming languages. In VBScript,
a semicolon is a syntax error, and there are no braces.
However, now that we've decided that {} should always be used, we need
to decide where. Should the opening curly bracket be on the same line
as the conditional,function etc. or on the next line?
A matter of taste and teamwork.
if (blah) {
}

or

if (blah)
{
}

The readability of the second case is considered superior, however in
some cases it can cause program errors. As Crockford points out in
"javascript: The Good Parts",

return
{
status: true
};

returns undefined, whereas

return {
status: true
};

returns true.
You (and Douglas) would need to recognize the difference between a block
statement and an Object initializer; here, the latter is meant (else it
would be a syntax error). Writing the braces for the former on their own
line always, and for the latter not, helps to see that difference. This is
also how I recommend to make the difference between function statements and
function expressions:

function foo()
{
// ...
}

but

var bar = function baz() {
// ...
};

foobar(
/x/,
function baz() {
// ...
});
HTH

PointedEars
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
madness: XHTML 1.1 as application/xhtml+xml
-- Bjoern Hoehrmann
Sep 22 '08 #21

P: n/a
On Sep 22, 1:00*pm, Thomas 'PointedEars' Lahn <PointedE...@web.de>
wrote:
Non sequitur. *ASP is an (IIS-based) application framework that supports
both VBScript and JScript, among other programming languages. *In VBScript,
a semicolon is a syntax error, and there are no braces.
Could have sworn I implied that if not actually said that.
>...Writing the braces for the former on their own
line always, and for the latter not, helps to see that difference. *This is
also how I recommend to make the difference between function statements and
function expressions:

* function foo()
* {
* * // ...
* }

but

* var bar = function baz() {
* * // ...
* };

* foobar(
* * /x/,
* * function baz() {
* * * // ...
* * });

Good suggestion. Thanks.

Bob
Sep 23 '08 #22

This discussion thread is closed

Replies have been disabled for this discussion.