Is there a set of things that every JavaScript programmer should know to be able to say "I know JavaScript"?
29 Answers
Not jQuery. Not YUI. Not (etc. etc.)
Frameworks may be useful, but they are often hiding the sometimes-ugly details of how JavaScript and the DOM actually work from you. If your aim is to be able to say “I know JavaScript”, then investing a lot of time in a framework is opposed to that.
Here are some JavaScript language features that you should know to grok what it's doing and not get caught out, but which aren't immediately obvious to many people:
That
object.prop
andobject['prop']
are the same thing (so can you please stop usingeval
, thanks); that object properties are always strings (even for arrays); whatfor
...in
is for (and what it isn't).Property-sniffing; what
undefined
is (and why it smells); why the seemingly-little-knownin
operator is beneficial and different fromtypeof
/undefined
checks;hasOwnProperty
; the purpose ofdelete
.That the
Number
datatype is really a float; the language-independent difficulties of using floats; avoiding theparseInt
octal trap.Nested function scoping; the necessity of using
var
in the scope you want to avoid accidental globals; how scopes can be used for closures; the closure loop problem.How global variables and
window
properties collide; how global variables and document elements shouldn't collide but do in IE; the necessity of usingvar
in global scope too to avoid this.How the
function
statement acts to ‘hoist’ a definition before code preceding it; the difference between function statements and function expressions; why named function expressions should not be used.How constructor functions, the
prototype
property and thenew
operator really work; methods of exploiting this to create the normal class/subclass/instance system you actually wanted; when you might want to use closure-based objects instead of prototyping. (Most JS tutorial material is absolutely terrible on this; it took me years to get it straight in my head.)How
this
is determined at call-time, not bound; how consequently method-passing doesn't work like you expect from other languages; how closures orFunction#bind
may be used to get around that.Other ECMAScript Fifth Edition features like
indexOf
,forEach
and the functional-programming methods onArray
; how to fix up older browsers to ensure you can use them; using them with inline anonymous function expressions to get compact, readable code.The flow of control between the browser and user code; synchronous and asynchronous execution; events that fire inside the flow of control (eg. focus) vs. events and timeouts that occur when control returns; how calling a supposedly-synchronous builtin like
alert
can end up causing potentially-disastrous re-entrancy.How cross-window scripting affects
instanceof
; how cross-window scripting affects the control flow across different documents; howpostMessage
will hopefully fix this.
See this answer regarding the last two items.
Most of all, you should be viewing JavaScript critically, acknowledging that it is for historical reasons an imperfect language (even more than most languages), and avoiding its worst troublespots. Crockford's work on this front is definitely worth reading (although I don't 100% agree with him on which the “Good Parts” are).
-
6Thanks a lot for that well thought answer. I'd like to add that using a framework can be really beneficial if you know how it's being done. You should learn to do those things by yourself before resorting to a framework. Apr 13, 2010 at 14:14
-
2"
object.prop and object['prop']
are the same thing" not quite. If followed by()
they executeprop
as a function, but only the first one setsthis = object
soprop
can accessobject
. Apr 21, 2010 at 7:26 -
4@Daniel: actually not so,
this
is bound whichever way you access it. Try it:var o= {b: function(){alert(this===o);}};
, theno['b']();
->true
. And if you want really freaky,(o['b'])()
->true
, but(c= o['b'])()
->false
, and in Mozilla only,(true? o['b'] : null)()
->true
. W, T, and indeed, F.– bobinceApr 21, 2010 at 9:21 -
7What a crock! It's not as if knowing all the different browser quirks makes you a better JS coder. Maybe more street cred among your peers...Abstractions make life easier and are an essential part of JS so I would say knowing a framework makes you a better JS coder than one who doesn't and wants to do things the long way.– RazorApr 22, 2010 at 8:14
-
19Sir Psycho: note that none of this answer mentions the DOM, which is what the big libraries are there to help you with. A framework cannot protect you from any of the things mentioned here. This stuff is important for anyone doing browser scripting, using a framework or not.– Tim DownApr 27, 2010 at 15:40
That it can be disabled.
-
12+1, I'm so tired of pages that doesn't even bother with even the very basics of graceful degradation because "it's so hard and everyone has javascript enabled anyway".– wasatzApr 13, 2010 at 10:51
-
27+1. A page that doesn't work without JavaScript is a page that will be fragile even with JS enabled.– bobinceApr 13, 2010 at 11:25
-
9@iconiK I'll just go and tell all my Government clientelle who have JavaScript globally disabled for security reasons that they're all morons, shall I? Apr 13, 2010 at 14:54
-
16-1 this is off topic and doesn't really have anythong to do with knowing about javascript as a language. It's good thing to consider when designing a web app, but it's still not an answer that belongs in this thread.– TM.Apr 13, 2010 at 17:30
-
24@TM, no, it really is an important consideration. This should be in the forefront of your mind as you test values before inserting them into the database or have the only way to login to your website through a fancy javascript pop up box. Speaking of which.... I think I need to go check something. Apr 13, 2010 at 19:39
Understanding the stuff written in Crockford's Javascript: The Good Parts is a pretty good assumption that a person is a decent JS programmer.
You can pretty much know how to use a good library like JQuery and still not know the hidden parts of Javascript.
Another note is Debugging tools on various browsers. A JS programmer should know how to debug his code in different browsers.
Oh! And knowing JSLint will totally hurt your feelings!!
-
8There are also a lot of instructive and insightful Crockford videos at developer.yahoo.com/yui/theater - and I think I need not mention crockfordfacts.com :-)– ndimApr 13, 2010 at 11:14
-
+1 - JSLint is a wonderful thing when you try developing JS for a framework that has zero embedded debugging support (cough Siebel, cough PDFs). Aug 12, 2010 at 21:31
If you want to be a true JavaScript ninja, you should know the answers to every question in the Perfection kills JavaScript Quiz.
An example to whet your appetite:
(function f(f){
return typeof f();
})(function(){ return 1; });
What does this expression return?
- “number”
- “undefined”
- “function”
- Error
-
10
-
@CMS Very good! Did you actually get the all right first time, or does this include some research? Apr 13, 2010 at 15:09
-
7Skilldrick: I think I got them all at the first time, I'm a frequent reader of the ECMA-262 Standard (I know, I'm a freak :-) Apr 13, 2010 at 15:26
You don't know JavaScript if you don't know:
- Closures
- Prototype-based inheritance
- The module pattern
- The W3C-DOM
- How events work
-
I really like this answer. It helps you spot dark areas in your knowledge. Events are the only thing still a bit obscure to me in this checklist (if the module pattern means "don't clobber the global namespace" and so includes scopes and the var operator).– silviotApr 21, 2010 at 19:17
-
11I would argue that
You don't know JavaScript if you don't know The W3C-DOM
. The two things are different.– gblazexOct 24, 2010 at 14:19
..that javascript is not java :)
Many, many people starting with website development have told me javascript is just simple java!
-
71
-
1Javascript is about as similar to Java as C# is similar to C. Sure there syntax looks kinda similar, but way way different.– EarlzApr 13, 2010 at 17:28
-
4
-
Interestingly, Microsoft did base the Y2k compliant date functions in JScript for IE3 on java.util.Date. May 5, 2010 at 0:59
-
Familiarize yourself with atleast one Javascript library ( Jquery, Prototype, etc ).
Learn how to use the debugging tools of the major browsers ( MSIE 7-8, Firefox, Chrome, Safari )
Read up on the industry: Douglas Crockford's website is a treasure trove while Ajaxian.com is a good blog to keep up on new, interesting, and or odd ideas for Javascript. There are a number of other resources but those are the ones that helped me the most.
-
1@Murali VP I made the assumption for "knowning" Javascript in context of browsers. Right after some equivalent of hello world, you're going to need to figure out your logical and runtime errors, which can be different per interpreter. I wouldn't claim to know any language if I didn't know how to debug it. As for a framework requirement, Javascript is kind of like early C, where subtle implementation differences will sabotage the unwary; jQuery & prototypejs gloss over these differences and make Javascript a reliable tool while adding additional API calls to boost productivity. (cont)– DavidApr 13, 2010 at 17:16
-
@Murali VP To be fair, Javascript has come a long way since I started using it in the 90's and with the exception of Microsoft, the other Javascript interpreters have done impressive work to obey the specifications and play fair.– DavidApr 13, 2010 at 17:18
-
-
I downvoted simply because I don't feel the answers have anything to do with the JavaScript language itself. Although they are excellent advice. Apr 26, 2010 at 18:19
-
@ScottKoon Fair enough, I'm more of school of thought that it takes more then just mastery of a language but also the environment its going to be used it. Sure make, gcc, lint, and similar tools are not required to write a c/c++ program yet without having the prerequisite knowledge to work with the tools of a language then its difficult to master the language itself.– DavidMay 13, 2011 at 22:05
Javascript objects and function as first-class citizen, callbacks, not to forget about events and then JQuery.
-
20
That Javascript is not something which can be learnt in an hour!
-
4
Variables are global unless declared to be local!!
Bad (DoSomething() is only called 10 times):
function CountToTen()
{
for(i=0; i< 10; i++)
{
DoSomething(i);
}
}
function countToFive()
{
for(i=0; i<5; i++)
{
CountToTen();
}
}
CountToFive();
Good (DoSomething() is called 50 times as intended):
function CountToTen()
{
var i;
for(i=0; i< 10; i++)
{
DoSomething(i);
}
}
function countToFive()
{
var i;
for(i=0; i<5; i++)
{
CountToTen();
}
}
CountToFive();
-
6
-
2Crockford prefers putting the
var
at the top of the function, because it doesn't deceive you about the size of the variable's scope.js2-mode
will complain if youvar i
in two separatefor
loops in the same function, since it suggests you think you have two separate variables, and you don't. Nevertheless, I do try to nevervar
things separate from where I initialize them. Apr 23, 2010 at 23:56 -
I don't care if it's not scoped. I can't stand having a variable declared 20 lines before it's used Jan 12, 2012 at 7:37
-
+1 The best book to read on JavaScript; and also Flanagan's book Apr 26, 2010 at 11:11
For knowing that Javascript was originally called LiveScript and the 'Java' prefix was attached for marketing purposes not because Java and Javascript are related (which they are not).
Oh and for owning any version of David Flanagan's 'Javascript: The Definitive Guide' (this information is on page 2).
... and for appreciating those that have gone before in trying to obfuscate Internet Explorer 4's document.all[] and Netscape Navigator 4's document.layers[] before the likes of Jquery took away the pain.
EDIT:
As @Kinopiko points out JavaScript was called project Mocha originally (some sources also reckon it was called project LiveWire) but it is generally accepted that the language (written by Brendan Eich) was slated to be released as LiveScript before the Java prefix was adopted on release in early 1996.
-
-
1I thought JavaScript was originally called Mocha?– user181548Apr 13, 2010 at 10:44
-
1@Kinopiko According to my 'Javascript: The Definitive Guide' 3ed (June 1998) book by David Flanaghan it was called LiveScript.– amelvinApr 13, 2010 at 10:47
-
-
@Kinopiko Agreed that on wikipedia it says it was called Mocha, then LiveScript then JavaScript. But it was never released as Mocha (or LiveWire another of its project names) it was intended to be released as LiveScript - before the Java bandwagon lead to a last minute release change.– amelvinApr 13, 2010 at 11:05
One should be aware about the following to say "I Know JavaScript":
- JavaScript is good but DOM is pain point
- Cross browser issues can make you go crazy
- Unless code is tested on least 4 different good browsers you can't say its bug free
- Closure.............. Must know
- Its prototype based ........... Nice one its fun to learn this
- debugger keyword ..... Helps in crisis
-
Nice list, pretty slim. I got a laugh at "4" good browsers. :) I think number 7 should be a healthy hatred for IE browsers under version 8.– ShyamApr 13, 2010 at 21:43
-
@Shyam, what makes you think we shouldn't have a healthy hatred of IE8? I still have issues in IE8... issues that are only in IE8 at that.– Tracker1Apr 14, 2010 at 0:25
-
@Tracker1: There will be always issues. And bashing a browser I haven't touched, well, that would be a bit unfair. That's why I laughed at 4 good browsers: 'Firefox, Chrome, Safari and Opera' are the only ones I develop for. I stopped hacking for IE, I just make it run Fisher Price code, as if JavaScript would be disabled.– ShyamApr 14, 2010 at 9:51
That JavaScript is much more different than other languages than you might think. Watch this great Google Tech Talk to get an impression: http://www.youtube.com/watch?v=hQVTIJBZook
-
1+1 This is a great explanation of how to stop JavaScript sucking. These are worth watching afterwards: yuiblog.com/crockford Apr 13, 2010 at 10:24
-
Another good Crockfod presentation ("The JavaScript Programming Language" 4 parts) video.yahoo.com/watch/111593/1710507– Alex K.Apr 13, 2010 at 10:27
What every javascript coder should know?
How about, I can turn off your efforts with 2 clicks. So provide a fallback if possible.
-
You might as well uninstall your web browser. There are very few people who disable javascript these days. Those who do probably don't need to browse the web. The only exception to this is that web crawlers need to access your public content and do cannot rely on JS to do so. Jul 12, 2011 at 18:44
-
I am more interested in providing non-JS ways to access things. I know of people that browse with JS disabled, or use screen readers. They don't always play nice with JS. I have seen sites that a simple login page is submitted via ajax with no fallback at all. No JS, no login. The site doesn't even make use of much JS, just to submit forms. Jul 13, 2011 at 9:16
-
I believe that users who intentionally disable JS as you implied, are very uncommon today, certainly a lot less than 10 years ago. This is why I don't understand why we should design a site twice for people who just don't really want to visit your site anyway. So in your example, they can't login, so what? The other thing is that there is absolutely no way you can design a modern site without JS. Jul 13, 2011 at 16:57
You know javascript if you can use Array, Number, String, Date and Object effectively. Plus points for Math and RegExp. You should be able to write functions and use variables (in correct scope, i.e. as 'methods' of an object).
I see some comments about knowing closures, extravagant function syntax, blabla. All that is quite irrelevant for this question. That's like saying you are a runner if you can run the 100m dash under 11 seconds.
I say it takes maybe a couple of weeks to become proficient in javascript. After that it takes years and dozens of books and thousands of lines of programming to become an expert, a ninja, etc.
But that wasn't the question.
Oh, and the DOM is not a part of javascript, and neither is jQuery. So I think both are equally irrelevant to the question too.
-
1Closure is there whether you care for it or not. It's powerful but can easily be misused. You don't know the language if you don't know how it works.– gblazexOct 24, 2010 at 14:24
-
Apart from the harm closures can cause, like memory leaks, especially in our true friend Internet Explorer 6. Nov 3, 2010 at 18:46
Having read all the above, it's also perfectly fine to learn Javascript by using a framework like jQuery. The truth is it's the first way a lot of folks picked JS up in the first place. No shame in that.
array.length
method is not a count of array's items, but the highest index. even when the item was set to undefined
var a = [];
a.length; // === 0
a[10]; // === undefined
a[10] = undefined;
a.length; // === 11
a.pop(); // === undefined
a.length; // === 10
this behavior is hardly distinguishable from a language design bug..
jQuery would be my best recommendation. Not just for the code itself, it's the idiom, the style, the thinking behind it that's most worthy of emulation.
-
2
-
1Good argument outline. Expanding would make it a great answer. Apr 13, 2010 at 10:54
-
jQuery forces you into a procedural mode. I much rather write OO JS Jan 12, 2012 at 7:42
-
There's nothing magical about object-orientation. I'd rather use a framework designed by John Resig and used by thousands of other developers than anything you or I would write, regardless of mode.– duffymoJan 12, 2012 at 10:15
That javascript is the most widely deployed language in the world. (Probably)
-
8Most widely deployed native natural language is Mandarin. Would knowing that make you a Mandarin speaker? Would knowing that fact even have anything to do with your grasp of the language?– ZanoApr 14, 2010 at 7:55
-
11The most widely deployed language in the world is the genetic code of the DNA that controls the protein synthesis within the cells.– ErnelliMay 7, 2010 at 12:11
-
Before Mandarin and DNA, the language of Love must first be deployed: thus, it wins. BAM! Nov 22, 2011 at 2:38
Learning a language really well and understanding its various quirks comes from (years of) experience. If you want to be a better programmer, I would say, understanding design patterns, how and when to use them and/ or even when you are using them without realising it; technical architecture & user experience.
Knowing the (JavaScript) language means you can pick up any framework and use it at will. You'll inevitably need to dive into the source code, and if all you know is the syntax a framework or 2 or 3, then you won't go far. In saying that, getting into a few different frameworks' source code is probably one of the best ways to see how JavaScript can be used. Messing about by stepping through the code in Firebug or Web Inspector, then checking JavaScript Documentation, especially the Mozilla and Webkit docs, to get further understanding of what you're looking at.
Understanding the difference between Object-Oriented and Functional Programming, that JavaScript is a sexy mix of the two and when and how to use both to create a killer codebase and awesome applications will make you a better JavaScript Programmer.
Simply reading some books, especially Crockford's "good parts" which merely presents his opinions on what is good in JavaScript, while skipping most of the AWESOME parts of JavaScript is going to get you off on the wrong foot.
Checking out code written by someone like Thomas Fuchs on the other hand is going to give you much more insight into the power of writing amazing and efficient JavaScript.
Trying to memorise a few gotchas or WTFs is not going to help much either, you'll pick that up if you start coding and stepping through a library/ frameworks' code, especially a helpfully commented one, to see why they've used certain properties/ values and not others why and when it's good to use specific operands and operators, this is all there in the code of the framework's people use. How better than to learn by example? :^)
-
+1 for not worshipping Crockford. I treat his views like I do a preacher at church. I respect what they say but take it all with a grain of salt. Jan 12, 2012 at 7:47
In Javascript, Performance matters.
There is not an intelligent compiler to optimize your code so You should be more careful while you are writing javascript code than languages like C#, Java...
-
1
-
1Chrome is very smart at optimizing your code, this answer is just not true with all the new JS engines Jan 12, 2012 at 7:51
-
The following things are also important:
1) Variable hoisting. 2) Scope chains and activation objects.
and then things like these: :)
3) wtfjs.com
4) everything is an object http://www.lifeinafolder.com/images/Js.jpg
-
63.) is wrong. Not everything is an object. stackoverflow.com/questions/3907613/…– gblazexOct 24, 2010 at 14:22
- Knowing that there is a life with and without
with()
and where to draw the line. - You can create custom errors with the
throw
statement to purposely stop the javascript runtime.
Since JS is a functional language, a decent JS programmer must be able to write Y-combinator and explain how it works off the top of head.
-
1What's wrong with being able to write Y-combinator's ? And yes javascript is a functional language. If you want to say you "know javascript" good understanding of functional programming is neccesary.– RaynosOct 8, 2010 at 11:13
-
-
I've read up about the Y combinator recently, understand how it works and in which cases it could be used.. but never found an instance where I couldn't rewrite a problem to not need the Y combinator.– EvertJun 14, 2011 at 13:10
... about Google Web Toolkit, which means that your javascript project probably could be developed in a much more conveniant way.
-
2GWT is not really JavaScript, it is the Javaish way of writing JavaScript. Jan 10, 2011 at 13:29
-
-
that your javascript project probably could be developed in a much more conveniant way. Feb 8, 2011 at 14:47
-
6