Ask HN: How do I learn JavaScript?

223 points by qwerty456127 ↗ HN
I feel like I would like to learn modern JavaScript (as supported by the most recent version of V8) from the very basic to the perfect and complete level (which makes the whole point of the question, ways to mediocre proficiency are countless and obvious).

I believe this is possible (and maybe not even hard) as I only mean the language itself - no browser APIs, no frameworks/libraries/tooling, no patterns and practices beyond those necessary to understand the features and the quirks of the language itself, what they can be used for and how to deal with them correctly.

Where do I go and how hard is this actually going to be?

127 comments

[ 4.3 ms ] story [ 319 ms ] thread
My favourite resource that I discovered a few years ago in a similar Ask HN thread: http://eloquentjavascript.net

> Where do I go?

You don't really need to go anywhere else (especially not into the vortex of looking for the best resource) to learn and be confident with vanilla javascript.

> ... and how hard is this actually going to be?

Well that depends more on you and your preference for learning materials. I studied a chapter a day (like 3 hours concentrated per day) and was done in 3 weeks.

Thank you, that looks pretty cool and easy to breeze through.
Eloquent Javascript is indeed a good and quick read!
It depends on how much programming you already know.

If you don’t know any programming, it’s a bad idea to start by JavaScript. Its design has followed a path from a hackish webpage scripting language to being used server-side, so a lot has evolved and a lot of crap remains from the old days. If you don’t know programming, you’ll have a hard time discerning the newer, cleaner features from the older less polished ones.

In my opinion it’s easier to learn java or C or Kotlin, which are a lot neater. And then learn about how JavaScript differs.

i think i haven't understand javascript till i have read "JavaScript: The Good Parts"

now that book is old and es6 changed a lot of things, so find a good book read it and if it has examples go thru them. only with examples was i able to understand scope inheritence and asynchronous calls in javascipt. like if you call settimeout in loop and all other gotchas.

It is not clear, if you want to learn programming, or you alerady know it, and want to learn a new language.

It takes years to become good at programming. Once you know programming, it usually takes hours to learn a new (procedural) programming language.

> it usually takes hours to learn a new (procedural) programming language.

Really? I feel like I’ve spent longer than that just trying to get my head around JavaScript’s prototypal inheritance. I’m even more confused by Promises.

Prototypical inheritance is not something I really understand in too much detail (and maybe I was late to the game, since I've never really felt I missed anything). Now js has 'classes' which I think are sugar over proto, can't remember.

You can think of a prototype as 'cloning' an object (but not quite), distinct from classes in OOP, which are typically created afresh, i.e. no entanglement occurs between instance 1 and 2 of the same class (unless of course explicitly specified in a constructor). If I have `var a = {one: 1, two: 2}`, I can use that as a 'live template' to stamp out other 'instances' that prototypically inherit from that ancestor. Any attribute lookups that are not specified directly on an object created with a prototype recursively look up the prototype ancestry chain until it is found. So if c -> b -> a (where a -> b means a prototypically inherits from b), looking up a property on c will try to look for the property on c first, failing that b, then a. If nothing is found, `undefined` is returned.

Let's open our inspector and have a play: ``` var a = {one: 1, two: 2}; var b = Object.create(a); // create b, based on prototype a var c = Object.create(b);

console.log(c.one) // 1, how, when this wasn't even defined! We looked up the p. chain until we found it

b.three = 3;

console.log(a.three) // undefined, a's only prototype is Object console.log(c.three) // 3, wow, c knew about something that happened to b! This is different from OOP. 'instances' share data defined at runtime.

```

And now for promises.

Why promises? Before promises, js code often used an error first callback strategy to communicate when an asynchronous process has finished. It's important to write blocking code as little as possible, since your computer can and should spend time doing 'compute' stuff, whilst waiting for a resource, such as a network request or disk etc.. which can take an unbounded amount of time.

Back to how callbacks look: ``` function myExpensiveSuccessfulFn(cbFn) { setTimeout(() => { cbFn(null, 'success'); // pretend we did something useful }, 60 * 1000) // time waste for a minute }

function myExpensiveFailingFn(cbFn) { setTimeout(() => { cbFn('oh no'); // pretend we tried to do something useful }, 60 * 1000) // time waste for a minute }

function myCallback(err, data) { console.log(`err: ${err}`); console.log(`data: ${data}`); }

myExpensiveSuccessfulFn(myCallback); // after 1 minute: err: null, data: 'success'

myExpensiveFailingFn(myCallback); // after 1 minute: err: 'oh no', data: undefined ```

Awesome. We can wait for some result and be notified whenever it finishes. Have a play in your inspector as before. Immediately after calling our expensive functions, we can execute code straightaway (try logging anything immediately after calling an expensive function)

Now callbacks start to get unwieldy when those same callbacks also want to do things that require something else asynchronously. There are better examples online, but I'll write something with anonymous functions to give you an idea:

``` function addSomethingSoon(a, b, cbFn) { // in 5 seconds, return the sum of two numbers setTimeout(() => { cbFn(a + b)// no err first style in this example }, 5 * 1000); }

// now let's get the sum of four numbers:

addSomethingSoon(1, 2, (result1) => { addSomethingSoon(result1, 3, (result2) => { addSomethingSoon(result2, 4, (finalResult) => { console.log(`1+2+3+4=${finalResult}`); }); }); }); ```

Only 3 operations, and things are getting quite ugly. Contrived, but let's see how we can do better.

Enter the promise. A promise is a 'promise' of a future result. It's like if you went to a fast food restaurant, made an order and got a ticket in return. Once you are given a ticket, they'll call out your number and give you your food, since you are holding the ticket (the promise of food in the future).

Let's have a play:

``` function getFoodIn5(menuItem) { // don't worry about the syntax here. You'll likely not be creating promises with 'new' often. You'll likely get given them from a library, say a http call or similar. return new Promise((onComplete) => { setTimeout(() => { onComplete(`fresh ${menuItem}`); }, 5 * 1000) }); }

const promiseOfFood = getFoodIn5('burger'); console.log(promiseOfFood) // depends on your browser, nothing very useful, and definitely NOT our burger....

promiseOfFood.then((food) => { console.log(food); // fresh burger, yes, it tastes so good! }); ```

So we got our burger, pretty fast too. Unfortunately they just hired a few trainees:

``` function burntFoodIn5(menuItem) { // don't worry about the syntax here. You'll likely not be creating promises with 'new' often. You'll likely get given them from a library, say a http call or similar. return new Promise((onComplete, onError) => { setTimeout(() => { onError(`burnt ${menuItem}`); }, 5 * 1000) }); }

const promiseOfFood = burntFoodIn5('burger'); console.log(promiseOfFood);

promiseOfFood.then((food) => { console.log(food); // ... :( nothing }).catch((mistake) => { console.log(mistake) // burnt burger, you don't want to eat this. }); ```

that is promises in a nutshell...

To me, the nice part of JS is that you can get pretty far without knowing the language intricately. So you can actually get started and be somewhat productive while picking up more knowledge along the way. The front-end ecosystem is so broad that it's hard to focus only on vanilla JS anyway.

That said, if you want a comprehensive read about Javascript, there's You don't know JS: https://github.com/getify/You-Dont-Know-JS

Aside from "this", all failure modes in Javascript are pretty obvious to google and figure out (unlike a segfault in C++), so I'd suggest just diving in and implementing something in it, if you already have programming experience.

However, just being able to do something in a language and being able to do it the most correct and future-proof way is different, and in JS, "best practices" seem to be constantly evolving with language and community. Every library and framework seem to be doing things in a slightly different way, and there's a lot of freedom to experiment with different coding styles and programming paradigms (unlike in a language like Go). Personally, I would suggest Typescript for professional projects, but there are plenty of very knowledgegble and competent people with a lot of different opinions on it. If you're the kind of person who likes this kind of environment, you'll fall in love with JS ecosystem.

Assuming you’re fluent in programming and languages in general.

I just went to the console and tried all things that should and should not have work. There you’ll learn about the specifics of prototyping, properties, operators, everything, and get insights for what’s going on under the hood. Didn’t find these details anywhere else. All sources of information are situational, down-to-earth utilitarian and resemble grandma’s cooking recipes, while what you seem to want is precise chemistry. (ed: another problem with js is that most books on it are out of date by design, e.g. one of the suggested links around says that prototypes can only hold methods and not values; what else is wrong there?)

>no browser APIs

A big part of js internals lies in the Object namespace. See also Symbol. (MDN for both)

I liked "JavaScript for impatient programmers" (https://exploringjs.com/impatient-js/) which is a relatively short but reasonably comprehensive explanation of modern JavaScript. In particular, it accurately describes a lot of important details (like how integer keys in objects work, "holes" in arrays, etc).

It doesn't cover the complete language, in particular it doesn't cover all outdated concepts and backward-compatible features. To get a complete understanding you would have to read the JavaScript specifications, but I don't think it makes sense to start there without having a solid understanding of the basic concepts first.

To piggy back onto this thread: I've written a fair amount of severside JavaScript, read the Eloquent JS book, the You Don't Know JS series (which I heartily recommend to the parent), and feel I have a pretty good handle on the modern language itself.

How does one take this knowledge and learn the browser APIs (in particular, best practices around those APIs) plus to navigate the frontend ecosystem in general without getting overwhelmed? Obviously you learn the APIs by building stuff, which I do. I can and do write frontend code, but always with the feeling that I've never learned this stuff properly.

I know there are tutorials aplenty on this stuff -- other than MDN, is there anything authoritative, comprehensive, and deep? Like, the SICP or TAOP of frontend programming?

is there anything authoritative, comprehensive, and deep?

I would recommend the official spec. It won't be an easy read, unless you're already used to reading standardese, but there's nothing more authoritative than that.

Not a tutorial or authoritative resource of any kind, but remember you can always open your browser of choice (on the desktop), open the developer tools and start fiddling with the browser APIs interactively, on any page you like.
Read the You Don't Know JS series [0] - this tackles much of what people with mediocre proficiency overlook. To go beyond that you would probably want to dive deep in to the ECMAScript specs [1] to really master the language. I don't think it will be that hard, just a slog.

[0] - https://github.com/getify/You-Dont-Know-JS

[1] - https://www.ecma-international.org/publications/standards/Ec...

OP, this is the best answer to your question. Lots of other answers on this thread are either ignoring the part where you said you wanted to really master the language and recommending introductory JS materials, or, bizarrely, telling you to learn something else instead.

I don’t think you can master a language in one go. It’s not how most people’s brains work. I think you do it in stages. Get yourself a good introductory JS resource. The eloquent javascript book others posted looks good although I haven’t read it myself. Then read You Don’t Know JS. And then study the spec. Almost by definition the spec is the only thing that can give you a perfect and complete understanding the language. But don’t start there as a complete beginner is not its intended audience.

Be sure to apply what you learn from each book by working on projects. Don’t just read the books. The material won’t stick that way.

Reading the spec will convey many useful details. If you truly want to master them, though, implement the spec and pass the conformance suite.

If Fabrice Bellard can do it, in C, with no dependencies, you can do it in whatever language you're already comfortable with, using the standard library. It's simply a matter of sustained effort and focus over time.

Yes I discovered so much unexpected combinations of features after implementing a Java parser. Totally pointless for actually writing Java though, so I question the motivation here. Just coz something is permitted in the language doesn't mean you should. I bet the corners of JavaScript are deep. Mastering them is a party trick, rather than something practical.
This is a good idea, but I'd be selective about it. There's a lot of tedious and uninteresting (IMO) stuff in there, like https://tc39.es/ecma262/#sec-array.prototype.splice or how unicode is handled in the source text.

But looking into the details of how object prototypes and properties really work is essential for getting a good grasp of the language.

wow, I've never heard of the first resource but it's amazing so far. There should be a directory for these types of resources (I'm thinking of Why's Poignant Guide for Ruby, which also helped me a lot in the past.)
Is there something like You Dont Know but for python? Im a sys eng thats been thrust into Python, I really enjoy the language but Im missing fundamentals
Fluent Python by Luciano Ramalho is very good.
It has great GR reviews, thanks for the rec
Agreed, the You Don't Know JS series is very good for solid fundamentals.

At some point, that knowledge can then be applied by learning more advanced language features such as implementing Proxies, Generators, and template literal functions.

To do so, some here are suggesting you read the language spec. I think Rau schmaer's series "Exploring ES6" [0] (and then ES7/8/9) is a great alternative to the actual spec. In those books he basically goes through the new features of each version of the language and does the deepest dive I've seen, with examples and references to the spec.

[0] - https://exploringjs.com/es6.html

After about a year of building a few larger web apps to get my base working knowledge down I am competent and can build and understand most things. I started reading YDKJS earlier this month and I think it has been the single biggest knowledge accelerator for me. Really understanding core principles has illuminated so many gotchas I ran into over the course of the previous year.

I do believe you need to have worked in JS for a while before jumping into YDKJS though. Having hit some of the idiosyncrasies of the language in the real world makes the book a much richer learning experience.

I’ve read this series twice whilst learning Javascript, once towards the start and again more recently. As others are saying, the lessons had a much greater impact after having some proper experience with the language.

The author, Kyle Simpson, has some really good video courses available online as well. He goes further in depth about some of the more interesting topics in YDKJS and is really able to sell some of his patterns.

Again, Kyle’s material was better digested after some practical experience with the language.

Find whatever works for you to reach "mediocre proficiency" then use that to improve until you reach "perfect and complete level". You won't find any resource for any language that will hold your hand all the way, if only because the concept of "perfect and complete" is rather fuzzy and subjective (and probably a moving target for a language like JS that's still in active development).

JS is a rather forgiving language (maybe too forgiving) that's very suitable for learning by trial and error. Get the basics, start hacking, find what works and what doesn't, look at other people's code to draw inspiration etc...

A little side note; You could consider ClojureScript.

I've worked with JavaScript many times through the years, and never felt that I got close to becoming an expert no matter what. The language it self is in the way. Browser compatibility, language weirdness (like the =, == or === mess) and there are a lot of standards around. But now a days working with ClojureScript, which settles the language problems, I get to focus on getting good at libraries, react and browser-stuff.

I hope I never have to work with vanilla JavaScript again, but since ClojureScript is a niche I'm pretty sure this dream will burst at some point. But I can attest ClojureScript has brought significantly more enjoyment into my life when dealing with front-end development.

I would second this, CLojureScript is the first language that has made front end seem sane to me.

Unfortunately your chances of getting a job doing ClojureScript is probably slim to none :(

There was a time when you couldn't get a job with Linux, and you couldn't convince a company to try Linux. So you snuck it in, and in some cases the company never knew (partly because it was so much more reliable than other options that it didn't crash nor reboot).

Sneak ClojureScript in. I know of one shop that trained its JavaScript engineers to use ClojureScript in two weeks. Quite frankly, if one is smart enough to write actual good, safe JavaScript, then one can definitely grok ClojureScript.

I'm a bit tempted to do something like this.

We have an old creaky app which I'm tempted to rewrite in ClojureScript in my own time and then show them it.

Worst case scenario they say it's great, now can we please rewrite it in JS. Best case scenario I get something in Clojure / CLJS into our system.

Either way I'd probably learn a lot just from the project. And I kinda need a new side project at the minute.

I would go for it. As you say, it will be a valuable learning experience. And writing anything the second time (even if switching languages) tends to be much easier than the first time since the problem is more known. So you lose not much time if you ultimately throw ClojureScript away in favor of something else.
> So you snuck it in

Linux did not win the server space because admins snuck it in. It won because it was free and worked well enough compared to signing up for tens of thousands of dollars worth of lengthy contracts with SCO/HP/IBM or even Microsoft.

> Sneak ClojureScript in

I don't see this ending well.

It's great to do your side projects in your favorite language but foisting it onto your employer so they they are forced to use it is a pretty bad violation of trust.

What happens if you quit and ClojureScript programmers are hard to find at the price the employer can afford without going out of business?

I would never try and pull this off.

Linux won because it got proven to be effective before any money had to be spent. The risk of trying it out was very low. And it ran well on old or low spec hardware, which Windows did not run (well) on. So we snuck Linux in by installing it on old puny PCs, setup some useful network services, and let it do its job well for months. Then we would casually mention to management what we did.

Many companies would not or because of SLAs _could not_ use free Linux. They would pay RedHat or Suse fees that included support/maintenance. Yes, it was still usually cheaper than Window licenses, but the price was not really the point.

Now about sneaking languages, platforms, and stacks in... Java was once too risky and unknown to be used in place of C/C++, but we snuck that in and proved it was up to task. Python... hah, Python was a toy "scripting language". No self-respecting CIO would approve of building company products in Python. Ruby? Rails? Surely not, those were also free, unknown, unproven technologies (which ironically were trying to supplant Java-based systems... that same Java which was once too risky).

PosgreSQL or MySQL? No way, that's not reliable for production. Of course it is, and it got snuck into companies whose engineers despised Oracle and SQL Server (not because MSSQL sucked, but because it only ran on Windows).

You can pick any modern best of breed tool, and I can point in history when that tool had to be snuck in to prove itself and gain acceptance.

> You can pick any modern best of breed tool, and I can point in history when that tool had to be snuck in to prove itself and gain acceptance.

I don't like the idea of "snuck in".

Working with management and having buy in that there's going to be a risk involved in taking something up that's new and unknown is OK.

That way we have a plan and action in place if things go other than expected.

That is exactly why I left a BIG5 firm and now work at startups because I can run these by the CEO and have a discussion.

The place where I work does not exist for my amusement.

Many people's livelihood including those of close friends and their families depend on the decisions I make.

If I am at a VC funded startup I am playing with the retirement of millions of people.

I owe it to them to be in the know of any risky decisions I take that I judge to be risky enough to affect them negatively.

Anything that's new and relatively unknown is risky.

That does not mean we don't try it.

It does mean we need to have a plan and action in place if things go other than expected.

Thats just good engineering and business because people depend on me.

Otherwise it's just a hobby and pastime.

I feel the same. I do full-time ClojureScript - at least a few jobs exist! If you would like a job doing ClojureScript, email me at the address in my bio.
Where's your bio?

My email is my handle at gmail.com

No obligation. I just want to connect with an individual interested in a "non-traditional" language :)

Why not Elm or Reason then?
ClojureScript is Clojure. Which eventually keeps me in the JVM universe where I'm experienced and familiar with tools, libraries, devops and everything around the development environment.

So as a Java developer ClojureScript keeps me a little in a familiar realm instead of jumping to a whole new ecosystem where I have to pick up every new aspect in the tool chain, including the language.

But this is personal, and I have absolutely no experience in these other languages you mention and they may be awesome.

Unfortunately, when one is seeking to learn JavaScript, you will encounter all variations of:

+ Use Typescript (no, it's not the same as JS)

+ Use ClojureScript

+ Use Elm

+ Use Reason

+ Use ...

If you go back about five years, you'll find this pattern also exists, except all the things people were saying to use are dead. Dead like a forgotten Egyptian pharaoh - buried and never to be seen again.

Unfortunately, all the code bases written in these poor JS-likes are still alive and I and many other poor souls still have to maintain the dang things.

You know what's still alive? Javascript. You know what still basically works the same? Javascript. You know what codebases from five or seven years ago I don't mind maintaining as much? Javascript.

It really feels that with typescript it may be finally different. Deno, the new version of Node, will speak typescript natively; and the adoption and satisfaction rates for typescript are over the roof. Coffeescript or clojurescript don't even come close.
JavaScript is still alive not because it's worthy of being alive (compared to the four other languages you mentioned), but because it was first and became well entrenched. COBOL is still alive too...

ClojureScript and Reason are superior languages, period. They will live long happy lives, too.

something else will come along that's even more superior, and the tooling surrounding your once-superior codebases will bitrot as the community jumps onto the next passing ship and you're caught holding the bag.
Oddly enough, being a superior language isn't the same thing as being a language anyone actually wants to use. There's a reason Python and JS are some of the most popular languages in the world despite "superior languages" existing.

I suspect that most of the ones I name will join the bone pile of the many other "superior languages" or continue to be used at most by a niche few.

I get your point. However I recently encountered 5 year old javascript and it was horrible. Full out jQuery and the (function(export){})(arg) pattern. And lots of dead test in some some long gone test library. But your point is valid if it were CoffeeScript and jQuery. That would be even worse for sure.

There is no relief in sight and it'll suck for a long time because everything is very fluid everywhere. Legacy will suck.

But if you want to be as productive and confident as you can these days; my take it is to not engange in vanilla JavaScript.

Don’t do this. Zero jobs. Might as well learn Elm
Where don’t you go! There are tonnes of course on udemy, pluralsight and similar and often they are free (because they want you to pay for the React / hot tech du jour course), so find one that suits you.

Pure JS will be a bit boring. You’d want to learn some Node apis to do something useful. But you could limit it to file I/o if it’s the JS you want to focus on. At least that’ll give you some async experience which I’m sure you’d be keen to learn.

I would recommend Javascript The Weird Parts. Good pacing and clear exploration of the languages ‘quirks’ and a general tour of vanilla js. Then you can dive into how your own framework can be created, also interesting for obvious reasons.

This course really pushed my js knowledge forward!

https://www.udemy.com/course/understand-javascript/

If you want a "perfect" understanding of ecmascript as it is implemented by V8 why not study the open source code for V8: https://v8.dev/. How hard will it be? Well how good are you at reading code/ how much do you know about c++? If this seems too daunting, better stick with a less than perfect guide to get you part of the way there.
> how much do you know about c++

"If you think you understand quantum mechanics, you don't understand quantum mechanics." - the same is true for C++ which is one of a few languages impossible to learn to the perfect and complete level.

An unorthodox approach would be to write a transpiler for JS.

I don't mean babel. I mean from scratch. Using whatever language you're comfortable with, turn lists of expressions into JS code.

https://github.com/sctb/lumen does this in just a couple thousand lines.