
A Reintroduction to JavaScript - psibi
https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript
======
cellover
I am currently in the process of re-learning JavaScript from scratch. And I
found the light:

1\. Douglas Crockford videos:
[http://www.yuiblog.com/crockford/](http://www.yuiblog.com/crockford/)

2\. Eloquent JavaScript intermediate level tutorials:
[http://eloquentjavascript.net/contents.html](http://eloquentjavascript.net/contents.html)

~~~
acjohnson55
If you truly want to master the language, Reg Braithwaite's stuff is
incredible. I think Javascript Allongé is one of the best programming books
I've read on any topic, and it's free online: [http://leanpub.com/javascript-
allonge](http://leanpub.com/javascript-allonge).

~~~
cellover
Excellent resource, thank you very much for posting!

------
henryw
The "even nicer [array for loop] idiom" is pretty cool:

    
    
      for (var key = 0, value; value = someArray[key++];) {
        // value is already defined by for loop
        console.log('index: ' + key, 'value: ' + value);
      }
    

Also, I finally understand closures:

"Whenever JavaScript executes a function, a 'scope' object is created to hold
the local variables created within that function. It is initialised with any
variables passed in as function parameters. This is similar to the global
object that all global variables and functions live in, but with a couple of
important differences: firstly, a brand new scope object is created every time
a function starts executing, and secondly, unlike the global object (which in
browsers is accessible as window) these scope objects cannot be directly
accessed from your JavaScript code... A closure is the combination of a
function and the scope object in which it was created."

~~~
Stratoscope
That was a great way to iterate over a non-sparse array such as an array of
objects... Back in 2006 when this article was written.

In fact, this was an even better way to write that loop in 2006:

    
    
      for( var value, i = -1;  value = array[++i]; ) {
        console.log( 'index: ' + i, 'value: ' + value );
      }
    

Basically the same thing except for the pre-increment instead of
postincrement. In some of the browsers of that day (at least IE), preincrement
was faster. And this version gives you the correct array index inside the
loop, unlike the off-by-one in the other version.

I was so proud of myself when I discovered this alternative that I wrote a
recipe for the jQuery Cookbook recommending it as the fastest way to iterate
over a typical array of objects such as you might receive from a JSON request.

It also used to be a great idea to optimize your machine code programs by
looking up the CPU cycles for each instruction. Fewer cycles = faster code.

Of course, that doesn't work any more, what with pipelining and out-of-order
execution.

Alas, these nifty JavaScript loops are not the fastest any more either. Fewer
operations != faster code.

The optimization guy for V8 explained this to me at Google I/O 2012. He said
that V8 can optimize the heck out of references into an array where all the
types are the same (either primitive values, or objects that all have the same
properties). But if you ever try to reference outside the bounds of the array,
it throws the whole thing back into deoptimized code.

And that is the problem. These nifty loops rely on reading the nonexistent
element just past the end of the array. That's their termination condition.

It turns out that with modern optimizing compilers, the plain old traditional
JavaScript loop is faster across the board:

    
    
      for( var i = 0, n = array.length;  i < n;  ++i ) {
        var value = array[i];
        console.log( 'index: ' + i, 'value: ' + value );
      }
    

(There is still a minor benefit to using preincrement instead of the more
traditional postincrement in some modern browsers.)

I put together a JSPerf for this a while ago:

[http://jsperf.com/mikes-loops/2](http://jsperf.com/mikes-loops/2)

I was quite embarrassed to learn how poorly my clever loop works in modern
browsers!

~~~
pixl97
>I was quite embarrassed to learn how poorly my clever loop works in modern
browsers!

What's really embarrassing is IE js performance.

Since I keep an ancient copy of of Netscape 9.0.0.6 on my computer I decided
to try it so see how much browsers have improved. It doesn't seem to upload
results I'll post them here in the same order as the testing page.

17.25 16.72 5.94 8.81 18.90 23.28 20.92 23.58

This is on the same computer that was pulling 5000+ on the fastest tests.
Browsers have come a long way.

------
welder
The example of JavaScript's prototype here is the best I've ever seen! It's in
the "Custom Objects" section.

~~~
exodust
Yeah it's good. The whole thing is nicely presented with great examples.
Bookmarked.

------
babuskov
Since I started using JS heavily lately, it's nice to be reminded of some
things. Thanks for posting.

One question though, it says:

    
    
        If you want to append an item to an array, the safest way to do it is like this:
        a[a.length] = item;  // same as a.push(item);
    

a.push() variant seems more elegant to me. Why is a[] variant "safer"?

~~~
bpierre
It must be for the compatibility, Array.prototype.push() has been added to IE
5.5:

[https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Refe...](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objects/Array/push#Browser_compatibility)

~~~
cstuder
Thirteen years ago... I would argue that you could use a.push() safely now.

So, why should a[a.length] be safer?

~~~
coldtea
He said it already, JUST for the compatibility. No other reason compared to
push nowadays.

------
aaronetz
Off-topic, but I must say that this site handles resizing very well. I really
appreciate it when a website seamlessly transitions from desktop-size to
mobile-size layout. Sometimes I just like having my browser window shrunk down
(or zoomed in for viewing from farther away), which means that with most sites
I have to scroll horizontally, which is not very usable.

------
ritchiea
It is probably a good idea to add 2006 to the title since that's the date of
the last update [1].

1\. [https://developer.mozilla.org/en-
US/docs/Web/JavaScript/A_re...](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/A_re-
introduction_to_JavaScript#Original_Document_Information)

~~~
frik
It's a wiki, see the page's history: [https://developer.mozilla.org/en-
US/docs/Web/JavaScript/A_re...](https://developer.mozilla.org/en-
US/docs/Web/JavaScript/A_re-introduction_to_JavaScript$history)

Maybe remove the "2006" from the headline (again).

~~~
psibi
Not able to edit the headline now.

------
inglor
Some mistakes there, will fix. `null` is most certainly not an object.

~~~
notjosh
I got this in an interview once as a curveball. It's most certainly an object
in Javascript!

    
    
      > typeof null
      "object"
    

Contrast that with:

    
    
      > typeof undefined
      "undefined"
    

Go figure :)

~~~
saurik
typeof null returns "object", but I do not believe it is correct to claim that
null "is an object". It is my understanding (maybe a misunderstanding, I will
happily state) from reading a ton of comments from Brendan Eich in various
places that typeof null is "object" for historical reasons involving the way
reference types were implemented in the original JavaScript VM.

~~~
raganwald
It is correct to say that typeof(null) returns the string 'object' because of
a bug that is now written into the standard to prevent old software from
"breaking" if they fixed this.

It is not ever correct to say that null in JavaScript is an object. Just ask
javaScript itself:

    
    
        Object.getPrototypeOf(null)
          //=> TypeError: Object.getPrototypeOf called on non-object

------
jokoon
still a better introduction to javascript:

[https://www.destroyallsoftware.com/talks/wat](https://www.destroyallsoftware.com/talks/wat)

(with a little bit of ruby)

~~~
chewxy
No. It's not a good introduction to JS. JS is very WTF worthy (I should know,
I'm writing a book on how to write asshole Javascript), but the WAT talk is
NOT a good intro

~~~
badman_ting
Agreed, it's a collection of trivia. Very WTF-worthy trivia but if your code
is doing basically any of the things listed in that talk, something has gone
terribly awry.

------
almog
"We've introduced another keyword: 'new'. new is strongly related to 'this'.
What it does is it creates a brand new empty object, and then calls the
function specified, with 'this' set to that new object"

Perhaps it would be worth to mention that 'new' not only sets 'this' to be the
empty object but also return that object to the location where new was used.

------
brofser
I've read this article a couple of times in the last few years and it never
ceases to amaze me. Clearly and in a concise way it lists all the points that
people usually miss about JS.

------
shultays
"if you're used to math in C or Java. Watch out for stuff like: 0.1 + 0.2 ==
0.30000000000000004"

Uh, how floating poing operators are different than this in C or java

------
mr-ron
One of my favorite tutorials from John Resig:
[http://ejohn.org/apps/learn/](http://ejohn.org/apps/learn/)

------
andrethegiant
I didn't know about the memory leak stuff! Any tools out there to help
identify this in your code?

~~~
lhorie
There's Dynatrace, IESieve and Drip (the latter two's websites are now defuct
though), but IIRC, the IE team fixed the memory leak issue via a service pack
or hotfix a few years ago.

------
shaboon
if that's was it's first name it should be renamed back to LiveScript

~~~
shaboon
"It was originally going to be called LiveScript, but was renamed in an ill-
fated marketing decision to try to capitalize on the popularity of Sun
Microsystem's Java language "

------
tunnuz
Old but gold.

------
CmonDev
If you wanted to find a friend for someone would you keep trying to introduce
them to same stupid ugly person, while saying: "Look! He/she is wearing make-
up this time!".

~~~
kajecounterhack
This isn't a productive comment.

Whether you like it or not js is here to stay. It's the language of the web
(and more). A lot of new capabilities are being exposed via browser makers
(e.g peerconnection, webrtc) which only serve to increase its power. Calling
it stupid and ugly is your unsubstantiated opinion. (Infinitely more useful:
say why this is your opinion.)

I think this is a nice intro to the language. Why it's being posted now though
is a little puzzling considering it's from 2006. It is obviously still
relevant and interesting but readers should realize it's not very recent.

~~~
lobotryas
I've never gone very deep with JS. Anything you could recommend, off the top
of your head, for a more recent look at the language?

~~~
aye
JavaScript Spessore, by Reginald Braithwaite:

[https://leanpub.com/javascript-spessore](https://leanpub.com/javascript-
spessore)

~~~
raganwald
Thank you, although please note that "JavaScript Spessore" is (a) a work-in-
progress, and (b) about "Thinking in objects" more than "The idiomatic way to
program in JavaScript.

