Is there a set of things that every JavaScript programmer should know to be able to say "I know JavaScript"?
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
and object['prop']
are the same thing (so can you please stop using eval
, thanks); that object properties are always strings (even for arrays);
what
for
...
in
is for
[1] (and
what it isn't
[2]).
Property-sniffing; what undefined
is (and
why it smells
[3]); why the seemingly-little-known in
operator is beneficial and different from typeof
/undefined
checks; hasOwnProperty
; the purpose of delete
.
That the Number
datatype is really a float; the language-independent difficulties of using floats; avoiding the parseInt
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
[4].
How global variables and window
properties collide; how global variables and document elements shouldn't collide but do in IE; the necessity of using var
in global scope too to avoid this.
How the function
statement acts to ‘
hoist
[5]’ a definition before code preceding it; the difference between function statements and function expressions; why named function expressions
should not be used
[6].
How constructor functions, the prototype
property and the new
operator really work;
methods
[7] 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
[8] from other languages; how closures or Function#bind
may be used to get around that.
Other ECMAScript Fifth Edition features like indexOf
, forEach
and the functional-programming
methods on
Array
[9]; 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; how postMessage
will hopefully fix this.
See this answer [10] 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).
[1] http://bonsaiden.github.com/JavaScript-Garden/#object.forinloopThat it can be disabled.
Understanding the stuff written in Crockford's Javascript: The Good Parts [1] 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!!
[1] https://rads.stackoverflow.com/amzn/click/com/0596517742If you want to be a true JavaScript ninja, you should know the answers to every question in the Perfection kills JavaScript Quiz [1].
An example to whet your appetite:
(function f(f){
return typeof f();
})(function(){ return 1; });
[1] http://perfectionkills.com/javascript-quiz/What does this expression return?
- “number”
- “undefined”
- “function”
- Error
You don't know JavaScript if you don't know:
You don't know JavaScript if you don't know The W3C-DOM
. The two things are different. - gblazex
..that javascript is not java :)
Many, many people starting with website development have told me javascript is just simple java!
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.
Javascript objects and function as first-class citizen, callbacks, not to forget about events and then JQuery [1].
[1] http://jquery.com/That Javascript is not something which can be learnt in an hour!
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();
for (var i=0;
in all my loops - ghoppe
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 you var i
in two separate for
loops in the same function, since it suggests you think you have two separate variables, and you don't. Nevertheless, I do try to never var
things separate from where I initialize them. - Kragen Javier Sitaker
How to use the good parts, and how to avoid the awful parts [1].
[1] http://books.google.com/books?id=PXa2bby0oQ0C&printsec=frontcover&dq=javascript+good+parts&source=bl&ots=HHsim6s_lE&sig=7rtiJx1lseFxls-T2Sh9h-OLh0E&hl=en&ei=okXES-_KA5n40wSWof3PDg&sa=X&oi=book_result&ct=result&resnum=6&ved=0CCgQ6AEwBQ#v=onepage&q&f=falseFor 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 [1] 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.
[1] http://www.howtocreate.co.uk/jshistory.htmlmocha:
as equivalent to javascript:
as an URL scheme. - Kragen Javier Sitaker
One should be aware about the following to say "I Know JavaScript":
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
What every javascript coder should know?
How about, I can turn off your efforts with 2 clicks. So provide a fallback if possible.
I strongly recommend to read Javascript: The Good Parts [1]
[1] http://cgi.ebay.com/JavaScript-The-Good-Parts-034980_W0QQitemZ260512070208QQcmdZViewItemQQptZUS_Texbook_Education?hash=item3ca7baba40#ht_613wt_940You 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.
JSLint http://www.JSLint.com/
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.
That javascript is the most widely deployed language in the world. (Probably)
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? :^)
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...
object literals because they are so nice to write.
The following things are also important:
1) Variable hoisting. 2) Scope chains and activation objects.
and then things like these: :)
3) wtfjs.com [1]
4) everything is an object http://www.lifeinafolder.com/images/Js.jpg [2]
[1] http://www.wtfjs.comwith()
and where to draw the line.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.
... about Google Web Toolkit [1], which means that your javascript project probably could be developed in a much more conveniant way.
[1] http://code.google.com/intl/sv-SE/webtoolkit/
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
. - Daniel Earwickerthis
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. - bobincethis
goes back to being the global object in a definite way? - Daniel EarwickerFunctionStatement
is a Mozilla syntax extension and it does not work like you described. The phrase "code that appears before it" is false if interpreted literally. Daniel Earwicker: <blockquote>"object.prop and object['prop'] are the same thing" not quite. If followed by () they execute prop as a function, but only the first one sets this = object so prop can access object.</blockquote> That is completely false, as explained. - GarrettFunctionDeclaration
production; indeed, Mozilla docs widely use the phrase to mean just this. There is no “function statement” that is not aFunctionDeclaration
in ECMAScript. The production that Mozilla namedFunctionStatement
is a peculiar non-standard and undesirable extension (presumably meant as some form of compatibility measure, and at least not quite as bad as what IE does). As with named function expressions, all the regular coder needs to know is: avoid. - bobinceFunctionStatement
that is distinct from aFunctionDeclaration
, I think it's worth being clear. - Tim Down