This question already has answers here:
Concise syntax for javascript if statements without curly brackets
(5 answers)
Closed 6 years ago.
Once and awhile I see and try to use an if statement like this:
var boo = true;
if(boo)
console.log("a");
as opposed to :
var boo = true;
if(boo == true){
console.log("a");
}else{
console.log("not true");
}
Is there a way to have an "else" with my first switch statement? How does the compiler even know when to stop? Does it do the conditional logic after a linebreak?
An if is just followed by a statement. A block (which is typically and idiomatically used there) is just a type of statement that wraps up a group of other statements.
Is there a way to have an "else" with my first switch statement?
The same is true of else
if (1)
something();
else
something_else();
How does the compiler even know when to stop?
It allows a single statement.
Does it do the conditional logic after a linebreak?
No, a statement. The line break there just triggers ASI.
The formal syntax for if else is something like:
if statement else statement
The generic "statement" there can be something like a simple assignment expression, a single function call, or a block of one or more statements enclosed in { }. Thus, the { } are not part of the syntactic structure of the if statement. They're part of the general and often-used compound statement. (JavaScript may formally call that something else; it's a common thing however and the name isn't so important. edit A comment notes that it's formally a "block statement", but I think "compound" is more descriptive so I'll leave it in.) A brace-enclosed compound statement contains any number of other statements, but from the outside it comprises just one statement.
The else part of the if statement is optional, so
if statement
is fine too.
Thus, in your examples:
if (boo)
console.log(a);
The console.log(a); is the single statement. In the second example:
var boo = true;
if(boo == true){
console.log("a");
}else{
console.log("not true");
}
there is an else clause, and both the if and the else have compound statements playing the role of the single statement in the formal syntax.
As to exactly how the parser understands that, well, that's a big topic. Suffice to say that programming languages are designed to be as unambiguous as possible, so that the code to parse the raw text of a program can be as simple as possible. Of course, as with anything, no such design is perfect, and in particular JavaScript has syntax features that are surprisingly hard to parse. What we're talking about here, however, isn't one of those. The whole purpose of the { } wrapper around a compound statement is to give the parser a clear signal: here comes a compound statement.
if (condition)
stuff...
else
stuff...
if(true)
alert("A")
else
alert("B")
alternatively
if(false)
alert("A")
else
alert("B")
Related
Can I write the if else shorthand without the else?
var x=1;
x==2 ? dosomething() : doNothingButContinueCode();
I've noticed putting null for the else works (but I have no idea why or if that's a good idea).
Edit: Some of you seem bemused why I'd bother trying this. Rest assured it's purely out of curiosity. I like messing around with JavaScript.
What you have is a fairly unusual use of the ternary operator. Usually it is used as an expression, not a statement, inside of some other operation, e.g.:
var y = (x == 2 ? "yes" : "no");
So, for readability (because what you are doing is unusual), and because it avoids the "else" that you don't want, I would suggest:
if (x==2) doSomething();
This is also an option:
x==2 && dosomething();
dosomething() will only be called if x==2 is evaluated to true. This is called Short-circuiting.
It is not commonly used in cases like this and you really shouldn't write code like this. I encourage this simpler approach:
if(x==2) dosomething();
You should write readable code at all times; if you are worried about file size, just create a minified version of it with help of one of the many JS compressors. (e.g Google's Closure Compiler)
Another option:
x === 2 ? doSomething() : void 0;
If you're not doing the else, why not do:
if (x==2) doSomething();
Using null is fine for one of the branches of a ternary expression. And a ternary expression is fine as a statement in Javascript.
As a matter of style, though, if you have in mind invoking a procedure, it's clearer to write this using if..else:
if (x==2) doSomething;
else doSomethingElse
or, in your case,
if (x==2) doSomething;
A small addition to this old thread..
If you're evaluating an expression inside a for/while loop with a ternary operator and want to continue or break as a result - you're going to have a problem because both continue & break aren't expressions; they're statements without any value.
This will produce Uncaught SyntaxError: Unexpected token continue
for (const item of myArray) {
item.value ? break : continue;
}
If you really want a one-liner that returns a statement, you can use this instead:
for (const item of myArray) {
if (item.value) break; else continue;
}
P.S - This code might raise some eyebrows. Just saying.. :)
Technically, putting null or 0, or just some random value there works (since you are not using the return value). However, why are you using this construct instead of the if construct? It is less obvious what you are trying to do when you write code this way, as you may confuse people with the no-op (null in your case).
Probably shortest (based on OR operator and its precedence)
x-2||dosomething()
let x=1, y=2;
let dosomething = console.log;
x-2||dosomething('x do something');
y-2||dosomething('y do something');
Reading through some JavaScript from an ecommerce hosting company and came across this:
function add_wishlist()
{
if ('1' == '1') // <-- What is this?
{
window.open('addtowishlist.asp?itemid=137','popup','height=300,width=550,location=no,scrollbars=no,menubars=no,toolbars=no,resizable=yes');
}
else
{
document.add.action = "add_cart.asp?action=addWishList";
document.add.submit();
}
}
From my basic understanding of JavaScript, the == equality operator will attempt type conversion if required then compare the values. In this case, the character 1 compared to the character 1, which seems like it will always be true.
I feel I might be missing something because why have an else clause if the code is always unreachable? This appears to have been purposeful code as I can't imagine it's easy to accidentally write this comparison. However, there does appear to be some inherent sloppiness to this code since JavaScript programmers should be in the habit of writing curly braces on the same line to avoid any possible semicolon insertion quirks...
Am I missing something here? Or is it just sloppy code?
Sometimes always true statements are used by developers to temporarily disable a branch of code. IMO, comments are a better way to do this.
Another possibility is that this is code generated by a tool, and this is the emitted code they got when disabling a feature.
This question already has answers here:
Do 'if' statements in JavaScript require curly braces? [duplicate]
(4 answers)
Closed 8 years ago.
I'm working thru a HTML5 projects course right now on Udemy.com and the guy's example code has this:
//Use a timer to call paint function
if(typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, speed);
I thought 'if' statements had to have curly braces so the code inside can run if the the 'if' statment is true. Please advise. Thanks
You can use if with any single statement, whether that statement is a block statement or any other kind.
The grammar for the if statement in ECMAScript is:
IfStatement :
if ( Expression ) Statement else Statement
if ( Expression ) Statement
Notice that there are no curly braces defined. Any valid statement is permitted.
This:
if (condition)
then_case();
else
else_case();
evaluates the same as this:
if (condition) {
then_case();
} else {
else_case();
}
If your have multiple statements, then you need a block statement in order to contain them.
if (condition) {
then_case();
also_this();
} else {
else_case();
also_that();
}
Sometimes you see things like
if (condition)
then_case(), also_this();
which evaluates, but is ugly. (Best just forget my last example. :-) )
Your example code is syntactically correct. You may omit the brackets assuming you have a single line of code after your if/else statement.
if (condition)
//Do something
else
//Do something
Many folks, including myself, loath this practice. Check out further discussion here:
Is it bad practice to use an if-statement without brackets?
Why is it considered a bad practice to omit curly braces?
Similar to other 'c' syntax languages, the scope of the context may be omitted if the statement is only a single line.
e.g.
if(true)
alert('hello');
is equal to
if(true) alert('hello');
is equal to
if(true){ alert('hello'); }
You may also see another form
var myBool = Boolean(someValue) ? false : true
If you have only one statement to be part of body of if or else, then curly braces are optional. But if you want group of statements to be part of if or else's body then it is mandatory to have curly braces.
if(condition)
//Only one statement
else if(condition2)
//Only one statement
else
//Only one statement
But in the following it is mandatory to have curly braces.
if(condition){
//first statement
//second statement
.....
//nth statement
}
else if(condition2){
//first statement
//second statement
.....
//nth statement
}
else{
//first statement
//second statement
.....
//nth statement
}
And please note, it is not only for JavaScript, it is same behavior in most of the programming languages as well, like C, C++, Java etc.
You don't need the curly braces for a one-line consequence of the if statement. But if the consequence of the if statement is multiple statements, then you wrap them in curly braces to identify them as such.
This question already has answers here:
Do you recommend using semicolons after every statement in JavaScript?
(11 answers)
Closed 7 years ago.
I want to know, is this legal?
function test()
{
alert ("hello")
$("#loading").show();
}
Or should I write this instead:
function test()
{
alert ("hello");
$("#loading").show();
}
Are semicolons optional in JavaScript? Because I saw this in a forum:
No, semicolons are usually optional in JavaScript (Google for ASI / automatic semicolon insertion). Using them makes the code look much cleaner though and ASI is a horrible mis-feature (at least in my opinion).
Semicolons are not always mandatory, but I would always recommend using them. See the ECMAScript spec for the rules on automatic semicolon insertion:
Certain ECMAScript statements (empty statement, variable statement,
expression statement, do-while statement, continue statement, break
statement, return statement, and throw statement) must be terminated
with semicolons. Such semicolons may always appear explicitly in the
source text. For convenience, however, such semicolons may be omitted
from the source text in certain situations. These situations are
described by saying that semicolons are automatically inserted into
the source code token stream in those situations.
Update (to explain further)
Perhaps the most common situation used to show why automatic semicolon insertion can be bad is that touched on by #sissonb in another answer. Consider the following:
function something(a, b) {
return
a + b;
}
What you may be expecting is for the new-line to be ignored, and the code interpreted as:
function something(a, b) {
return a + b;
}
Unfortunately, automatic semicolon insertion comes into play, and the code is actually interpreted like this:
function something(a, b) {
return;
a + b;
}
And an empty return statement means the function returns undefined. So instead of a nice sum of the two argument, you get undefined and potentially end up very confused as to where you've gone wrong! Which is why I completely agree with the statement in your question that automatic semicolon insertion is a horrible misfeature.
Example (returns undefined because of ASI).
Example (returns expected result).
Semicolons are not mandatory. They are automatically added at the end of a line if it is missing which actually causes this code to return undefined.
return
{
text:"hello"
}
Yeah, read properly. In the last time I saw different patterns of argument validation in JavaScript (functions) and wondered which of them would be best-practice. At first I'll show two example code snippets. The first shows an (in my words) "immediate" argument/condition validation and the second one a "delayed" validation. Each of them affect the appearance of following code in different ways. Up to now I always used the "immediate" validation. But slowly I am getting doubtful if it's reasonable to force the whole following code into such conditional blocks. Please tell me what you think and what might be the "best" pattern.
And what about the place where variables are declared? A few times I read, that ALL variables should be declared on to of the method, before they're actually used. Is this correct? Because I think that it is useless to declare variables before it is sure that they'll be actually used (maybe invalid arguments force the throw of an Exception), I moved the variable-declaration-part beyond the argument/condition validation part. Is this advisable?
Thanks!
First example:
if ( colorStops.constructor === Array
&& colorStops.length
&& colorStops.every(function(c) {
return c instanceof ColorStop
}))
{
var privateVar1 = "foo",
privateVar2 = "bar",
privateVar3 = "tutifrutti";
// here goes the code
}
else {
throw new TypeError("GradientCanvasFacade: cannot add Colors; " +
"invalid arguments received");
}
Second example:
if (cg instanceof ColorGradient) {
throw new TypeError("PresetManager: Cannot add preset; " +
"invalid arguments received");
}
var privateVar1 = "foo",
privateVar2 = "bar",
privateVar3 = "tutifrutti";
// here goes the code
// Here goes the code that get executed when no explicit
// return took place ==> all preconditions fulfilled
Since JavaScript variables are scoped to the declaring function and not to the block as most other languages, declaring variables at the beginning of the function makes alot of sense.
function someFunc()
{
if (1==1)
{
var x = 1;
}
else
{
var x = 2;
}
return x
}
Now imagine a function a lot more complex, to me atleast, declaring x at the beginning makes alot of sense. For variables generally bound to a block (like iterator variables or collections) I still declare them in the block though.
I would definitely go for your second example not because it fails earlier, because really it doesn't, but because it's easier to remove and add validations this way without breaking a complicated if structure.
I'd go with the second, simply because it's easier to read. Also, with the first, if your function is very long, someone looking at the bottom, will wonder what that } is for, and have to hop up to the top to see.
Also the scoping of variables is very clear, even for someone who forgets that javascript has weird scoping rules.
Also, as mentioned by Martijn, the second method makes it a lot easier to check for various errors, ie each can have their own if statement and so on.
if (some condition) {
if (some other condition based in the first) {
if (another condition based in 1st and 2nd) {
do_job();
} else?
} else?
} else?
Where to put the else block? After every if or after the last?
It seems absolutely more readable the second choise