share
Stack OverflowWhat should every JavaScript programmer know?
[+368] [30] gath
[2010-04-13 10:13:21]
[ javascript programming-languages ]
[ https://stackoverflow.com/questions/2628672/what-should-every-javascript-programmer-know ]

Is there a set of things that every JavaScript programmer should know to be able to say "I know JavaScript"?

[+590] [2010-04-13 11:16:04] bobince [ACCEPTED]

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.forinloop
[2] http://bonsaiden.github.com/JavaScript-Garden/#array.general
[3] https://stackoverflow.com/questions/2235622/setting-a-variable-to-undefined/2236186#2236186
[4] https://stackoverflow.com/questions/2568966/how-do-i-pass-the-value-not-the-reference-of-a-js-variable-to-a-function
[5] https://stackoverflow.com/questions/1710424/referencing-a-javascript-value-before-it-is-declared-can-someone-explain-this/1710509#1710509
[6] http://kangax.github.com/nfe/#jscript-bugs
[7] https://stackoverflow.com/questions/1595611/how-to-properly-create-a-custom-object-in-javascript
[8] https://stackoverflow.com/questions/1544735/js-object-this-method-breaks-via-jquery#1544893
[9] https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Working_with_Arrays#Introduced_in_JavaScript_1.6
[10] https://stackoverflow.com/questions/2734025/is-javascript-guaranteed-to-be-single-threaded/2734311#2734311

(80) Ahhhh, finally a thoughtful, thorough answer. If I could +10, I would. Knowing a framework does not mean you can program JavaScript effectively. - Tim Down
(6) Thanks 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. - Javier Parra
(1) Any online references with the answers to these JS details? - luiscubal
Adding some more links. (Sorry for the preponderance of SO self-links, but it's much easier to find past comments than sift through the search results...) - bobince
This is a fantastic answer, and more than enough of a reason for this question to remain open. - Skilldrick
(2) "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. - Daniel Earwicker
(1) +1 a very good answer - might want to link to this when you mention Crockford's book yuiblog.com/crockford - the first part isn't about JS but may be interesting anyway as a selective potted history of programming languages. - Daniel Earwicker
(4) @Daniel: actually not so, this is bound whichever way you access it. Try it: var o= {b: function(){alert(this===o);}};, then o['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. - bobince
OMG! And OYG for that matter! I think I got that idea from Crockford's videos - presumably I misunderstood. Does the ECMA standard actually say when this goes back to being the global object in a definite way? - Daniel Earwicker
ECMAScript Fifth Edition section 11.2.3, then see 8.7 for what GetBase does. Then the NOTE in 11.1.6 explains why adding brackets around the reference doesn't lose the baseValue, and 11.13.1 step 3 for why the assignment operator does. By my reading of 11.12, Mozilla's behaviour with the conditional operator is an error (maybe an optimisation gone awry?) but given how horrible the ECMAScript standard is to read (even by standards documents standards it's pretty heavy going), I can't be 100% sure... - bobince
(7) What 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. - Vince Panuccio
Great list, although I'd add "know the difference between == and === and how it relates to null and undefined". Seen a lot of bad bugs caused by null checks using == and not catching typos in method calls. - ScottKoon
(19) Sir 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 Down
Bobince:<blockquote>the function statement acts to ‘hoist’ a definition before code preceding it;</blockquote> That is a false and misleading statement. FunctionStatement 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. - Garrett
Garrett's correct. It's function declarations rather than function statements that are subject to hoisting. - Tim Down
(1) I think “function statement” is a pretty normal and appropriate way to describe the construct represented by the ECMAScript FunctionDeclaration production; indeed, Mozilla docs widely use the phrase to mean just this. There is no “function statement” that is not a FunctionDeclaration in ECMAScript. The production that Mozilla named FunctionStatement 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. - bobince
I take your point, but given the existence of a separate FunctionStatement that is distinct from a FunctionDeclaration, I think it's worth being clear. - Tim Down
This answer is awesome, and a little intimidating for a slightly naive gunslinger like me who just thought, "hey, I'll just quickly whip up this nifty ajaxified UI for next Wednesday, I mean, how hard can it be to learn some event handlers". ;) Well, I'll start out with some jQuery and work my way through that list by and by... - Hanno Fietz
@bobince: could you expand on why named function expressions should not be used? - Adriano Varoli Piazza
@Adriano: IE before version 9 makes a real hash of them. I've added a link to kangax's article for the gory details. - bobince
1
[+248] [2010-04-13 10:42:20] graphicdivine

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". - wasatz
(27) +1. A page that doesn't work without JavaScript is a page that will be fragile even with JS enabled. - bobince
(1) I disagree. An AJAX application will be totally useless without JS. So far Wt and ASP.NET WF is are the only toolkits that do graceful degradation automatically. And even then, it's only for generated code. - CMircea
@iconiK If you are building an Ajax app that relies heavily on JS for core functionality then you still need to rememebr that it can be disabled and put in some form of appropriate warning at the entry points rather than just leaving a scattering of broken UI elements across the screen or, worse still, just a blank screen. - Colonel Sponsz
(5) @Colonel Sponsz, a warning is fine and easily doable. However, expecting it to be gracefully degradable is way too much. Today web applications are REAL applications. In my book, if you have JS disabled, you're a moron, and thus I'll warn you. - CMircea
(7) @iconiK If it can degrade gracefully then it should, if it can't then a clean page with a warning is the equivalent - it's not rocket surgery. There's so much bad JS out there that I have it disabled until you've proved to me that you are not a moron. - Colonel Sponsz
(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? - graphicdivine
(3) @graphicdivine, JS security problems? What, they're still running IE where you can modify local files? (which turns out to be really bad with a FAT partition). That sounds stupid. - CMircea
(4) +1 Even funnier, is looking at your fancy new javascripted and stylesheeted site without a style sheet. The javascript still cycles through slideshows and the fancy hover feature on menus look hilarious in the default blue underlined font for links. Try it some time. - Elizabeth Buckwalter
@iconiK I use noscript to protect me from malicious scripts, XSS, click-jacking and whatever other thing it does (blocking unwanted flash, google analytics spying etc.). So when I stumble on a JS only website, the chance of me going forward are low if I don't see anything. The best was a website who tried to redirect you if you did not have javascript activated and got a good old XSS warning when js was authorized for the main domain. - Arkh
(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.
(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. - Elizabeth Buckwalter
(1) +1 for the shortest but still very usefull answer ... and for making me laugh :) - Petr Peller
(1) However people may feel about this issue it is definitely statistically irrelevant. Surveys have found over the last few years that people and organisations no longer switch off JS in significant numbers. It's falling all the time and getting down to the level where it's hard to measure at all. - Daniel Earwicker
(1) @Daniel Earwicker "Surveys"? Do you have any examples? I find it impossible to find any reliable statistics on the subject. And by reliable I mean a statistics gathering procedure which doesn't rely on javascript. - graphicdivine
(1) @Elizabeth - While you're right that it is an important consideration given a browser implementation, it really has nothing to do with the javascript language. That is strictly a browser feature and not all javascript runs in the browser. - user113716
JavaScript is a programming language, and this comment hast absolutely nothing to do with it. - alcuadrado
Where the hell is +10 .. man - mr_eclair
I totally disagree. The failure to understand the beauty or meaning of something does not mean you should shut it off. - Assambar
@ElizabethBuckwalter & likes, only if you are in a world where JavaScript is confined to browser, yes your answer was the most fruitful one. To me the question looks like its about knowing things in JavaScript as a programming language, and not about what needs to be done when it's disabled in the browser. By the way guys who claim that they "disable" JavaScript while browsing, well you would have not been able to post replies on stackoverflow in the first place with JS disabled. Don't adduce your points with baseless claims. - ch4nd4n
Not everybody is writing general public facing web sites. I write web apps that are 100% dynamic. Everything on the screen is an object that can be reused and tested. Sure graceful degradation is desirable if you don't know who's visiting your web pages. But you're going to have code things twice and your code will be tightly coupled, messy and hard to reuse and test - Juan Mendes
Also, that we live in 2012 (as of now). If your web site/app is targeting people who disable Javascript, accept my deepest condolences. - Slavo
2
[+75] [2010-04-13 10:25:06] bron

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/0596517742

+1 Keep forgetting about that book, excellent recommendation. - David
+1 good points. - Daniel Vassallo
(8) There 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 :-) - ndim
+1 - JSLint is a wonderful thing when you try developing JS for a framework that has zero embedded debugging support (cough Siebel, cough PDFs). - J. Polfer
+1 This book is gold! - Chris Pietschmann
3
[+49] [2010-04-13 11:36:14] Skilldrick

If 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; });

What does this expression return?

  • “number”
  • “undefined”
  • “function”
  • Error
[1] http://perfectionkills.com/javascript-quiz/

(10) Give a look to my answers: codingspot.com/2010/02/… - CMS
@CMS Very good! Did you actually get the all right first time, or does this include some research? - Skilldrick
(7) Skilldrick: 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 :-) - CMS
(1) +1 Very nice quiz! - Tomas
4
[+46] [2010-04-21 07:29:00] edwin

You don't know JavaScript if you don't know:

  1. Closures
  2. Prototype-based inheritance
  3. The module pattern
  4. The W3C-DOM
  5. 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). - silviot
(11) I would argue that You don't know JavaScript if you don't know The W3C-DOM. The two things are different. - gblazex
+1 for module pattern - Brian Wigginton
5
[+37] [2010-04-13 10:19:10] Sripathi Krishnan

..that javascript is not java :)

Many, many people starting with website development have told me javascript is just simple java!


+1 This point is pretty fundamental! - amelvin
(71) “JavaScript is to Java as carpet is to car.” - Josh Lee
(1) Javascript is about as similar to Java as C# is similar to C. Sure there syntax looks kinda similar, but way way different. - Earlz
(4) unless they use Google Web Toolkit - Afriza N. Arief
Interestingly, Microsoft did base the Y2k compliant date functions in JScript for IE3 on java.util.Date. - Bayard Randel
Java is to JavaScript as Ham is to HamSter - dave1010
6
[+27] [2010-04-13 10:21:43] David
  1. Familiarize yourself with atleast one Javascript library ( Jquery, Prototype, etc ).

  2. Learn how to use the debugging tools of the major browsers ( MSIE 7-8, Firefox, Chrome, Safari )

  3. 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.


Seriously, why the down vote? - David
+1 Too much tactical voting, seriously people should just upvote the good answers not just try to foist their answer to the top. - amelvin
(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) - David
@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. - David
@David thanks for the nice explanation. Tend to agree with you. - Murali VP
I downvoted simply because I don't feel the answers have anything to do with the JavaScript language itself. Although they are excellent advice. - ScottKoon
@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. - David
7
[+24] [2010-04-13 10:17:12] Sarfraz

Javascript objects and function as first-class citizen, callbacks, not to forget about events and then JQuery [1].

[1] http://jquery.com/

(20) Ah jQuery, the overhyped JS framework! - Murali VP
8
[+24] [2010-04-21 09:00:25] Ashwin Prabhu

That Javascript is not something which can be learnt in an hour!


(4) but this seems to be the popular belief - Livingston Samuel
9
[+23] [2010-04-16 20:54:59] theycallmemorty

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();

(2) I'd never even considered this. Very good point. - olive
(6) I try and get in the habit of for (var i=0; in all my loops - ghoppe
(2) Crockford 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 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
I don't care if it's not scoped. I can't stand having a variable declared 20 lines before it's used - Juan Mendes
10
[+20] [2010-04-13 10:18:22] Daniel Vassallo

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=false

+1 The best book to read on JavaScript; and also Flanagan's book - Andreas Grech
11
[+8] [2010-04-13 10:25:29] amelvin

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 [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.html

+1 for picking tit bits from Douglas Crockford! - gath
(1) I thought JavaScript was originally called Mocha? - user181548
(1) @Kinopiko According to my 'Javascript: The Definitive Guide' 3ed (June 1998) book by David Flanaghan it was called LiveScript. - amelvin
@gath A day when you learn something is a good day! - amelvin
Sez Mocha here: en.wikipedia.org/wiki/JavaScript - user181548
(1) @amelvin Every day's a school day. - Colonel Sponsz
@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. - amelvin
Even though it was never released as Mocha, Netscape up to at least version 4 would interpret mocha: as equivalent to javascript: as an URL scheme. - Kragen Javier Sitaker
12
[+8] [2010-04-13 16:06:18] Anil Namde

One should be aware about the following to say "I Know JavaScript":

  1. JavaScript is good but DOM is pain point
  2. Cross browser issues can make you go crazy
  3. Unless code is tested on least 4 different good browsers you can't say its bug free
  4. Closure.............. Must know
  5. Its prototype based ........... Nice one its fun to learn this
  6. 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. - Shyam
@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. - Tracker1
@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. - Shyam
13
[+7] [2010-04-13 10:18:02] ericteubert

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 - Colonel Sponsz
Another good Crockfod presentation ("The JavaScript Programming Language" 4 parts) video.yahoo.com/watch/111593/1710507 - Alex K.
+1 Didn't know about this. - amelvin
14
[+7] [2010-04-21 08:21:53] Khainestar

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. - Jean Vincent
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. - Khainestar
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. - Jean Vincent
15
[+6] [2010-04-14 07:15:17] Sungguk Lim

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_940

16
[+6] [2010-04-21 17:39:18] Michiel van der Blonk

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.


(1) Closure 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. - gblazex
Apart from the harm closures can cause, like memory leaks, especially in our true friend Internet Explorer 6. - Marcel Korpel
17
[+4] [2010-04-13 10:17:28] Richard Inglis
18
[+4] [2010-04-21 07:24:23] Soup

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.


19
[+4] [2011-08-02 22:51:13] mykhal

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..


20
[+3] [2010-04-13 10:15:58] duffymo

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) +1 Jquery has revolutionised my use of javascript. - amelvin
(1) Good argument outline. Expanding would make it a great answer. - Donal Fellows
jQuery forces you into a procedural mode. I much rather write OO JS - Juan Mendes
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. - duffymo
21
[+3] [2010-04-13 10:30:23] zaf

That javascript is the most widely deployed language in the world. (Probably)


(8) Most 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? - Zano
(11) The most widely deployed language in the world is the genetic code of the DNA that controls the protein synthesis within the cells. - Ernelli
Before Mandarin and DNA, the language of Love must first be deployed: thus, it wins. BAM! - Christopher
22
[+3] [2011-06-23 15:35:45] christos constandinou

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. - Juan Mendes
23
[+2] [2010-05-15 16:49:42] caltuntas

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) In fact Browser compilers are very good at optimizing your code. - Eduardo
(1) Chrome is very smart at optimizing your code, this answer is just not true with all the new JS engines - Juan Mendes
What about IE, mobile browsers? - caltuntas
24
[+1] [2010-04-13 11:18:29] poo

object literals because they are so nice to write.


25
[0] [2010-04-21 03:57:25] Rajat

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.com
[2] http://www.lifeinafolder.com/images/Js.jpg

(6) 3.) is wrong. Not everything is an object. stackoverflow.com/questions/3907613/… - gblazex
26
[0] [2010-04-29 20:50:45] FK82
  1. Knowing that there is a life with and without with() and where to draw the line.
  2. You can create custom errors with the throw statement to purposely stop the javascript runtime.

27
[-1] [2010-11-03 11:16:11] Soul_Master

JavaScript is not support separating return keyword and return statement with newline character like the following code (or try it at my jsFiddle page [1])

function foo()
{
    return
    {
        bar: 'something'
    };
}

$(function()
{
    document.write(foo());
});

I don't understand why JavaScript does not support this style because it's much easier to read very complex JavaScript source code when compare with default style of JavaScript.

PS. I have written JavaScript almost 6 years. But I just found this bug with myself when I try to execute the following function. It always returns undefined. When I use debugger and step into this function everything is work fine. I think it should be the worst programming bug in my life.

function JqGridInlineEditor_GenerateTool(cellvalue, options, rowObject, disableEdit, disableDelete)
{
    return 
        (!disableEdit ? '<a class="button edit" href="javascript: void(0);" onclick="JqGridInlineEditor_EditRow(this, \'{0}\');return false;" title="{2}"><img src="{1}" alt="{2}" /></a>'.format(options.rowId, getUrl('~/Content/Icons/Edit.gif'), 'Click here to Edit or \nDouble-click row to edit.') : '') +
        (!disableDelete ? '<a class="button delete" href="javascript: void(0);" onclick="JqGridInlineEditor_DeleteRow(this, \'{0}\');return false;" title="{2}"><img src="{1}" alt="{2}" /></a>'.format(options.rowId, getUrl('~/Content/Icons/Delete.png'), 'Click here to Delete or \nSelect row and then press Delete') : '') +
        (!disableEdit ? '<a class="button save" style="display:none" href="javascript: void(0);" onclick="JqGridInlineEditor_SaveRow(this, \'{0}\');return false;" title="{2}"><img src="{1}" alt="{2}" /></a>'.format(options.rowId, getUrl('~/Content/Icons/Save.png'), 'Click here to Save or \nPress Enter') : '') +
        (!disableEdit ? '<a class="button cancel" style="display:none" href="javascript: void(0);" onclick="JqGridInlineEditor_RestoreRow(this, \'{0}\');return false;" title="{2}"><img src="{1}" alt="{2}" /></a>'.format(options.rowId, getUrl('~/Content/Icons/Cancel.png'), 'Click here to Cancel or \nPress Esc') : '');
}
[1] http://jsfiddle.net/Soul_Master/tVsWS/

(3) In JavaScript, newline characters usually act as separators of statements; only when it's impossible a statement has ended (e.g., var foo = "bar" +) the parser reads on. - Marcel Korpel
Another jsFiddle. jsfiddle.net/Soul_Master/BxrDJ - Soul_Master
(2) @Marcel — That isn't precisely true; for example, the two lines var foo = 5 and -1; will result in foo being set to 4, even though each are valid statements on their own. - Ben Blank
(4) This is because the language injects semicolons automatically to separate statements. This is a gotcha with the language. Your return statement gets converted to this: return; { key : value, } To avoid this problem, you should adopt the practice of putting semicolons in the same line, like this: return { key : value }; Also, do yourself a favor and grab a copy of the Douglas Crockford : The Good Parts. This is clearly mentioned in the book. - Rajat
@Ben – Interesting case, thanks for pointing at that. That said, I'd recommend to not rely on these edge cases and just put everything on one line ending with a semicolon and only put your code on multiple lines when a line is ending with something a statement or expression simply can't end with. - Marcel Korpel
@Marcel — No argument here! Semicolon insertion basically boils down to "magic". ;-) - Ben Blank
@Rajat - I just realize that JavaScript will automatically fill the end of line with semicolon. It might be the main cause why JavaScript does not support this problem. - Soul_Master
28
[-3] [2010-04-13 10:28:32] user187291

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.


(1) What'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. - Raynos
C can be used as a functional language, too. - kzh
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. - Evert
29
[-5] [2010-04-14 07:05:07] Viktor Sehr

... 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/

(2) GWT is not really JavaScript, it is the Javaish way of writing JavaScript. - Livingston Samuel
...and every Javascipt programmer should know about it. - Viktor Sehr
And the reason is ... ? - gblazex
that your javascript project probably could be developed in a much more conveniant way. - Viktor Sehr
(6) I think Javascript is easier to deal with than Java, personally. - timw4mail
30