Why does 'onhashchange'in(window) work? - javascript

'onhashchange'in(window)
Having in() work is not a surprise, as new(XMLHTTPRequest) or typeof(x) are other examples of this construct, but not having to separate the string and in is.
Is this per ECMAScript specs? It works in Chrome and FF, haven't tested IE.

From what I can tell, there's no difference whether you wrap window in parenthesis or not in this particular instance. Either way, it checks for this member on the window object.
Might be less confusing if you use spaces:
'onhashchange' in (window)
The same as
'onhashchange' in window
in is not a function, but when you remove the spaces I can see how you read it as such. One advantage to wrapping window in parenthesis is that you can then minify the code:
'onhashchange'in(window)
Something you could not do without the parenthesis.

' is a token that ends a string, so a pair of '' are semantically unambiguous, you don't need whitespace after the end of a string for the lexer to know that it has reached the end of a string.
Another way of saying that is that this works for the same reason that 'Hello '+'world' works.
Additionally, in is a keyword, not a function. It seems like you're thinking of () as the "function call operator", but in this case it's just a disambiguating parentheses.
It's like asking "why does 1 +(2) work?" + doesn't become a function just because you follow it with a paren, and similarly the following will work:
function foo(){}
foo
();
Javascript is brittle with its whitespace rules.

I'm not sure if the notation is confusing you (that maybe in() is a method?), but in is one of those elements of JS that few people correctly understand (I didn't really understand it until quite recently). This is a simplified version showing what in does:
var foo = {
'bar':1,
'barbar':2
}
console.log('bar' in foo); //true
console.log('baz' in foo); //false
What makes this all the more confusing is that you can use in inside a for() loop, as if it (in) were an iterator. The way I tend to think of for loops is like this:
for (exp1; condition; exp2) {
/* statements */
}
for (condition) {
/* statements */
}
In other words, the loop will continue until the in condition fails, which will happen when it runs out of members.

Related

I don't understand one liner if else statement in javascript. Can anyone explain? [duplicate]

I once heard that leaving the curly braces in one-line statements could be harmful in JavaScript. I don't remember the reasoning anymore and a Google search did not help much.
Is there anything that makes it a good idea to surround all statements within curly braces in JavaScript?
I am asking, because everyone seems to do so.
No
But they are recommended. If you ever expand the statement you will need them.
This is perfectly valid
if (cond)
alert("Condition met!")
else
alert("Condition not met!")
However it is highly recommended that you always use braces because if you (or someone else) ever expands the statement it will be required.
This same practice follows in all C syntax style languages with bracing. C, C++, Java, even PHP all support one line statement without braces. You have to realize that you are only saving two characters and with some people's bracing styles you aren't even saving a line. I prefer a full brace style (like follows) so it tends to be a bit longer. The tradeoff is met very well with the fact you have extremely clear code readability.
if (cond)
{
alert("Condition met!")
}
else
{
alert("Condition not met!")
}
There's a readability aspect - in that when you have compound statements it can get very confusing. Indenting helps but doesn't mean anything to the compiler/interpreter.
var a;
var b;
var c;
//Indenting is clear
if (a===true)
alert(a); //Only on IF
alert(b); //Always
//Indenting is bad
if (a===true)
alert(a); //Only on IF
alert(b); //Always but expected?
//Nested indenting is clear
if (a===true)
if (b===true)
alert(a); //Only on if-if
alert (b); //Always
//Nested indenting is misleading
if (a===true)
if (b===true)
alert(a); //Only on if-if
alert (b); //Always but expected as part of first if?
//Compound line is misleading
//b will always alert, but suggests it's part of if
if (a===true) alert(a);alert(b);
else alert(c); //Error, else isn't attached
And then there's an extensibility aspect:
//Problematic
if (a===true)
alert(a);
alert(b); //We're assuming this will happen with the if but it'll happen always
else //This else is not connected to an if anymore - error
alert(c);
//Obvious
if (a===true) {
alert(a); //on if
alert(b); //on if
} else {
alert(c); //on !if
}
The thinking goes that if you always have the brackets then you know to insert other statements inside that block.
The question asks about statements on one line. Yet, the many examples provided show reasons not to leave out braces based on multiple line statements. It is completely safe to not use brackets on one line, if that is the coding style you prefer.
For example, the question asks if this is ok:
if (condition) statement;
It does not ask if this is ok:
if (condition)
statement;
I think leaving brackets out is preferable because it makes the code more readable with less superfluous syntax.
My coding style is to never use brackets unless the code is a block. And to never use multiple statements on a single line (separated by semicolons). I find this easy to read and clear and never have scoping issues on 'if' statements. As a result, using brackets on a single if condition statement would require 3 lines. Like this:
if (condition) {
statement;
}
Using a one line if statement is preferable because it uses less vertical space and the code is more compact.
I wouldn’t force others to use this method, but it works for me and I could not disagree more with the examples provided on how leaving out brackets leads to coding/scoping errors.
Technically no but very recommended!!!
Forget about "It's personal preference","the code will run just fine","it has been working fine for me","it's more readable" yada yada BS. This could easily lead to very serious problems if you make a mistake and believe me it is very easy to make a mistake when you are coding(Don't belive?, check out the famous Apple go to fail bug).
Argument: "It's personal preference"
No it is not. Unless you are a one man team leaving on mars, no. Most of the time there will be other people reading/modifying your code. In any serious coding team this will be the recommended way, so it is not a 'personal preference'.
Argument: "the code will run just fine"
So does the spaghetti code! Does it mean it's ok to create it?
Argument: "it has been working fine for me"
In my career I have seen so many bugs created because of this problem. You probably don't remember how many times you commented out 'DoSomething()' and baffled by why 'SomethingElse()' is called:
if (condition)
DoSomething();
SomethingElse();
Or added 'SomethingMore' and didn't notice it won't be called(even though the indentation implies otherwise):
if (condition)
DoSomething();
SomethingMore();
Here is a real life example I had. Someone wanted to turn of all the logging so they run find&replace "console.log" => //"console.log":
if (condition)
console.log("something");
SomethingElse();
See the problem?
Even if you think, "these are so trivial, I would never do that"; remember that there will always be a team member with inferior programming skills than you(hopefully you are not the worst in the team!)
Argument: "it's more readable"
If I've learned anything about programming, it is that the simple things become very complex very quickly. It is very common that this:
if (condition)
DoSomething();
turns into the following after it has been tested with different browsers/environments/use cases or new features are added:
if (a != null)
if (condition)
DoSomething();
else
DoSomethingElse();
DoSomethingMore();
else
if (b == null)
alert("error b");
else
alert("error a");
And compare it with this:
if (a != null) {
if (condition) {
DoSomething();
}
else {
DoSomethingElse();
DoSomethingMore();
}
} else if (b == null) {
alert("error b");
} else {
alert("error a");
}
PS: Bonus points go to who noticed the bug in the example above.
There is no maintainability problem!
The problem with all of you is that you Put semicolons everywhere. You don't need curly braces for multiple statements. If you want to add a statement, just use commas.
if (a > 1)
alert("foo"),
alert("bar"),
alert("lorem"),
alert("ipsum");
else
alert("blah");
This is valid code that will run like you expect!
There is no programming reason to use the curly braces on one line statements.
This only comes down to coders preferences and readability.
Your code won't break because of it.
In addition to the reason mentioned by #Josh K (which also applies to Java, C etc.), one special problem in JavaScript is automatic semicolon insertion. From the Wikipedia example:
return
a + b;
// Returns undefined. Treated as:
// return;
// a + b;
So, this may also yield unexpected results, if used like this:
if (x)
return
a + b;
It's not really much better to write
if (x) {
return
a + b;
}
but maybe here the error is a little bit easier to detect (?)
It's a matter of style, but curly braces are good for preventing possible dangling else's.
Always found that
if(valid) return;
is easier on my eye than
if(valid) {
return;
}
also conditional such as
(valid) ? ifTrue() : ifFalse();
are easier to read (my personal opinion) rather than
if(valid) {
ifTrue();
} else {
ifFalse();
}
but i guess it comes down to coding style
There are lots of good answers, so I won’t repeat, except as to say my “rule” when braces can be omitted: on conditions that ‘return’ or ‘throw’ (eg.) as their only statement. In this case the flow-control is already clear that it’s terminating:
Even the “bad case” can be quickly identified (and fixed) due to the terminating flow-control. This concept/structure “rule” also applies to a number of languages.
if (x)
return y;
always();
Of course, this is also why one might use a linter..
Here is why it's recommended
Let's say I write
if(someVal)
alert("True");
Then the next developer comes and says "Oh, I need to do something else", so they write
if(someVal)
alert("True");
alert("AlsoTrue");
Now as you can see "AlsoTrue" will always be true, because the first developer didn't use braces.
I'm currently working on a minifier. Even now I check it on two huge scripts. Experimentally I found out:
You may remove the curly braces behind for,if,else,while,function* if the curly braces don't include ';','return','for','if','else','while','do','function'. Irrespective line breaks.
function a(b){if(c){d}else{e}} //ok
function a(b){if(c)d;else e} //ok
Of course you need to replace the closing brace with a semicolon if it's not followed by on other closing brace.
A function must not end in a comma.
var a,b=function()c; //ok *but not in Chrome
var b=function()c,a; //error
Tested on Chrome and FF.
There are many problems in javascript. Take a look at JavaScript architect Douglas Crockford talking about it The if statement seems to be fine but the return statement may introduce a problem.
return
{
ok:false;
}
//silent error (return undefined)
return{
ok:true;
}
//works well in javascript
Not responding the question directly, but below is a short syntax about if condition on one line
Ex:
var i=true;
if(i){
dosomething();
}
Can be written like this:
var i=true;
i && dosomething();
I found this answer searching about a similar experience so I decided to answer it with my experience.
Bracketless statements do work in most browsers, however, I tested that bracketless methods in fact do not work in some browser.
As of February 26th 2018, this statement works in Pale Moon, but not Google Chrome.
function foo()
return bar;
I would just like to note that you can also leave the curly braces off of just the else. As seen in this article by John Resig's.
if(2 == 1){
if(1 == 2){
console.log("We will never get here")
}
} else
console.log("We will get here")
The beginning indentation level of a statement should be equal to the number of open braces above it. (excluding quoted or commented braces or ones in preprocessor directives)
Otherwise K&R would be good indentation style. To fix their style, I recommend placing short simple if statements on one line.
if (foo) bar(); // I like this. It's also consistent with Python FWIW
instead of
if (foo)
bar(); // not so good
If I were writing an editor, I'd make its auto format button suck the bar up to the same line as foo, and I'd make it insert braces around bar if you press return before it like this:
if (foo) {
bar(); // better
}
Then it's easy and consistent to add new statements above or below bar within the body of the if statement
if (foo) {
bar(); // consistent
baz(); // easy to read and maintain
}
No, curly braces are not necessary, However, one very important reason to use the curly brace syntax is that, without it, there are several debuggers that will not stop on the line inside the if statement. So it may be difficult to know whether the code inside the if statement ran without altering the code (some kind of logging/output statements). This is particularly a problem when using commas to add multiple lines of execution. Without adding specific logging, it may be difficult to see what actually ran, or where a particular problem is. My advice is to always use curly braces.
Braces are not necessary.....but add them anyway^
....why should you add braces in if statements if they are not necessary? Because there's a chance that it could cause confusion. If you're dealing with a project with multiple people, from different frameworks and languages, being explicit reduces the chances of errors cropping up by folks misreading each other's code. Coding is hard enough as it is without introducing confusion. But if you are the sole developer, and you prefer that coding style, then by all means, it is perfectly valid syntax.
As a general philosophy: avoid writing code, but if you have to write it, then make it unambiguous.
if (true){console.log("always runs");}
if (true) console.log("always runs too, but what is to be gained from the ambiguity?");
console.log("this always runs even though it is indented, but would you expect it to?")
^ Disclaimer: This is a personal opinion - opinions may vary. Please consult your CTO for personalized coding advice. If coding headaches persist, please consult a physician.
Please do write like this if you do if ifs:
if(a===1) if(b===2) alert(a);
alert(b);
Sometimes they seem to be needed! I couldn't believe it myself, but yesterday it occurred to me in a Firebug session (recent Firefox 22.0) that
if (! my.condition.key)
do something;
executed do something despite my.condition.key was true. Adding braces:
if (! my.condition.var) {
do something;
}
fixed that matter. There are myriards of examples where it apparently works without the braces, but in this case it definitely didn't.
People who tend to put more than one statement on a line should very definitely always use braces, of course, because things like
if (condition)
do something; do something else;
are difficult to find.
There is a way to achieve multiple line non curly braces if statements.. (Wow what english..) but it is kinda tedius:
if(true)
funcName();
else
return null;
function funcName(){
//Do Stuff Here...
}

force javascript treat variables as strings if not defined

Imagine we have a function test like this:
function test(input) {
console.log(input);
}
And we can simply call it like this:
test("hello");
Now, my problem is I have a string like this:
test(hello); test(world); test(foo); test(bar);
That I need to run. I use eval to do so, but because variables hello, word, foo, bar, ... are not defined, eval will throw ReferenceError.
I need to somehow force JavaScript to treat all undefined variables as strings. I need it to run like this:
test("hello"); test("world"); test("foo"); test("bar");
Also sometimes there are nested functions.
Is there any way to do this?
Since you have your input as a string - you could just try to replace all ( with (" and all ) with ") in order to transform your vars inside of parentheses into strings.
function test(str) {
console.log(str);
}
var initialString = "test(hello); test(world); test(foo); test(bar);";
var transformedString = initialString.replace(/\((\w+)\)/g, '("$1")');
eval(transformedString);
eval("test(test(test(test(test(hello)))))".replace(/\((\w+)\)/g, '("$1")'));
But definitely, this is not a good solution (as mentioned in comments) but just a brute force approach.
UPDATE: Updated answer to support nested calls.

Coffeescript parentheses for function invocation

Coffeescript gives the freedom to set or omit parentheses for functions calls. Like
alert 'Hi folks'
alert ('Hi folks')
are equal.
Now I am wondering, probably due to insufficient experience with coffeescript, its syntax and its aim to keep things simple, if it possible to add parentheses for a statement like the following. I know they aren't necessary.
define (require) ->
return 'goodbye'
Edit: If I apply the option to set parentheses in the same manner as for the alert statement, than I would assume this syntax shouldn't make any difference to the final js.
define ((require) ->
return 'goodbye'
)
define (require) ->
return 'goodbye'
would be equivalent to the JavaScript code
define(function(require) { return 'goodbye' })
That is, a function call to define with a function as its first (and only) argument. It is probably not what you expected the snippet to do when you asked your question.
Something I found very helpful when I played around with CoffeeScript was to try things out in the on-line "try CoffeeScript" dialogue on the CoffeeScript website. This allows you to see the JavaScript that a given snippet is compiled to, and immediately see what effect e.g. adding parentheses or changing indentation has on the resulting JavaScript code. I definitely recommend doing that. :-)
Edit to reflect the edit in the question:
Yes, adding parentheses around the function ((require) -> return 'goodbye') is valid, and doesn't alter the behaviour. Note however that "foo (bar)" and "foo(bar)" is parsed differently by the parser; in the former the parenthes denote precedence (priority, "regular parentheses"), and in the latter they are function invocation parentheses.
"foo bar", "foo(bar)", "foo (bar)" all do the same thing, but whereas "foo bar, baz" and "foo(bar, baz)" work fine, "foo (bar, baz)" is a syntax error.
Yes, you can wrap an anonymous function in parentheses.
I ran this simple script.
test.coffee
define = (func) -> func()
console.log define ((require) ->
return 'goodbye'
)
output:
goodbye

Why use (function(){})() or !function(){}()?

I was reading In JavaScript, what is the advantage of !function(){}() over (function () {})()? then it hit me, why use :
(function(){})() or !function(){}() instead of just function(){}()?
Is there any specific reason?
It depends on where you write this. function(){}() by itself will generate a syntax error as it is evaluated as function declaration and those need names.
By using parenthesis or the not operator, you enforce it to be interpreted as function expression, which don't need names.
In case where it would be treated as expression anyway, you can omit the parenthesis or the operator.
I guess you are asking why use:
var fn = (function(){}());
versus:
var fn = function(){}();
The simple answer for me is that often the function on the RHS is long and it's not until I get to the bottom and see the closing () that I realise I've been reading a function expression and not a function assignment.
A full explanation is in Peter Michaux's An Important Pair of Parens.
A slight variation on RobG's answer.
Many scripts encompass the entire program in one function to ensure proper scoping. This function is then immediately run using the double parentheses at the end. However, this is slightly different then programs which define a function that can be used in the page but not run initially.
The only difference between these two scenarios is the last two characters (the addition of the double parentheses). Since these could be very long programs, the initial parenthesis is there to indicate that "this will be run immediately."
Is it necessary for the program to run? No. Is it helpful for someone looking at the code and trying to understand it? Yes.

Are semicolons needed after an object literal assignment in JavaScript?

The following code illustrates an object literal being assigned, but with no semicolon afterwards:
var literal = {
say: function(msg) { alert(msg); }
}
literal.say("hello world!");
This appears to be legal, and doesn't issue a warning (at least in Firefox 3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed?
I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it.
Not technically, JavaScript has semicolons as optional in many situations.
But, as a general rule, use them at the end of any statement. Why? Because if you ever want to compress the script, it will save you from countless hours of frustration.
Automatic semicolon insertion is performed by the interpreter, so you can leave them out if you so choose. In the comments, someone claimed that
Semicolons are not optional with statements like break/continue/throw
but this is incorrect. They are optional; what is really happening is that line terminators affect the automatic semicolon insertion; it is a subtle difference.
Here is the rest of the standard on semicolon insertion:
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.
The YUI Compressor and dojo shrinksafe should work perfectly fine without semicolons since they're based on a full JavaScript parser. But Packer and JSMin won't.
The other reason to always use semi-colons at the end of statements is that occasionally you can accidentally combine two statements to create something very different. For example, if you follow the statement with the common technique to create a scope using a closure:
var literal = {
say: function(msg) { alert(msg); }
}
(function() {
// ....
})();
The parser might interpret the brackets as a function call, here causing a type error, but in other circumstances it could cause a subtle bug that's tricky to trace. Another interesting mishap is if the next statement starts with a regular expression, the parser might think the first forward slash is a division symbol.
JavaScript interpreters do something called "semicolon insertion", so if a line without a semicolon is valid, a semicolon will quietly be added to the end of the statement and no error will occur.
var foo = 'bar'
// Valid, foo now contains 'bar'
var bas =
{ prop: 'yay!' }
// Valid, bas now contains object with property 'prop' containing 'yay!'
var zeb =
switch (zeb) {
...
// Invalid, because the lines following 'var zeb =' aren't an assignable value
Not too complicated and at least an error gets thrown when something is clearly not right. But there are cases where an error is not thrown, but the statements are not executed as intended due to semicolon insertion. Consider a function that is supposed to return an object:
return {
prop: 'yay!'
}
// The object literal gets returned as expected and all is well
return
{
prop: 'nay!'
}
// Oops! return by itself is a perfectly valid statement, so a semicolon
// is inserted and undefined is unexpectedly returned, rather than the object
// literal. Note that no error occurred.
Bugs like this can be maddeningly difficult to hunt down and while you can't ensure this never happens (since there's no way I know of to turn off semicolon insertion), these sorts of bugs are easier to identify when you make your intentions clear by consistently using semicolons. That and explicitly adding semicolons is generally considered good style.
I was first made aware of this insidious little possibility when reading Douglas Crockford's superb and succinct book "JavaScript: The Good Parts". I highly recommend it.
In this case there is no need for a semicolon at the end of the statement. The conclusion is the same but the reasoning is way off.
JavaScript does not have semicolons as "optional". Rather, it has strict rules around automatic semicolon insertion. Semicolons are not optional with statements like break, continue, or throw. Refer to the ECMA Language Specification for more details; specifically 11.9.1, rules of automatic semicolon insertion.
Use JSLint to keep your JavaScript clean and tidy
JSLint says:
Error:
Implied global: alert 2
Problem at line 3 character 2: Missing
semicolon.
}
The semi-colon is not necessary. Some people choose to follow the convention of always terminating with a semi-colon instead of allowing JavaScript to do so automatically at linebreaks, but I'm sure you'll find groups advocating either direction.
If you are looking at writing "correct" JavaScript, I would suggest testing things in Firefox with javascript.options.strict (accessed via about:config) set to true. It might not catch everything, but it should help you ensure your JavaScript code is more compliant.
This is not valid (see clarification below) JavaScript code, since the assignment is just a regular statement, no different from
var foo = "bar";
The semicolon can be left out since JavaScript interpreters attempt to add a semicolon to fix syntax errors, but this is an extra and unnecessary step. I don't know of any strict mode, but I do know that automated parsers or compressors / obfuscators need that semicolon.
If you want to be writing correct JavaScript code, write the semicolon :-)
According to the ECMAscript spec, http://www.ecma-international.org/publications/standards/Ecma-262.htm, the semicolons are automatically inserted if missing. This makes them not required for the script author, but it implies they are required for the interpreter. This means the answer to the original question is 'No', they are not required when writing a script, but, as is pointed out by others, it is recommended for various reasons.

Categories

Resources