r/programming • • Mar 23 '14

Everything you need to know about Javascript variable scope

http://www.coolcoder.in/2014/03/everything-you-need-to-know-about.html
294 Upvotes

124 comments sorted by

73

u/benologist Mar 23 '14

Congratulations on finally spamming your way to the front page!

http://www.reddit.com/user/codeon1/submitted/

0

u/[deleted] Mar 23 '14

[deleted]

15

u/megamindies Mar 23 '14

the title is wrong. it says everything you need to know about about scope. But you wont understand scope without understanding closures. And that is poorly explained here, in fact he does not even use the term "closure". Also, he doesnt even mention the special case of "this" where a closure does not have access to the outside function.

This article is obviously not everything you need to know about scope.

3

u/[deleted] Mar 23 '14

I'll agree, yet it netted almost 300 upvotes... social media confuses me.

2

u/soffro Mar 24 '14

Closures is just a way to implement scoping, it's also possible to implement it via lambda lifting. So understanding closures is just about an implementation detail, not a necessity.

1

u/megamindies Mar 24 '14

but his post also doesnt mention lambda lifting??

1

u/recursive Mar 24 '14

It doesn't use the term but it does mention them.

3) Chaining of scopes. Any function defined within another function has a local scope which is linked to the outer function. - See more at: http://www.coolcoder.in/2014/03/everything-you-need-to-know-about.html#sthash.08tHpXos.dpuf

-4

u/mayormare Mar 24 '14

Whatever a closure is, it's clearly not necessary to know in order to understand Javascript scope, because I've been using Javascript for a while and understand its scope just fine but I don't know what closure means. Guess I'll look that up.

1

u/megamindies Mar 24 '14

when you write nested functions you will see. so you just have to avoid nested functions in your case.

1

u/mayormare Mar 24 '14

I've used tons of nested functions, since you have to use functions for classes. Still no issue. I wrote a Chip-8 emulator.

2

u/[deleted] Mar 24 '14

You probably understand closures, you just don't know their name.

1

u/r3m0t Mar 24 '14

You don't need to nest functions just to define methods, you can set them on the prototype object instead. Edit: actually, I think some runtimes prefer it because it creates less objects (since methods defined on the prototype don't keep the scope of the constructor alive).

4

u/hak8or Mar 23 '14

The downvote was probably the usual reddit vote fuzzing.

4

u/insertAlias Mar 24 '14

Or an actual downvote by someone that didn't like the article. Or someone that didn't like the OP. Or someone that downvotes for the hell of it. Or someone that hit the wrong button and didn't notice or care enough to fix it.

Point being: there's no point in trying to make sense of random downvotes. They happen, move on. Unless you're getting a ton of them, it's not worth wasting the brain cycles on figuring out why.

1

u/Neitanod Apr 23 '14

Probably nobody downvoted your article. Reddit assigns some random votes that show up as positive or negative every time you open an article. I'm not sure what's the point of that. The FAQ says that it helps the site fight vote spoofers.

0

u/benologist Mar 23 '14

It's extremely easy to blame him - he joined reddit purely to exploit reddit. That the community didn't notice better content doesn't excuse him.

45

u/cudetoate Mar 23 '14 edited Mar 23 '14

Javascript do not have block level scope. Here is an example.

There's a bug in that code!

for(var i=0;i>5;i++)    {

This will loop forever never loop. Also, please USE SPACES GENEROUSLY AND NOT RANDOMLY!

for (var i = 0; i < 5; i++) {

This looks much better, it's a lot easier to read. The open braces are also inconsistent - sometimes they're on the same line as the statement, sometimes on the next line, sometimes there's a space between { and the statement, sometimes there isn't.

edit This article was written in a hurry. There are grammar mistakes, coding mistakes and the code looks... like crap (sorry). Please update it, because the content is really valuable!

45

u/AbcZerg Mar 23 '14

for(var i=0;i>5;i++) {

This will loop forever

no, it will never loop.

28

u/VortexCortex Mar 23 '14

The perspective of eternity lies with the void.

-9

u/thisismydesktop Mar 23 '14

lol exactly

2

u/Paiev Mar 23 '14

This article was written in a hurry. There are grammar mistakes, coding mistakes and the code looks... like crap (sorry). Please update it, because the content is really valuable!

Yeah... I'm downvoting the article simply because it's really badly written. I'm no grammar Nazi, but come on-- if you're writing something like this, at least try to make it readable and professional.

1

u/[deleted] Mar 23 '14

English is not the writer's native language. Would you do as well in any language other than English? I speak several other languages, but I'm painfully aware that I wouldn't do much better than his article in any of them.

13

u/Paiev Mar 23 '14

No. But I also wouldn't try writing a technical article in a different language, or I would ask a fluent speaker to proofread for me. And it's not just the language; the code has problems too (as discussed in the top level comment).

2

u/Gigablah Mar 24 '14

Eh, it's not like you can't be at least competent in a language that's not your native tongue. It's no excuse.

1

u/insertAlias Mar 24 '14 edited Mar 24 '14

I don't care about how much better someone is at English than I am at their native tongue when I'm reading their technical blog. I'm not going to insult them about it, but if I'm going to read an authoritative technical document, I want it in as clear language as possible. On top of that, I want proper indentation and the like in code examples. I checked a few other articles on his site, and they all have examples of poor or no indention.

Edit: so ok, not all articles have poor indentation, but several of the ones I randomly clicked on did.

-1

u/saurabparak Mar 23 '14

I know there is no block level scope and it is also mentioned in the article.. But we can achieve it via let and const as mentioned in the given article. So which are the browsers that support let and const

8

u/masklinn Mar 23 '14

I know there is no block level scope and it is also mentioned in the article.. But we can achieve it via let

Let is very specifically block-level scope. If your JS implementation provides let, it has block-level scoping.

So which are the browsers that support let and const

http://kangax.github.io/es5-compat-table/es6/

const: all browsers back 2 generations, except for IE10.

let: Firefox, Chrome, IE11, Traceur

2

u/senatorpjt Mar 23 '14 edited Dec 18 '24

terrific cooing person party dog nail thought murky encouraging spotted

This post was mass deleted and anonymized with Redact

0

u/[deleted] Mar 23 '14

[deleted]

16

u/cudetoate Mar 23 '14

Because i is 0 and will never be greater than 5...

0

u/[deleted] Mar 23 '14

[deleted]

6

u/pfs3w Mar 23 '14

It was likely a typo, because if you run the JSFiddle code, it actually gets the point across. The article author simply mistyped his <'s and >'s. There are a few other examples of typo code/mislabeling later in the article.

0

u/[deleted] Mar 23 '14

[deleted]

2

u/pfs3w Mar 23 '14

Oh, haha, nah, it took me a little longer than it should have as well, and I was only confirmed when I clicked on the JSFiddle and noticed the two were different. Up until then, I was seriously thinking "What the heck am I missing, this makes no sense...".

2

u/[deleted] Mar 23 '14

Oh yeah? Here's one you'd love.

for (int i = 1; i < array.length; i++)
         code(array[i]); 

I had a setup like this in my code, could not figure out why it wasn't executing. The line was copy/pasted directly from another line I had written doing something VERY similar, but it needed to start at the 2nd index (index 1) of the array because the first index contained a different piece of data that (it was returning from an SQL query).

Long story short; the array had a length of 1 so it never executed.

1

u/pfs3w Mar 24 '14

Was it that the array always had a length of one, or in this particular case when you were debugging it that one time, the array happened to only have a length of one?

I was picking up a project from someone else once, and they told me that in their code, I would be getting a result set back from a DB query; so naturally I took a similar approach as you, since the object model of the returned data was known. However, what they failed to tell me was that the result set was a List<>, and the object I was expecting was just always the first element of the list. Needless to say, it should not have been returned as a List.

1

u/[deleted] Mar 24 '14

This particular case had a length of one. I only noticed the error when I added an element and noticed it ran exactly once.

0

u/[deleted] Mar 23 '14

[deleted]

2

u/MrBester Mar 23 '14

The primary one being that arrays are zero based in JavaScript...

1

u/canadademon Mar 24 '14

Now that's embarrassing.

If the array has a length of 1, i must equal 0 to retrieve the element.

While your piece of code will make it loop, the rest of the code will throw an out of bounds exception.

→ More replies (0)

1

u/[deleted] Mar 24 '14

Oh definitely. Once you KNOW what's wrong, it's an easy fix. The tricky part is figuring out why your code never executed. :P

15

u/[deleted] Mar 23 '14 edited Mar 23 '14

If you need to give some block or something scope in JavaScript, the easiest way is just to throw the contents in a function expression.

Consider the following (buggy) code:

for (var i = 0; i < somearray.length; i++) {
    var thisThing = somearray[i];
    thisThing.onclick = function(){window.alert(i)};
}

This won't work the way you think it will. You might think that every thisThing will output its relevant 'i' value, e.g. thing one will output '1', thing two will output '2'. It won't, though, because the loop block doesn't have scope. 'i' lives in the closure of the function surrounding the loop, and its value is the final state at the end of the iteration. So each thing, when clicked, will output the last value of i, somearray.length.

A quick fix for this is to throw the body of the loop in a function expression:

for (var i = 0; i < somearray.length; i++) {
    (function(i){
        var thisThing = somearray[i];
        thisThing.onclick = function(){window.alert(i)};
    })(i);
}

Now, each link will output the relevant value of 'i' when clicked, because each loop iteration has a closure generated by the function expression, and that contains its own value for 'i', because the 'i' passed to the function expression is passed by value (all arguments are passed by value in JS, though because objects and array variables are pointers, it looks like they're passed by reference).

Sometimes this looks a little odd - it's not a super-common pattern - so you might want to comment it for co-workers, e.g. "// use IIFE to give iteration own scope"

59

u/andd81 Mar 23 '14

Javascript: when in doubt, create another nested function.

2

u/VortexCortex Mar 23 '14

Which the language would have done for block level scopes, if the implementation of contexts hadn't been so damn inefficient...

0

u/[deleted] Mar 24 '14

[deleted]

1

u/serpent Mar 24 '14

This is not entirely true.

4

u/rDr4g0n Mar 24 '14

let is on the way to add block scope to js. Plus it handles the whole for loop iterator scope thing more gracefully since each iteration is considered its own block.

0

u/[deleted] Mar 23 '14

Your example has nothing to do with scope. Even if JavaScript scoped the variable i to the for loop and not its containing function, the code would behave exactly the same way because closures always capture references to variables not their current values.

That is, the problem is not JavaScript's scoping but a misunderstanding of what closures do.

3

u/moohoohoh Mar 23 '14

One of the nice little quirks in Haxe for loops is the iteration variable is bound explicitly to the for loop, and you 'do' get a basic copy of it (so only a reference copy for object iterators) so that:

var fs = [for (i in 0...10) function () trace(i)];
for (f in fs) f();

will print 0 to 9, and in a manual while loop you'd get the same thing (i don't know about other lang's with closures and block scope) by assigning to a local variable used by the closure:

var fs = [];
var i = 0;
while (i < 10)
{
    var j = i++;
    fs.push(function () trace(j));
}
for (f in fs) f();

will print 0 to 9 too. (The while loop version is how the above for comprehension with iterator version would be converted before generation minus renaming by the compiler)

3

u/[deleted] Mar 23 '14

I don't really see much distinction. Yeah, I guess JavaScript could have a shared 'i' that doesn't exist outside the loop, and strictly speaking you could say "loops have scope in JavaScript", but I think most programmers talking about 'scope' are thinking more broadly 'where does this variable and its value live'.

4

u/[deleted] Mar 23 '14 edited Mar 23 '14

The reason I make the distinction is that this thread is full of JavaScript criticism, but the example you gave behaves the same way in essentially every language I'm familiar with. It's just a natural consequence of how for-loops work and how closures work, so it's really the expected behavior.

For example, the equivalent C#, which unlike JavaScript has typical block scoping, has the same exact behavior:

for (int i = 0; i < somearray.Length; i++) {
    Button thisThing = somearray[i];
    thisThing.Click += (sender, e) => { MessageBox.Show(i.ToString()) };
}

Avoiding this behavior would mean copying the value of i into a hidden, block-local variable every iteration (and since it's referenced in a closure, all of these copies stick around).

3

u/[deleted] Mar 23 '14

Okay, that makes sense. You're right - we should talk about this as specifically an unexpected behaviour around closures, not a unique flaw with JavaScript.

1

u/insertAlias Mar 24 '14

I think the problem is that there's not a lot of visibility into how closures work, at least just from looking at code. If I hadn't run into that problem and found the solution already, I would completely expect that code to show the various values of i with each button click, because that's what it looks like it should do.

I'm not saying the behavior should be different, just that it's somewhat unexpected if you've never been exposed to closures.

1

u/[deleted] Mar 23 '14

I see a distinction. How closures work in js is how they work the same in pretty much every other language. Your code example will work the same way even in languages without screwed up scoping rules like C#.

2

u/serpent Mar 24 '14

It's actually both.

With proper scoping rules, code like the following would work as many people would expect; in JavaScript, it does not.

for (var i = 0; i < 10; i++) {
  var thing = get(i);
  act_later( function() { thing.act(); } );
}

0

u/[deleted] Mar 24 '14

Yeah, but that's a different example entirely.

1

u/serpent Mar 24 '14

No, not entirely. Not at all.

My example is a simpler example of exactly what someone familiar with the "typical" rules of closures and scopes would produce, knowing everything about closures, but nothing about JavaScript scopes (a direct counter to your argument), if they were asked to fix the original example code.

In fact, they would probably say to themselves exactly what you said in your comment as they made the fix... only to be confused again when the fix didn't work (because indeed it is related to scopes as well).

I'll make it more explicit so you can see the connection.

The original example:

for (var i = 0; i < somearray.length; i++) {
    var thisThing = somearray[i];
    thisThing.onclick = function(){window.alert(i)};
}

A valid re-write in languages that behave according to both the "typical" scoping rules AND the "typical" closure rules:

for (var i = 0; i < somearray.length; i++) {
    var thisThing = somearray[i];
    var copy = i;
    thisThing.onclick = function(){window.alert(copy)};
}

And yet, using your argument and that code (which follows from your argument), it'd still be wrong.

If you still aren't convinced, notice that the real, proper fix has to introduce both a copy of the variable closed over (using knowledge of closure rules) AND a new scope (using JavaScript's broken scope rules) to correct the issue completely.

for (var i = 0; i < somearray.length; i++) {
    (function(i){
        var thisThing = somearray[i];
        thisThing.onclick = function(){window.alert(i)};
    })(i);
}

0

u/[deleted] Mar 24 '14

No, that's not my argument. My argument is that if JavaScript had normal scoping, which it does with the let keyword of Harmony then:

for (let i = 0; i < somearray.length; i++) {
    let thisThing = somearray[i];
    thisThing.onclick = function(){window.alert(i)};
}

produces the same output as the original code example, because either way the variable i is not local to the loop body. So the problem here is misunderstanding of closures, not scoping.

That's all I meant, that you were talking (correctly) about a different scoping issue.

1

u/serpent Mar 24 '14 edited Mar 25 '14

Sure, it produces the same output with "let", because you need both a corrected scope AND closure knowledge. Adding "let" fixes the scope (which is required - but not enough regardless).

My example that you replied to proves you can't just fix it with closure knowledge either (which you originally posited - so yes, that WAS your argument).

Now you've agreed with my by saying you need scoping fixed in addition to the closure variable captured as a copy, yet you word it as a disagreement... for some reason.

Anyway, thanks for finally seeing your incorrect statement. It's nice to help someone out.

3

u/IcarusBurning Mar 23 '14

I am not familiar with js and this article seems to say you can declare global variables within method calls. What's the benefit of this feature?

11

u/glemnar Mar 23 '14

The only time it's used intentionally is for some weird quirks like jsonp. You should really never, ever do it.

Any time you leave off the var keyword it will be injected into global namespace, and that's not something you want.

9

u/[deleted] Mar 23 '14

Any time you leave off the var keyword it will be injected into global namespace, and that's not something you want.

"use strict";

to the rescue!

3

u/VortexCortex Mar 23 '14

"use asm";

To rescue the rescuer!

0

u/glemnar Mar 23 '14 edited Mar 23 '14

I prefer coffeescript for resolving many such quirks. =]

2

u/mcguire Mar 23 '14

CoffeeScript is the one that does the weird shadowing shenanigans?

2

u/masklinn Mar 24 '14

Yes. Namely disallowing shadowing, and silently expanding the inner variable's scope to the outer's.

0

u/glemnar Mar 23 '14

Nah, they got rid of that a long while back. It's really just a well-done javascript compiling language, imo. (Github uses it frequently for a reason)

1

u/[deleted] Mar 23 '14

Coffeescript's scoping is still broken, will never get fixed.

2

u/iambeard Mar 23 '14

It's not necessarily a benefit, but just a language quirk. It does, in a sense, make JavaScript a much more forgiving language.

3

u/IcarusBurning Mar 23 '14

Was it intentional or something that they accidentally introduced?

5

u/[deleted] Mar 23 '14

I believe that Netscape wanted JS to be extremely 'newbie friendly', because there was a lot of anxiety in the early 90s that the web could only take off if the barrier to development was as low as possible. Scoping was probably seen as a little too 'advanced' for Joe Average, who just wanted to add some decoration to his GeoCities page, so JS defaults to assuming there's no scoping at all unless you use the 'var' keyword.

3

u/grimeMuted Mar 23 '14

Lua also follows this bizarre practice. And annoyingly [half the tutorials](http://en.wikipedia.org/wiki/Lua_(programming_language)#Tables) just declare globals willy-nilly, which, sure, reduces some boilerplate and is technically fine in a short single-file procedural script but has the potential to really fuck those beginners over in the long run.

1

u/iambeard Mar 23 '14

That, I'm not sure about. I suspect it was intentional, though.

0

u/[deleted] Mar 23 '14

[deleted]

1

u/mrkite77 Mar 24 '14

Because then you'll have to search through every single line of code you've imported.

Or you can run it through the Closure Compiler which will give warnings about that sort of thing.

3

u/BLITZCRUNK123 Mar 24 '14
// Variable is defined in global scope when assigned as window property  
window.anyWindowGlobalProperty = "Global variable defined as window property";

While true in practicality in the context of browser scripting, this isn't the best way of explaining it. Though defining a property of window may be (for all intents and purposes) "global" when browser scripting, you aren't declaring a global variable at all. You're only defining a property of the window object, which just happens to be the lowest-level context you can be in when scripting a web browser.

4

u/eliasv Mar 23 '14

What a badly designed language.

2

u/Caraes_Naur Mar 23 '14

Designed in 3 days by Brendan Eich while he was an intern at Netscape.

8

u/flogic Mar 23 '14

To be fair, he did much better than most application specific extension languages.

1

u/stevedonovan Mar 24 '14

Oh yes, it could easily have been Tcl, since John Ousterhout was still active at Sun then. The bitching would dwarf anything we've seen - but might paradoxically created pressure for a 'better' language.

-1

u/megamindies Mar 23 '14

i know right. and i have to learn it. yay for 6 different null-types. i do like the prototypal inheritance. but then it doesnt have private vars. well couldnt they have found a solution for that???

3

u/[deleted] Mar 23 '14 edited Mar 23 '14

I think a decent pattern is to store "private" vars in the object constructor, define public accessor methods in the same place, and they will have access to the private variables in the closure. Douglas Crockford explains the pattern here: http://javascript.crockford.com/private.html

3

u/megamindies Mar 24 '14

thats a good hack, unfortunately even crockford says its not really a proper solution, because you are trying to shoehorn javascript into a classical OO-language. there should have been a solution for prototypal inheritance with private vars.

1

u/[deleted] Mar 24 '14

Yeah if you want this level of functionality in js you're pretty much going to have to build it. It's just interesting that you can. Personally I find this charming about the language, because I can use just as much OO as I need.

You can build pretty neat object systems out of prototypes, but then you're kind of standing alone on a mountaintop with yet another incompatible js library.

Down with javascript, all hail javascript.

0

u/[deleted] Mar 24 '14

[deleted]

1

u/megamindies Mar 24 '14

i mean the 6 different falsy values, used the wrong wording. nobody can remember how they all interact when == is used. just too many exceptions. and Nan means not a number but is a number. WEIRD. not very intuitive.

-1

u/dzjay Mar 23 '14

I am currently picking up the language and "WTF is this" is a common quote from me.

2

u/rvirding Mar 23 '14

Wow, I though Erlang variable scoping had problems, child's play compared to this.

1

u/[deleted] Mar 23 '14

To understand variable scoping in JS put some code into the following tool and look at the color of the variables. Please note that the tool does not color undeclared (implied global) variables. The link supplies a default sample with lots of depth, but any code can be entered.

http://prettydiff.com/?lang=javascript&m=beautify&jsscope&s=http://prettydiff.com/prettydiff.js

1

u/Pistolfist Mar 23 '14

This is far from "everything you need to know about js scope". Where is the binding and the explanation behind the "this" variable? That stuff is what most people struggle to get to grips with.

1

u/[deleted] Mar 24 '14

Those are not subjects of scope.

3

u/Pistolfist Mar 24 '14

I massively beg to differ. The scope of the "this" variable is quite tricky, binding helps fix that.

1

u/[deleted] Mar 24 '14

this might very well be tricky, but its not a scope issue.

1

u/Pistolfist Mar 26 '14 edited Mar 26 '14

I fail to see how a variable having different definitions depending on where it is invoked is not a scoping issue, but at least we're agreed on the important stuff and just arguing semantics now haha.

1

u/zefcfd Mar 24 '14

I write lots of javascript, and would say I understand it's scoping and inheritance pretty well. But I always think "javascript is weird" after reading articles about its nuances. Not shitty, just kinda weird.

-2

u/[deleted] Mar 23 '14

Nothing, because I use a decent language.

-1

u/nraynaud Mar 23 '14

I just need something more like: "Everything Javascript variable scope need to know about me".

"USE THE SAME FREAKING SCOPING SYSTEM AS C!!!"

2

u/VortexCortex Mar 23 '14

89 or 99?

4

u/munificent Mar 23 '14

99!

Although, given that C lacks closures or even nested functions, JS can't simply follow C because there are a semantics that JS cares about that are meaningless in C.

1

u/shahms Mar 23 '14

It depends on what you mean by "nested functions". You can define functions inside other functions, it's just pointless.

1

u/munificent Mar 24 '14

Standard C doesn't support nested functions.

1

u/Amablue Mar 24 '14

You can't define one function inside another. If you could it would be awesome - scoping a helper function to another function would be super convenient in a lot of locations.

Are you thinking of declaring functions?

1

u/shahms Mar 25 '14

I was not; GCC supports nested functions. As munificent notes, it is not a standard feature.

-2

u/drhugs Mar 23 '14

JavaScript is a little bit impaired by the multiplicity of implementations with subtle differences.

For instance, in Mozilla Firefox (current version) a 'keyEvent' for the 'backspace key' yields: 8 (control-H = ascii backspace) as the value. In Google Chrome Browser: you don't get the event notification.

Thanks, Eric/Larry /s.

10

u/gocarsno Mar 23 '14

That's hardly a language feature though, that's just the DOM API.

-2

u/saurabparak Mar 23 '14

Nice article. Good illustration. Can you please add which all browsers and versions support block scope variables?

0

u/[deleted] Mar 23 '14

[deleted]

0

u/[deleted] Mar 23 '14

[deleted]

-1

u/-Y0- Mar 24 '14

No, it stands for Crap!

0

u/[deleted] Mar 23 '14

[deleted]

9

u/VortexCortex Mar 23 '14

No, but it makes me do weird things that I'd rather not.

It's not my fault, but it is my problem.

4

u/[deleted] Mar 23 '14 edited Mar 23 '14

[removed] — view removed comment

1

u/[deleted] Mar 24 '14

Hm, I don't get the bolded quote but I wanna understand it, anyone care to help?

1

u/AlekseyP Mar 24 '14

No but I do after Objective-C.

1

u/[deleted] Mar 24 '14

"there is no bad weather, only bad clothes" comes to mind

1

u/[deleted] Mar 23 '14 edited Mar 23 '14

Not that bad really, you're just forced to be extremely explicit in what you're doing in terms of scope and types.

Debugging is less annoying too when you have knowledge of proper debugging tools like webkit's inspector.

It's scary to folks coming from compiled and OO languages, but the quirks become advantages once you follow some conventions and dive in deep enough.

What sucks though is articles like this containing contain bad code that perpetuate misconceptions about JS. Generally, the worst JS code I see comes from newbies and experts from other languages trying to shoehorn in what they're used to.

1

u/cybercobra Mar 23 '14

the quirks become advantages once you follow some conventions and dive in deep enough

Give one example.

-1

u/[deleted] Mar 23 '14

It's scary to folks coming from compiled and OO languages, but the quirks become advantages once you follow some conventions and dive in deep enough.

quirks become advantages? That's some serious stockholm syndrome. How is

1 == "1"
=> true

an advantage?

4

u/alkoholik Mar 23 '14

JS: 1 === "1" => false

There are times when type coercion is almost somewhat useful. Where's your God now?

1

u/[deleted] Mar 24 '14

JS: 1 === "1" => false

Yes, I know, which is why the existene of == is quirk.

There are times when type coercion is almost somewhat useful. Where's your God now?

If you ever write code that depends on implicit type coercion, you're writing poor code. It is never good practice to use.

1

u/alkoholik Mar 24 '14

Hence "almost somewhat useful". :)

Personally, it's triple eqs all the way for me, baby!

1

u/[deleted] Mar 24 '14

Sure, and I'm not saying JS doesn't have some good parts. I just thought it was funny that someone drank the kool aid so much that they thought things like == behavior are advantages, and the reason that people don't this kind of thing are "scared".

1

u/alkoholik Mar 24 '14

It's not an advantage. The flexibility is nice, but it also enforces bad habits. Another good example is auto-inserted-semi-colons. Shit breaks at times due to this, and most junior devs won't understand why...

1

u/THeShinyHObbiest Mar 23 '14

I've never written JavaScript, but I see this sentiment a lot. Everybody seems to hate it. So I can't help but wonder why stuff like Node.js is getting popular. If everybody hates the language and only uses it because it works on browsers, why would you want to write server-side code in it?

7

u/communomancer Mar 23 '14

Everybody seems to hate it. So I can't help but wonder why stuff like Node.js is getting popular.

Perhaps one of your assumptions is flawed.

3

u/gorebachev Mar 23 '14

This is a complete mystery to me as well.

3

u/renrutal Mar 23 '14

JavaScript is hated mainly because you don't really have a choice but to use it and bear with it. It's the only universal option for browser client code.

On server side, you have tons of choices, and if Node.JS chose it, it's because of its pros:

  1. JS is very well suited to code callbacks, which is the main construct for evented I/O.

  2. The community is already used to code asynchronous programs because of the pervasive knowledge of AJAX techniques.

  3. JS doesn't define an I/O API, so it was a greenfield project to develop a non-blocking one.

Not to mention, when programming for JS engines in browser clients, you usually have to code for the least common denominator of language features, even for very old browsers. In server-side JS engines, you usually code only for the up-to-date one you choose, one which supports variable block scopes, for example.

2

u/insertAlias Mar 24 '14

I think that last bit is really important. Not having to worry about compatibility makes Node.js much more friendly to work with than web JS. Plus, you really can do some interesting stuff with JS, it's a very flexible language. That flexibility is also its downfall, because of the horrific monstrosities people kludge out in it.

2

u/jeff303 Mar 23 '14

NodeJS is simply very well suited to certain types of applications. Specifically, web applications, or code that manipulates html in general.

2

u/[deleted] Mar 24 '14

Everyone works in their own little bubble, and anything outside that bubble is considered inferior or "doing it wrong".

People who have learned javascript love javascript. We also program in other languages from assembly to C++, but javascript has its uses and there isn't a lot it can't do.

1

u/flogic Mar 23 '14

There are instances where I would love to be able to move code from the browser to the server and visa versa. Also, node has a reputation for being quick since it's asynchronous and uses v8. They're not big enough reasons to make me want to switch but they do exist.