Douglas Crockford

Mentioned 178

Describes the reliable features of JavaScript, covering such topics as syntax, objects, functions, arrays, regular expressions, inheritance, and methods.

More on

Mentioned in questions and answers.

I'm using JSLint to go through JavaScript, and it's returning many suggestions to replace == (two equals signs) with === (three equals signs) when doing things like comparing idSele_UNVEHtype.value.length == 0 inside of an if statement.

Is there a performance benefit to replacing == with ===?

Any performance improvement would be welcomed as many comparison operators exist.

If no type conversion takes place, would there be a performance gain over ==?

The identity (===) operator behaves identically to the equality (==) operator except no type conversion is done, and the types must be the same to be considered equal.

Reference: Javascript Tutorial: Comparison Operators

The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. Both are equally quick.

To quote Douglas Crockford's excellent JavaScript: The Good Parts,

JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases:

'' == '0'           // false
0 == ''             // true
0 == '0'            // true

false == 'false'    // false
false == '0'        // true

false == undefined  // false
false == null       // false
null == undefined   // true

' \t\r\n ' == 0     // true

The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use === and !==. All of the comparisons just shown produce false with the === operator.


A good point was brought up by @Casebash in the comments and in @Phillipe Laybaert's answer concerning reference types. For reference types == and === act consistently with one another (except in a special case).

var a = [1,2,3];
var b = [1,2,3];

var c = { x: 1, y: 2 };
var d = { x: 1, y: 2 };

var e = "text";
var f = "te" + "xt";

a == b            // false
a === b           // false

c == d            // false
c === d           // false

e == f            // true
e === f           // true

The special case is when you compare a literal with an object that evaluates to the same literal, due to its toString or valueOf method. For example, consider the comparison of a string literal with a string object created by the String constructor.

"abc" == new String("abc")    // true
"abc" === new String("abc")   // false

Here the == operator is checking the values of the two objects and returning true, but the === is seeing that they're not the same type and returning false. Which one is correct? That really depends on what you're trying to compare. My advice is to bypass the question entirely and just don't use the String constructor to create string objects.


As a rule of thumb, I would generally use === instead of == (and !== instead of !=).

Reasons are explained in in the answers above and also Douglas Crockford is pretty clear about it (JavaScript: The Good Parts).

However there is one single exception: == null is an efficient way to check for 'is null or undefined':

if( value == null ){
    // value is either null or undefined

For example jQuery 1.9.1 uses this pattern 43 times, and the JSHint syntax checker even provides the eqnull relaxing option for this reason.

From the jQuery style guide:

Strict equality checks (===) should be used in favor of ==. The only exception is when checking for undefined and null by way of null.

// Check for both undefined and null values, for some important reason. 
undefOrNull == null;

I don't fully get what Node.js is all about. Maybe it's because I am mainly a web based business application developer. What is it and what is the use of it?

My understanding so far is that:

  1. The programming model is event driven, especially the way it handles I/O.
  2. It uses JavaScript and the parser is V8.
  3. It can be easily used to create concurrent server applications.

Are my understandings correct? If yes, then what are the benefits of evented I/O, is it just more for the concurrency stuff? Also, is the direction of Node.js to become a framework like, JavaScript based (V8 based) programming model?

I use Node.js at work, and find it to be very powerful. Forced to choose one word to describe Node.js, I'd say "interesting" (which is not a purely positive adjective). The community is vibrant and growing. JavaScript, despite its oddities can be a great language to code in. And you will daily rethink your own understanding of "best practice" and the patterns of well-structured code. There's an enormous energy of ideas flowing into Node.js right now, and working in it exposes you to all this thinking - great mental weightlifting.

Node.js in production is definitely possible, but far from the "turn-key" deployment seemingly promised by the documentation. With Node.js v0.6.x, "cluster" has been integrated into the platform, providing one of the essential building blocks, but my "production.js" script is still ~150 lines of logic to handle stuff like creating the log directory, recycling dead workers, etc. For a "serious" production service, you also need to be prepared to throttle incoming connections and do all the stuff that Apache does for PHP. To be fair, Ruby on Rails has this exact problem. It is solved via two complementary mechanisms: 1) Putting Ruby on Rails/Node.js behind a dedicated webserver (written in C and tested to hell and back) like Nginx (or Apache / Lighttd). The webserver can efficiently serve static content, access logging, rewrite URLs, terminate SSL, enforce access rules, and manage multiple sub-services. For requests that hit the actual node service, the webserver proxies the request through. 2) Using a framework like Unicorn that will manage the worker processes, recycle them periodically, etc. I've yet to find a Node.js serving framework that seems fully baked; it may exist, but I haven't found it yet and still use ~150 lines in my hand-rolled "production.js".

Reading frameworks like Express makes it seem like the standard practice is to just serve everything through one jack-of-all-trades Node.js service ... "app.use(express.static(__dirname + '/public'))". For lower-load services and development, that's probably fine. But as soon as you try to put big time load on your service and have it run 24/7, you'll quickly discover the motivations that push big sites to have well baked, hardened C-code like Nginx fronting their site and handling all of the static content requests (...until you set up a CDN, like Amazon CloudFront)). For a somewhat humorous and unabashedly negative take on this, see this guy.

Node.js is also finding more and more non-service uses. Even if you are using something else to serve web content, you might still use Node.js as a build tool, using npm modules to organize your code, Browserify to stitch it into a single asset, and uglify-js to minify it for deployment. For dealing with the web, JavaScript is a perfect impedance match and frequently that makes it the easiest route of attack. For example, if you want to grovel through a bunch of JSON response payloads, you should use my underscore-CLI module, the utility-belt of structured data.

Pros / Cons:

  • Pro: For a server guy, writing JavaScript on the backend has been a "gateway drug" to learning modern UI patterns. I no longer dread writing client code.
  • Pro: Tends to encourage proper error checking (err is returned by virtually all callbacks, nagging the programmer to handle it; also, async.js and other libraries handle the "fail if any of these subtasks fails" paradigm much better than typical synchronous code)
  • Pro: Some interesting and normally hard tasks become trivial - like getting status on tasks in flight, communicating between workers, or sharing cache state
  • Pro: Huge community and tons of great libraries based on a solid package manager (npm)
  • Con: JavaScript has no standard library. You get so used to importing functionality that it feels weird when you use JSON.parse or some other build in method that doesn't require adding an npm module. This means that there are five versions of everything. Even the modules included in the Node.js "core" have five more variants should you be unhappy with the default implementation. This leads to rapid evolution, but also some level of confusion.

Versus a simple one-process-per-request model (LAMP):

  • Pro: Scalable to thousands of active connections. Very fast and very efficient. For a web fleet, this could mean a 10X reduction in the number of boxes required versus PHP or Ruby
  • Pro: Writing parallel patterns is easy. Imagine that you need to fetch three (or N) blobs from Memcached. Do this in PHP ... did you just write code the fetches the first blob, then the second, then the third? Wow, that's slow. There's a special PECL module to fix that specific problem for Memcached, but what if you want to fetch some Memcached data in parallel with your database query? In Node.js, because the paradigm is asynchronous, having a web request do multiple things in parallel is very natural.
  • Con: Asynchronous code is fundamentally more complex than synchronous code, and the up-front learning curve can be hard for developers without a solid understanding of what concurrent execution actually means. Still, it's vastly less difficult than writing any kind of multithreaded code with locking.
  • Con: If a compute-intensive request runs for, for example, 100 ms, it will stall processing of other requests that are being handled in the same Node.js process ... AKA, cooperative-multitasking. This can be mitigated with the Web Workers pattern (spinning off a subprocess to deal with the expensive task). Alternatively, you could use a large number of Node.js workers and only let each one handle a single request concurrently (still fairly efficient because there is no process recycle).
  • Con: Running a production system is MUCH more complicated than a CGI model like Apache + PHP, Perl, Ruby, etc. Unhandled exceptions will bring down the entire process, necessitating logic to restart failed workers (see cluster). Modules with buggy native code can hard-crash the process. Whenever a worker dies, any requests it was handling are dropped, so one buggy API can easily degrade service for other cohosted APIs.

Versus writing a "real" service in Java / C# / C (C? really?)

  • Pro: Doing asynchronous in Node.js is easier than doing thread-safety anywhere else and arguably provides greater benefit. Node.js is by far the least painful asynchronous paradigm I've ever worked in. With good libraries, it is only slightly harder than writing synchronous code.
  • Pro: No multithreading / locking bugs. True, you invest up front in writing more verbose code that expresses a proper asynchronous workflow with no blocking operations. And you need to write some tests and get the thing to work (it is a scripting language and fat fingering variable names is only caught at unit-test time). BUT, once you get it to work, the surface area for heisenbugs -- strange problems that only manifest once in a million runs -- that surface area is just much much lower. The taxes writing Node.js code are heavily front-loaded into the coding phase. Then you tend to end up with stable code.
  • Pro: JavaScript is much more lightweight for expressing functionality. It's hard to prove this with words, but JSON, dynamic typing, lambda notation, prototypal inheritance, lightweight modules, whatever ... it just tends to take less code to express the same ideas.
  • Con: Maybe you really, really like coding services in Java?

For another perspective on JavaScript and Node.js, check out From Java to Node.js, a blog post on a Java developer's impressions and experiences learning Node.js.

Modules When considering node, keep in mind that your choice of JavaScript libraries will DEFINE your experience. Most people use at least two, an asynchronous pattern helper (Step, Futures, Async), and a JavaScript sugar module (Underscore.js).

Helper / JavaScript Sugar:

  • Underscore.js - use this. Just do it. It makes your code nice and readable with stuff like _.isString(), and _.isArray(). I'm not really sure how you could write safe code otherwise. Also, for enhanced command-line-fu, check out my own Underscore-CLI.

Asynchronous Pattern Modules:

  • Step - a very elegant way to express combinations of serial and parallel actions. My personal reccomendation. See my post on what Step code looks like.
  • Futures - much more flexible (is that really a good thing?) way to express ordering through requirements. Can express things like "start a, b, c in parallel. When A, and B finish, start AB. When A, and C finish, start AC." Such flexibility requires more care to avoid bugs in your workflow (like never calling the callback, or calling it multiple times). See Raynos's post on using futures (this is the post that made me "get" futures).
  • Async - more traditional library with one method for each pattern. I started with this before my religious conversion to step and subsequent realization that all patterns in Async could be expressed in Step with a single more readable paradigm.
  • TameJS - Written by OKCupid, it's a precompiler that adds a new language primative "await" for elegantly writing serial and parallel workflows. The pattern looks amazing, but it does require pre-compilation. I'm still making up my mind on this one.
  • StreamlineJS - competitor to TameJS. I'm leaning toward Tame, but you can make up your own mind.

Or to read all about the asynchronous libraries, see this panel-interview with the authors.

Web Framework:

  • Express Great Ruby on Rails-esk framework for organizing web sites. It uses JADE as a XML/HTML templating engine, which makes building HTML far less painful, almost elegant even.
  • jQuery While not technically a node module, jQuery is quickly becoming a de-facto standard for client-side user interface. jQuery provides CSS-like selectors to 'query' for sets of DOM elements that can then be operated on (set handlers, properties, styles, etc). Along the same vein, Twitter's Bootstrap CSS framework, Backbone.js for an MVC pattern, and Browserify.js to stitch all your JavaScript files into a single file. These modules are all becoming de-facto standards so you should at least check them out if you haven't heard of them.


  • JSHint - Must use; I didn't use this at first which now seems incomprehensible. JSLint adds back a bunch of the basic verifications you get with a compiled language like Java. Mismatched parenthesis, undeclared variables, typeos of many shapes and sizes. You can also turn on various forms of what I call "anal mode" where you verify style of whitespace and whatnot, which is OK if that's your cup of tea -- but the real value comes from getting instant feedback on the exact line number where you forgot a closing ")" ... without having to run your code and hit the offending line. "JSHint" is a more-configurable variant of Douglas Crockford's JSLint.
  • Mocha competitor to Vows which I'm starting to prefer. Both frameworks handle the basics well enough, but complex patterns tend to be easier to express in Mocha.
  • Vows Vows is really quite elegant. And it prints out a lovely report (--spec) showing you which test cases passed / failed. Spend 30 minutes learning it, and you can create basic tests for your modules with minimal effort.
  • Zombie - Headless testing for HTML and JavaScript using JSDom as a virtual "browser". Very powerful stuff. Combine it with Replay to get lightning fast deterministic tests of in-browser code.
  • A comment on how to "think about" testing:
    • Testing is non-optional. With a dynamic language like JavaScript, there are very few static checks. For example, passing two parameters to a method that expects 4 won't break until the code is executed. Pretty low bar for creating bugs in JavaScript. Basic tests are essential to making up the verification gap with compiled languages.
    • Forget validation, just make your code execute. For every method, my first validation case is "nothing breaks", and that's the case that fires most often. Proving that your code runs without throwing catches 80% of the bugs and will do so much to improve your code confidence that you'll find yourself going back and adding the nuanced validation cases you skipped.
    • Start small and break the inertial barrier. We are all lazy, and pressed for time, and it's easy to see testing as "extra work". So start small. Write test case 0 - load your module and report success. If you force yourself to do just this much, then the inertial barrier to testing is broken. That's <30 min to do it your first time, including reading the documentation. Now write test case 1 - call one of your methods and verify "nothing breaks", that is, that you don't get an error back. Test case 1 should take you less than one minute. With the inertia gone, it becomes easy to incrementally expand your test coverage.
    • Now evolve your tests with your code. Don't get intimidated by what the "correct" end-to-end test would look like with mock servers and all that. Code starts simple and evolves to handle new cases; tests should too. As you add new cases and new complexity to your code, add test cases to exercise the new code. As you find bugs, add verifications and / or new cases to cover the flawed code. When you are debugging and lose confidence in a piece of code, go back and add tests to prove that it is doing what you think it is. Capture strings of example data (from other services you call, websites you scrape, whatever) and feed them to your parsing code. A few cases here, improved validation there, and you will end up with highly reliable code.

Also, check out the official list of recommended Node.js modules. However, GitHub's Node Modules Wiki is much more complete and a good resource.

To understand Node, it's helpful to consider a few of the key design choices:

Node.js is EVENT BASED and ASYNCHRONOUS / NON-BLOCKING. Events, like an incoming HTTP connection will fire off a JavaScript function that does a little bit of work and kicks off other asynchronous tasks like connecting to a database or pulling content from another server. Once these tasks have been kicked off, the event function finishes and Node.js goes back to sleep. As soon as something else happens, like the database connection being established or the external server responding with content, the callback functions fire, and more JavaScript code executes, potentially kicking off even more asynchronous tasks (like a database query). In this way, Node.js will happily interleave activities for multiple parallel workflows, running whatever activities are unblocked at any point in time. This is why Node.js does such a great job managing thousands of simultaneous connections.

Why not just use one process/thread per connection like everyone else? In Node.js, a new connection is just a very small heap allocation. Spinning up a new process takes significantly more memory, a megabyte on some platforms. But the real cost is the overhead associated with context-switching. When you have 10^6 kernel threads, the kernel has to do a lot of work figuring out who should execute next. A bunch of work has gone into building an O(1) scheduler for Linux, but in the end, it's just way way more efficient to have a single event-driven process than 10^6 processes competing for CPU time. Also, under overload conditions, the multi-process model behaves very poorly, starving critical administration and management services, especially SSHD (meaning you can't even log into the box to figure out how screwed it really is).

Node.js is SINGLE THREADED and LOCK FREE. Node.js, as a very deliberate design choice only has a single thread per process. Because of this, it's fundamentally impossible for multiple threads to access data simultaneously. Thus, no locks are needed. Threads are hard. Really really hard. If you don't believe that, you haven't done enough threaded programming. Getting locking right is hard and results in bugs that are really hard to track down. Eliminating locks and multi-threading makes one of the nastiest classes of bugs just go away. This might be the single biggest advantage of node.

But how do I take advantage of my 16 core box?

Two ways:

  1. For big heavy compute tasks like image encoding, Node.js can fire up child processes or send messages to additional worker processes. In this design, you'd have one thread managing the flow of events and N processes doing heavy compute tasks and chewing up the other 15 CPUs.
  2. For scaling throughput on a webservice, you should run multiple Node.js servers on one box, one per core, using cluster (With Node.js v0.6.x, the official "cluster" module linked here replaces the learnboost version which has a different API). These local Node.js servers can then compete on a socket to accept new connections, balancing load across them. Once a connection is accepted, it becomes tightly bound to a single one of these shared processes. In theory, this sounds bad, but in practice it works quite well and allows you to avoid the headache of writing thread-safe code. Also, this means that Node.js gets excellent CPU cache affinity, more effectively using memory bandwidth.

Node.js lets you do some really powerful things without breaking a sweat. Suppose you have a Node.js program that does a variety of tasks, listens on a TCP port for commands, encodes some images, whatever. With five lines of code, you can add in an HTTP based web management portal that shows the current status of active tasks. This is EASY to do:

var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
}).listen(1337, "");

Now you can hit a URL and check the status of your running process. Add a few buttons, and you have a "management portal". If you have a running Perl / Python / Ruby script, just "throwing in a management portal" isn't exactly simple.

But isn't JavaScript slow / bad / evil / spawn-of-the-devil? JavaScript has some weird oddities, but with "the good parts" there's a very powerful language there, and in any case, JavaScript is THE language on the client (browser). JavaScript is here to stay; other languages are targeting it as an IL, and world class talent is competing to produce the most advanced JavaScript engines. Because of JavaScript's role in the browser, an enormous amount of engineering effort is being thrown at making JavaScript blazing fast. V8 is the latest and greatest javascript engine, at least for this month. It blows away the other scripting languages in both efficiency AND stability (looking at you, Ruby). And it's only going to get better with huge teams working on the problem at Microsoft, Google, and Mozilla, competing to build the best JavaScript engine (It's no longer a JavaScript "interpreter" as all the modern engines do tons of JIT compiling under the hood with interpretation only as a fallback for execute-once code). Yeah, we all wish we could fix a few of the odder JavaScript language choices, but it's really not that bad. And the language is so darn flexible that you really aren't coding JavaScript, you are coding Step or jQuery -- more than any other language, in JavaScript, the libraries define the experience. To build web applications, you pretty much have to know JavaScript anyway, so coding with it on the server has a sort of skill-set synergy. It has made me not dread writing client code.

Besides, if you REALLY hate JavaScript, you can use syntactic sugar like CoffeeScript. Or anything else that creates JavaScript code, like Google Web Toolkit (GWT).

Speaking of JavaScript, what's a "closure"? - Pretty much a fancy way of saying that you retain lexically scoped variables across call chains. ;) Like this:

var myData = "foo";
database.connect( 'user:pass', function myCallback( result ) {
    database.query("SELECT * from Foo where id = " + myData);
} );
// Note that doSomethingElse() executes _BEFORE_ "database.query" which is inside a callback

See how you can just use "myData" without doing anything awkward like stashing it into an object? And unlike in Java, the "myData" variable doesn't have to be read-only. This powerful language feature makes asynchronous-programming much less verbose and less painful.

Writing asynchronous code is always going to be more complex than writing a simple single-threaded script, but with Node.js, it's not that much harder and you get a lot of benefits in addition to the efficiency and scalability to thousands of concurrent connections...

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

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

What "Hidden Features" of JavaScript do you think every programmer should know?

After having seen the excellent quality of the answers to the following questions I thought it was time to ask it for JavaScript.

Even though JavaScript is arguably the most important Client Side language right now (just ask Google) it's surprising how little most web developers appreciate how powerful it really is.

I could quote most of Douglas Crockford's excellent book JavaScript: The Good Parts.

But I'll take just one for you, always use === and !== instead of == and !=

alert('' == '0'); //false
alert(0 == ''); // true
alert(0 =='0'); // true

== is not transitive. If you use === it would give false for all of these statements as expected.

In JavaScript, every object is at the same time an instance and a class. To do inheritance, you can use any object instance as a prototype.

In Python, C++, etc.. there are classes, and instances, as separate concepts. In order to do inheritance, you have to use the base class to create a new class, which can then be used to produce derived instances.

Why did JavaScript go in this direction (prototype-based object orientation)? what are the advantages (and disadvantages) of prototype-based OO with respect to traditional, class-based OO?

You should check out a great book on JavaScript by Douglas Crockford. It provides a very good explanation of some of the design decisions taken by JavaScript creators.

One of the important design aspect of JavaScript is its prototypal inheritance system. Objects are first class citizens in JavaScript, so much that regular functions are also implemented as objects ('Function' object to be precise). In my opinion when it was originally designed to run inside a browser, it was meant to be used to create lots of singleton objects. In browser DOM, you find that window, document etc all singleton objects. Also JavaScript is loosely typed dynamic language (as opposed to say Python which is strongly typed, dynamic language), as a result a concept of object extension was implemented through the use of 'prototype' property.

So I think there are some pros for protytype-based OO as implemented in JavaScript:

  1. Suitable in loosely typed environments, no need to define explicit types.
  2. Makes it incredibly easy to implement singleton pattern (compare JavaScript and Java in this regard, and you'll know what I am talking about).
  3. Provides ways of applying a method of an object in the context of a different object, adding and replacing methods dynamically from an object etc. (things which are not possible in a strongly typed languages).

Here are some of the cons of prototypal OO:

  1. No easy way of implementing private variables. Its possible to implement private vars using Crockford's wizardry using closures, but its definitely not as trivial as using private variables in say Java or C#.
  2. I don't know how to implement multiple inheritance (for what its worth) in JavaScript yet.

Is it possible to call the base method from a prototype method in JavaScript if it's been overridden?

MyClass = function(name){ = name; = function() {
        //do somthing 
}; = function() {  
    if ( === 'something') {
        //do something new
    } else {

I'm afraid your example does not work the way you think. This part: = function(){ /*do something*/ };

overwrites the definition of = function(){ /*do something else*/ };

Since the newly created object already has a "do" property, it does not look up the prototypal chain.

The classical form of inheritance in Javascript is awkard, and hard to grasp. I would suggest using Douglas Crockfords simple inheritance pattern instead. Like this:

function my_class(name) {
    return {
        name: name,
        do: function () { /* do something */ }

function my_child(name) {
    var me = my_class(name);
    var base_do =; = function () {
        if ( === 'something'){
            //do something new
        } else {
    return me;

var o = my_child("something");; // does something new

var u = my_child("something else");; // uses base function

In my opinion a much clearer way of handling objects, constructors and inheritance in javascript. You can read more in Crockfords Javascript: The good parts.

At the moment, the only fully supported language, and the de-facto standard for DOM tree manipulation in the browser is JavaScript. It looks like it has deep design issues that make it a minefield of bugs and security holes for the novice.

Do you know of any existent or planned initiative to introduce a better (redesigned) language of any kind (not only javascript) for DOM tree manipulation and HTTP requests in next generation browsers? If yes, what is the roadmap for its integration into, say, Firefox, and if no, for what reasons (apart of interoperability) should be JavaScript the only supported language on the browser platform?

I already used jQuery and I also read "javascript: the good parts". Indeed the suggestions are good, but what I am not able to understand is: why only javascript? On the server-side (your-favourite-os platform), we can manipulate a DOM tree with every language, even fortran. Why does the client side (the browser platform) support only javascript?

If you're thinking that JavaScript has deep issues, I recommend Doug Crockford's book, JavaScript: The Good Parts. (Or Google for "Crockford JavaScript" to find several video presentations he's done.) Crockford sketches out a safe subset and set of practices, and specifically lists some parts of the language to avoid.

I'm unaware of plans to replace JavaScript as the de facto means of manipulating the DOM. So best learn to use it safely and well.

Is it a good idea to learn JavaScript before learning a JavaScript framework library such as jQuery, Prototype, etc.?

Sometimes I find myself struggling because I feel I don't know JavaScript as well as I should.

There are really two seperate aspects to JavaScript within the Browser. First, the JavaScript Language, and second the HTML DOM that allows you to manipulate the page using the JavaScript Language.

That said, then YES you should spend time learning the JavaScript Language. I recommend picking up a copy of "JavaScript: The Good Parts" by Douglas Crockford.

Now as to the second part, the HTML DOM. You really don't need to focus too much on learning the ins and outs of the HTML DOM if you are going to use a framework like jQuery. Just do things the "jQuery way" and then pick up as much HTML DOM as is necessary along the way.

I'm new to JavaScript and just discovered toFixed() and toPrecision() to round numbers. However, I can't figure out what the difference between the two is.

What is the difference between number.toFixed() and number.toPrecision()?

I believe that the former gives you a fixed number of decimal places, whereas the latter gives you a fixed number of significant digits.

Math.PI.toFixed(2); // "3.14"
Math.PI.toPrecision(2); // "3.1"

Furthermore, toPrecision will yield scientific notation if there are more integer digits in the number than the specified precision.

(Math.PI * 10).toPrecision(2); // "31"
(Math.PI * 100).toPrecision(2); // "3.1e+2"

EDIT: Oh, and if you are new to JavaScript, I can highly recommend the book "JavaScript: The Good Parts" by Douglas Crockford.

I am going offline for a few days, and would like to bring the JavaScript documentation with me on my laptop :)

Does anyone know of a place where I can get downloadable reference documentation for JavaScript, preferably for Firefox?

I have checked the Mozilla site, but have only been able to find an online version.

How about finding a copy of both (or either one of) JavaScript: The Definitive Guide by David Flanagan and JavaScript: The Good Parts ?

This is a question for general discussion. Are there any good, comprehensive resources for useful JavaScript design patterns. I am trying to avoid references that attempt to coerce JavaScript into, say, Java by imposing patterns more suited to another language. Let's let JS be JS and shape our patterns around the strengths.

Please any discussion would be valued by more than just me, I suspect.

JavaScript is a lightweight and powerful language, but it's often misunderstood and hard to learn (especially about its object oriented programming).

What are the good materials (blogs, screencasts and books) to learn JavaScript OOP? The topics can be anything, but let's not include browsers, AJAX and libraries for now.

Also how did you learn the functional programming, closure, object, inheritance and design patterns in JavaScript? Personally I would like to see more code examples because some of the books I mentioned above keep the example minimal.

(EDIT: As this post is now community effort, please help maintain and develop the following list of resources!)



On Stack Overflow


You can see great code examples of Javascript in mainstream libraries like jQuery. I've learned a lot just reading it's source code. There's nothing better than reading sources that are working in millions of websites and are concerned about best practices.

In the same vein as The Good Parts, Douglas Crockford's website has many good articles on JavaScript and OOP, such as Prototypal Inheritance, Classical Inheritance in JavaScript, etc.

My background is in C and I've picked up PHP, mySQL, HTML, CSS without too much issue.

But I'm finding Javascript/jQuery surprisingly difficult to get right. Very frustrating. Why?

  1. It seems to violate a number of traditional programming principles (e.g. variable scope)

  2. Undefined variables seem to appear out of nowhere and already have values associated with them. For example (from the jQuery docs):

    $("a").click(function(event) {
              .append('default ' + event.type + ' prevented')

    What exactly is "event"? Do I have to use this variable name? Should I just assume that this object is magically instantiated with the right stuff and I can use any of the methods list at the JQuery API?

  3. There seems to be bunch of random rules (e.g. return false to stop a default action, but sometimes this doesn't work?)

  4. Non-deterministic behavior when debugging. (e.g. I refresh the browser, try something and get result X for JS variables I'm watching in Firebug. I refresh again and I get result Y?)

  5. Very messy looking code that is hard to follow. What happens when? I'm using Firebug and Chrome Developer Tools, but I'm not getting enough visibility.

It seems like everyday there's some random JS "rule" that comes up that I've never seen before in any of my JS books or tutorials.

What do I need to do to make Javascript/jQuery more deterministic, controlled, and logical to me?

Are there any resources that explain Javascript's quirks/gotchas?


Douglas Crockford's "Javascript: The Good Parts" was an invaluable resource. Javascript plays a lot more like Lua, Lisp, or Python than C, it just happens to LOOK like C.

Link provided to Amazon; I snagged mine from O'Reilly.

Have you ever restricted yourself to using a subset of language features, and more importantly, why?

I'm curious to find out who choose to use only certain language features and avoid others in order to win big in areas such as, but not limited to, memory usage, execution speed or plain old readability and maintainability. And by doing so did it yield the expected results or did it perhaps just hamper some other aspect of producing software. Are there any cautionary tales or wild success stories out there worth sharing regarding this subject?

Douglas Crockford's book Javascript: The Good Parts is a prime example of this. He lists 'features' in javascript that should be avoided and provides alternatives that use the 'good parts' of the language.

A few of the bad parts are:

  • eval
    slower, harder to read, dangerously insecure

  • ==
    confusing and ambiguous with differently typed operands

  • with
    unpredictable results

A while ago, when I was learning Javascript, I studied Javascript: the good parts, and I particularly enjoyed the chapters on the bad and the ugly parts. Of course, I did not agree with everything, as summing up the design defects of a programming language is to a certain extent subjective - although, for instance, I guess everyone would agree that the keyword with was a mistake in Javascript. Nevertheless, I find it useful to read such reviews: even if one does not agree, there is a lot to learn.

Is there a blog entry or some book describing design mistakes for Python? For instance I guess some people would count the lack of tail call optimization a mistake; there may be other issues (or non-issues) which are worth learning about.

You asked for a link or other source, but there really isn't one. The information is spread over many different places. What really constitutes a design mistake, and do you count just syntactic and semantic issues in the language definition, or do you include pragmatic things like platform and standard library issues and specific implementation issues? You could say that Python's dynamism is a design mistake from a performance perspective, because it makes it hard to make a straightforward efficient implementation, and it makes it hard (I didn't say completely impossible) to make an IDE with code completion, refactoring, and other nice things. At the same time, you could argue for the pros of dynamic languages.

Maybe one approach to start thinking about this is to look at the language changes from Python 2.x to 3.x. Some people would of course argue that print being a function is inconvenient, while others think it's an improvement. Overall, there are not that many changes, and most of them are quite small and subtle. For example, map() and filter() return iterators instead of lists, range() behaves like xrange() used to, and dict methods like dict.keys() return views instead of lists. Then there are some changes related to integers, and one of the big changes is binary/string data handling. It's now text and data, and text is always Unicode. There are several syntactic changes, but they are more about consistency than revamping the whole language.

From this perspective, it appears that Python has been pretty well designed on the language (syntax and sematics) level since at least 2.x. You can always argue about indentation-based block syntax, but we all know that doesn't lead anywhere... ;-)

Another approach is to look at what alternative Python implementations are trying to address. Most of them address performance in some way, some address platform issues, and some add or make changes to the language itself to more efficiently solve certain kinds of tasks. Unladen swallow wants to make Python significantly faster by optimizing the runtime byte-compilation and execution stages. Stackless adds functionality for efficient, heavily threaded applications by adding constructs like microthreads and tasklets, channels to allow bidirectional tasklet communication, scheduling to run tasklets cooperatively or preemptively, and serialisation to suspend and resume tasklet execution. Jython allows using Python on the Java platform and IronPython on the .Net platform. Cython is a Python dialect which allows calling C functions and declaring C types, allowing the compiler to generate efficient C code from Cython code. Shed Skin brings implicit static typing into Python and generates C++ for standalone programs or extension modules. PyPy implements Python in a subset of Python, and changes some implementation details like adding garbage collection instead of reference counting. The purpose is to allow Python language and implementation development to become more efficient due to the higher-level language. Py V8 bridges Python and JavaScript through the V8 JavaScript engine – you could say it's solving a platform issue. Psyco is a special kind of JIT that dynamically generates special versions of the running code for the data that is currently being handled, which can give speedups for your Python code without having to write optimised C modules.

Of these, something can be said about the current state of Python by looking at PEP-3146 which outlines how Unladen Swallow would be merged into CPython. This PEP is accepted and is thus the Python developers' judgement of what is the most feasible direction to take at the moment. Note it addresses performance, not the language per se.

So really I would say that Python's main design problems are in the performance domain – but these are basically the same challenges that any dynamic language has to face, and the Python family of languages and implementations are trying to address the issues. As for outright design mistakes like the ones listed in Javascript: the good parts, I think the meaning of "mistake" needs to be more explicitly defined, but you may want to check out the following for thoughts and opinions:

At work, we place braces on the next line, but at home, I do the opposite. Which one do you prefer? (K&R vs OTBS)

function something() {
    // ...

function something()
    // ...

A lot of JavaScript libraries seem to use the OTBS (one true brace style). I'd like to follow them for consistence among other JavaScript projects, but doesn't K&R style look more readable?

Note: We know the problem with return and braces in JavaScript, that will always be an exception. However, that is only a single case.

Douglas Crockford gives a reason for choosing the K&R style1:

I always use the K&R style, putting the { at the end of a line instead of the front, because it avoids a horrible design blunder in JavaScript's return statement.

The blunder he is referring to is how JavaScript handles the return statement differently in the following two scenarios:

return {
   'status': 'ok'

... and:

   'status': 'ok'

The first one will return an object with a status property, while the latter will return undefined because of semicolon insertion.

1 Douglas Crockford: JavaScript: The Good Parts: Style (page 96) - ISBN: 978-0596517748.

What it a good starting point for learning javascript? I'm a well versed C and Java programmer and I have some decent experience in C++, so I'm looking for a few suggestions:

  • What is some good reference material?
  • Is there a particular IDE/editor that is worth looking at? I use vim for C/C++ development and I used IntelliJ Idea for Java. I'm limited to either Linux or Mac based tools.
  • How do you debug javascript code? Is it just a series of alert()'s?
  • Am I required to run a webserver to test javascript, or can I load the .js file directly? If so, are there limitations to this approach?
  • Any other advice for a javascript beginner?


I think that there are a lot of good answers here with a lot of good suggestions, however, I also disagree with most of the answers that say "start learning with jQuery." I'm passionately against learning a framework for a language before learning the language in which the framework is implemented. You're automatically creating a level of abstraction for yourself. Knowing the language prior to learning jQuery or any other framework will help enhance your ability to understand what the framework is doing, how to write better code, and how to implement a feature into the framework that you wish was there but isn't.

With that said, here's a set of resources that I have found to be extremely helpful in learning JavaScript (some of them have already been mentioned):



  • Head First JavaScript. This book is really good at getting you up to speed on the synxtax of JavaScript and what it's capable of without getting you bogged down into the technical implementations of the language. It also helps connect the dots between JavaScript and the DOM.
  • JavaScript: The Good Parts At approximately 150 pages, this is a relatively easy read that explains the good parts of the language and the bad parts of the language. This book will make you a better JavaScript programmer by staying away from the 'awful parts' of the language while also helping you to stick to the good parts and writing more clear, maintainable, expressive code.



  • jQuery. This seems to be the favorite around Stack Overflow. I've done some work with it and it really is a good library.
  • Prototype. This is another library that I enjoy using. It's class creation and inheritance support are nice as well as its API.


  • Aptana Studio is the best JavaScript IDE that I've ever used. It has all of the features you'd expect from a powerful IDE with respect to JavaScript.
  • Notepad. You don't really need anything other than a web browser and text editor for writing JavaScript, so if this floats your boat, then go for it.

Yes, there are more websites, books, and videos that can help you get started, but for someone that has a programming background, I can't imagine that picking up JavaScript would be utterly difficult. Additionally, there are other frameworks available, but jQuery and Prototype are the ones with which I'm most familiar and have found them to be really useful.

If you're looking for a reference book on the language, JavaScript: The Definitive Guide is the book to get.

Visual Studio is by far the best Javascript debugging environment, but that's not useful to you if you're limited to Linux & Mac. On that platform, I would agree with the suggestions for Firefox with Firebug and Venkman.

What's the best and most efficient book to learn JavaScript?

I think I've read them all. Here's the dark sheep. This one came out of left field. I was surprised at how good it is.

JavaScript: The Missing Manual

alt text

The other books are great. But for actually learning the language, I think this one wins hands down.

after the basics, every Javascript developer must read this:
Douglas Crockford: JavaScript: The Good Parts

ppk on JavaScript was really great. His website is also filled with tons of useful information including lots on browser incompatibilities.

alt text

I've been reading Douglas Crockford's JavaScript: The Good Parts, and I came across this weird example that doesn't make sense to me:

'' == '0'           // false
0 == ''             // true
0 == '0'            // true

false == undefined  // false
false == null       // false
null == undefined   // true

The author also goes on to mention "to never use == and !=. Instead, always use === and !==". However, he doesn't explain why the above behavior is exhibited? So my question is, why are the above results as they are? Isn't transitivity considered in JavaScript?

'' == '0' // false

The left hand side is an empty string, and the right hand side is a string with one character. They are false because it is making a comparison between two un identical strings (thanks Niall).

0 == '' // true

Hence, why this one is true, because 0 is falsy and the empty string is falsy.

0 == '0' // true

This one is a bit trickier. The spec states that if the operands are a string and a number, then coerce the string to number. '0' becomes 0. Thanks smfoote.

false == undefined // false

The value undefined is special in JavaScript and is not equal to anything else except null. However, it is falsy.

false == null // false

Again, null is special. It is only equal to undefined. It is also falsy.

null == undefined // true

null and undefined are similar, but not the same. null means nothing, whilst undefined is the value for a variable not set or not existing. It would kind of make sense that their values would be considered equal.

If you want to be really confused, check this...

'\n\r\t' == 0

A string consisting only of whitespace is considered equal to 0.

Douglas Crockford makes a lot of recommendations, but you don't have to take them as gospel. :)

T.J. Crowder makes an excellent suggestion of studying the ECMAScript Language Specification to know the whole story behind these equality tests.

Further Reading?

The spec.

yolpo (on falsy values)

Having trouble understanding why JSLint is surprised by my use of this in the following code:

function testConstr (x) {
    'use strict';
    this.joker = "Whyyy sooo seriousss?";
    this.x = x;

For both property assignments, JSLint says: Unexpected 'this'. How do I correct my code?

So in other words, JSLint doesn't automatically expect me to use a constructor pattern?

You know, I think you're right. Your question bugged me, and I signed up for Crockford's JSLint discussion group and asked. He replied, but ignored the solution I'm going to present, below, which I think means that it's okay, the same way JSLint doesn't complain if something passes muster.

(I'm still waiting for an updated Good Parts, though.)

That caveat aside, here's what I'd suggest doing for OO JavaScript that passes Beta JSLint (as of today, anyhow).

I'm going to rewrite an example from MDN's page, "Introduction to Object Oriented Programming," which itself uses this liberally.

With this

Here's the original, unlinted MDN example from the section linked, above:

var Person = function (firstName) {
  this.firstName = firstName;

Person.prototype.sayHello = function() {
  console.log("Hello, I'm " + this.firstName);

var person1 = new Person("Alice");
var person2 = new Person("Bob");

// call the Person sayHello method.
person1.sayHello(); // logs "Hello, I'm Alice"
person2.sayHello(); // logs "Hello, I'm Bob"

That follows the conventions we know and love.

Without this

It's pretty easy to figure out how to make "constructors" that don't follow that pattern, but we lose use of prototype, if I'm not missing something, and have to include all of the object's methods in our constructor that we want all of our Peeps to share.

/*jslint white:true, devel:true */
var Peep = function(firstName) {
    "use strict";
    var peep = {};
    peep.firstName = firstName;

    peep.innerSayHello = function() {
        console.log("Hello, I'm " + peep.firstName + ".");

    return peep;

var peep1 = new Peep("Bob");
var peep2 = new Peep("Doug");


So there's a lintable alternative. That does, other than the return peep; and the inner definition of methods, make JavaScript act like many OO-first languages you might encounter. It's not wrong, at least.

Not having access to prototype isn't horrible; it's really bad news to change prototype somewhere that's not right beside the constructor, as your code would go to spaghetti. "Some Persons have sayGoodbye() and some don't, depending on if we'd amended the prototype at the point of their construction." That's awful. So this alternative convention has its advantages.

You can still, of course, add functions to a single instantiation of Peep later, but I'm not sure how you'd access firstName without using this, so perhaps he wants us to stop munging objects after construction.

person1.sayGoodbye = function (other) { 
    console.log("Goodbye, " + other + "."); 

(I mean, we could also still monkey-patch Peep to change it mid-process, but that's horrible, stupid programming. Usually.)

Inheritance (without this)

And inheritance is easy enough, I think.

var PeepWithGoodbye = function (firstName) {
    "use strict";
    var peepWithGoodbye = new Peep(firstName);

    peepWithGoodbye.innerSayGoodbye = function (otherPeep) {
        if (undefined === otherPeep) {
            otherPeep = { firstName: "you" };
        console.log("This is " + firstName 
            + " saying goodbye to " + otherPeep.firstName + ".");

    return peepWithGoodbye;

var pwg1 = new PeepWithGoodbye("Fred");
pwg1.innerSayHello();           // Hello, I'm Fred.
pwg1.innerSayGoodbye(peep1);    // This is Fred saying goodbye to Bob.
pwg1.innerSayGoodbye();         // This is Fred saying goodbye to you.

EDIT: See also this answer where the asker later found Crockford's suggested means of creating OO javascript. I'm trying to convince that guy to delete that Q&A and move the A here. If he doesn't, I'll probably add his stuff and community wiki it here.

I'm a self learner in javascript and I'm currently following the lessons in the book named "Beginning javascript 3rd edition" by Paul Wilton.

So far I've advanced myself towards chapter 4: Javascript - An object based language, and I did follow and solve the exercises provided inside the book. I tried to write a calculator myself, and by modifying and changing the code, every time I learn something new to enhance it.

How can I become good in javascript coding? Is there any special approach? Is there any concept or things I should learn first? What kind of study/career path should I follow for javascript? Anything I should be aware of?

I really have the courage to continue learning javascript, I just need some guidance.

I don't mind any expert opinion given, or pointing out any mistakes regarding this question, as I know that through my mistakes, I always learn something.

  1. Program a lot
  2. Read JavaScript: The Good Parts
  3. Use JsLint!
  4. Go to 1

I think that Object-Oriented JavaScript by Stoyan Stefanov is an amazing book, but that could just be me.

var myJSON = {  
              "list1" : [ "1", "2" ],
              "list2" : [ "a", "b" ],
              "list3" : [ { "key1" : "value1" }, { "key2" : "value2" } ],
              "not_a_list" : "11"

How do I dynamically build this JSON structure in javascript? Google tells me to use use some push command, but I've only found specific cases. So what do I write to enter data to "listX" and "not_a_list". Appending as well as creating a new list. The whole procedure begninning with:

var myJSON = {};

First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".

With that pedantry out of the way, I think that you're asking how to set object and array properties.

// make an empty object
var myObject = {};

// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];

// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';

myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
// or unshift them on to the beginning
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';

myObject.not_a_list = '11';

That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.

The following code illustrates an object literal being assigned, but with no semicolon afterwards:

var literal = {
    say: function(msg) { alert(msg); }
literal.say("hello world!");

This appears to be legal, and doesn't issue a warning (at least in FireFox 3). Is this completely legal, or is there a strict version of JavaScript where this is not allowed? I'm wondering in particular for future compatibility issues... I would like to be writing "correct" JavaScript, so if technically I need to use the semicolon, I would like to be using it.

Javascript interpreters do something called "semicolon insertion", so if a line without a semicolon is valid, a semicolon will quietly be added to the end of the statement and no error will occur.

var foo = 'bar'
// Valid, foo now contains 'bar'
var bas = 
    { prop: 'yay!' }
// Valid, bas now contains object with property 'prop' containing 'yay!'
var zeb = 
switch (zeb) {
// Invalid, because the lines following 'var zeb =' aren't an assignable value

Not too complicated and at least an error gets thrown when something is clearly not right. But there are cases where an error is not thrown but the statements are not executed as intended due to semicolon insertion. Consider a function that is supposed to return an object:

return {
    prop: 'yay!'
// The object literal gets returned as expected and all is well
    prop: 'nay!'
// Oops! return by itself is a perfectly valid statement, so a semicolon 
// is inserted and undefined is unexpectedly returned, rather than the object 
// literal. Note that no error occurred. 

Bugs like this can be maddeningly difficult to hunt down and while you can't ensure this never happens (since there's no way I know of to turn off semicolon insertion), these sorts of bugs are easier to identify when you make your intentions clear by consistently using semicolons. That and explicitly adding semicolons is generally considered good style.

I was first made aware of this insidious little possibility when reading Douglas Crockford's superb and succinct book "Javascript: The Good Parts". I highly recommend it.

I am developing my first ASP.NET MVC application and I beleive that Script# can help me a lot. But it cannot find the resource necessary to support my development.

I could not find The codeplex site; There is only one manual, which is very good, but it is not enough; I could find very few tutorials; I know that Script# was used to develop ASP.NET MVC scripts and that the source of MVC distributes the library.

But it seems that it is used only internally in Microsoft.

Where can I find other resources???

Do you really think that Script# will be continued and new versions will be deployed and it should be used by third-party projetcs ???

Thanks in advance

Don't be afraid of Javascript, it's a beautiful and powerful language. And with frameworks like jQuery, Prototype and Dojo, DOM manipulation and AJAX are greatly simplified and cross-browser issues are mostly history.

About Script#, I agree with this answer by mcintyre321. Last release over a year ago + closed source = no go for me.

UPDATE Jan/2010: there have been new Script# releases since the original writing of this answer. It's still closed-source but the author mentions open sourcing it after 1.0

UPDATE May 2011: Script# is now open source.

over the last couple of years I've seen jquery grow leaps and bounds. And every time I look at some jquery code I feel there is something I am missing which I need to learn. I've given their documentation a try, and it seems to be ok for basic stuff.

Can you guys suggest a good jquery book that might help? I'm looking for something that doesnt go much in depth into the theory part of jquery but actually does and shows examples of how to do all the cool stuff.

Back in the days when I was in school, I never cared for JS, CSS, HTML ...but now that after 3 years after school I see myself doing a lot of server side web development. I want to learn these technologies.

  1. Learn the language first: Javascript The Definitive Guide, 5th Edition

  2. Learn jQuery: jQuery in Action

I agree with Mark Hurd below. Learn Javascript first.

The first book that gave me "aha- this is amazing" is DOM Scripting: Web Design with JavaScript and the Document Object Model

Once you get the basics of that, what jQuery does will come more naturally to you and it will seem easy.

These books are all (co) authored by John Resig who also wrote jQuery itself.

For JS in general, I've also heard very good things about this: JavaScript: The Good Parts by Douglas Crockford who works for Yahoo!.

Crockford and Resig both have free and comprehensive videos at the YUI theater. These three are good for a broad overview of general JS:

  • Douglas Crockford — The JavaScript Programming Language
  • Douglas Crockford — Advanced JavaScript
  • Douglas Crockford — An Inconvenient API: The Theory of the DOM

I have been programming in PHP and C# for a long time, but I have done very little Javascript. For server side programming I use MVC, which is very nice and my code is neatly organized.

Now, for Javascript, when I write code, I usually screw things up. It becomes something like spaghetti code. I don't know how to organize my code.

Can anyone please help me with any resource, book, or anything which might help with writing neat and organized Javascript code?

Thanks in advance.

JavaScript: The Good Parts

Plus any Crockford videos from YUI Theater.

You mention that you have been programming in PHP and C# for a long time. Take your code organization experience and apply it to your javascript.

Couple of frameworks

Google's Closure tools -

If Google uses it to organize Gmail and Google Docs, then it should work for most large applications.

Also, Yahoo! YUI is good too -

And backbone.js (not as "big" as Google or Yahoo) -

Decent Book

For me, writing javascript unit test helps me stay organized -

Test-Driven JavaScript Development

I think the following code will make the question clear.

// My class
var Class = function() { console.log("Constructor"); };
Class.prototype = { method: function() { console.log("Method");} }

// Creating an instance with new
var object1 = new Class();
console.log("New returned", object1);

// How to write a factory which can't use the new keyword?
function factory(clazz) {
    // Assume this function can't see "Class", but only sees its parameter "clazz".
    return; // Calls the constructor, but no new object is created
    return;  // Doesn't work because there is new() method

var object2 = factory(Class);
console.log("Factory returned", object2);

Because JavaScript doesn't have classes, let me reword your question: How to create a new object based on an existing object without using the new keyword?

Here is a method that doesn't use "new". It's not strictly a "new instance of" but it's the only way I could think of that doesn't use "new" (and doesn't use any ECMAScript 5 features).

//a very basic version that doesn't use 'new'
function factory(clazz) {
    var o = {};
    for (var prop in clazz) {
        o[prop] = clazz[prop];
    return o;

var clazz = { prop1: "hello clazz" };
var testObj1 = factory(clazz);
console.log(testObj1.prop1);    //"hello clazz" 

You could get fancy and set the prototype, but then you get into cross-browser issues and I'm trying to keep this simple. Also you may want to use "hasOwnProperty" to filter which properties you add to the new object.

There are other ways that use "new" but sort of hide it. Here is one that borrows from the Object.create function in JavaScript: The Good Parts by Douglas Crockford:

//Another version the does use 'new' but in a limited sense
function factory(clazz) {
    var F = function() {};
    F.prototype = clazz;
    return new F();

var orig = { prop1: "hello orig" };
var testObj2 = factory(orig);
console.log(testObj2.prop1);  //"hello orig"

EcmaScript 5 has the Object.create method which will do this much better but is only supported in newer browsers (e.g., IE9, FF4), but you can use a polyfill (something that fills in the cracks), such as ES5 Shim, to get an implementation for older browsers. (See John Resig's article on new ES5 features including Object.create).

In ES5 you can do it like this:

//using Object.create - doesn't use "new"
var baseObj = { prop1: "hello base" };
var testObj3 = Object.create(baseObj);

I hope that helps

Rails is a very great backend framework keeping everything clean and structured.

I guess that you all have thought about doing the same for the frontend.

  • Sproutcore
  • Cappuccino

Do you use one of thes MVC javascript frameworks for the frontend with Rails?

In case you do, do you feel satisfied with it?

How did you code before and how has it changed?

Isn't Sproutcore more suitable for Rails cause it uses js+css+html which Rails also does. In Cappuccino you don't use either of these.

Share your thoughts and experience cause I'm all green to this field and don't know which one I should use with Rails.

I just know I better have a MVC framework on the frontend to get DRY-structure and best practices.

When looking at MVC frameworks at work, we considered SproutCore and Cappuccino. They both draw an enormous amount of inspiration from Apple's Cocoa framework and Objective C.

We chose to use SproutCore because:

  • It leverages JavaScript in a manner that is aligned with Douglas Crockford's view of JavaScript as described in JavaScript: the Good Parts.
  • Good MVC framework that produces fast applications.
  • Good community backing the project. Charles Jolley, SproutCore's daddy, worked at Apple until recently, and now is working full time on SproutCore. Apple contributes a lot of code to SproutCore's base, and is making good use out of it, as evidenced by the fact that was build using SproutCore.
  • SproutCore was designed for very heavy applications that have thousands of elements, using optimized techniques like recycling list items in large lists à la Google Wave or Google Maps.

We didn't choose Cappuccino because:

  • It creates a different language in which you run your application in. This is non-intuitive, makes you think in Objective J, which does provide benefits in the fact that you don't bring nasty JavaScript hacky habits, but neglects the fact that JavaScript is beautiful, extensible, and powerful. (I am in no way 'slamming' Objective J, just providing insight to the fact that you run JavaScript in the browser, not Objective J. If you do run another language in your browser, it can get confusing since you're interpreting an interpreted language using an interpreted language.)
  • However, Objective J and Cappuccino make beautiful applications and leverage Objective C's language architecture, which is a good model to look at in the world of MVC.

(Keep in mind, I don't have a great deal of experience in Cappuccino and Objective J, so if I make broad and naïve claims, tell me!)

You need to look more at what you want as a frontend framework rather than what "works best" with Rails. Both frameworks are good. We chose SproutCore because it fit our needs that we had for our application more, and fit our ideology.

From experience from wading through SproutCore's source, I can say that it's fairly independent of the server implementation that you're using. We use Prosody, a BOSH server written in Lua. You want to use Rails. SproutCore offers this out of the box:

  • DataSources for Rails deploys. FYI- DataStores are SproutCore's low-end model layer for hooking into web services. This is most likely the meeting point between your SproutCore app and your Rails app. SproutCore is not really meant to run in Rails, but you certainly could do it!
  • DataStore for RESTful Rails services. Or any REST API for that matter. It also allows for server-side push, if you have a need for that.

As for your DRY requirement- that's all up to you! You can leverage the framework to make your code independent and DRY, or have tight dependencies and repeat. Either framework is good, it just depends on your needs. Don't be nervous- dive in and get to know the communities and what's going on in each of them! We don't bite... too much.

I'm reading Douglas Crockfords Javascript: The Good Parts, I just finished the regular expressions chapter. In this chapter he calls JavaScript's \b, positive lookahead (?=) and negative lookahead (?!) "not a good part"

He explains the reason for \b being not good (it uses \w for word boundary finding, and \w fails for any language that uses unicode characters), and that looks like a very good reason to me.

Unfortunately, the reason for positive and negative lookahead being not good is left out, and I cannot come up with one. Mastering Regular Expressions showed me the power that comes with lookahead (and of course explains the issues it brings with it), but I can't really think of anything that would qualify it as "not a good part".

Can anyone explain why JavaScript (positive|negative) lookahead or (positive|negative) lookahead in general should be considered "not good"?

It seems I'm not the only one with this question: one and two.

Maybe it's because of Internet Explorer's perpetually buggy implementation of lookaheads. For anyone authoring a book about JavaScript, any feature that doesn't work in IE might as well not exist.

I'm reading through Douglas Crockford's JavaScript: The Good Parts, and I'm at the point where he defines a fade function. Part of this code boils down to this:

var level = 1;
var hex = level.toString(16);

So I run this in my browser's console to see what I get....

var level = 1;

Hey, it returns "1"... Fabuloso! Wunderbar!

Then to be cheeky, I try this to see what I get...


And I get

SyntaxError: Unexpected token ILLEGAL

What the what? If level is a variable equal to 1, and running this method on level works fine, then why doesn't running this method on the actual number 1 work? I tried a similar experiment with the toPrecision() method and that worked fine in both cases. What's the issue here? Is this another one of those inherent flaws in the JavaScript implementation, or am I missing something? I am testing in Google Chrome.

Related: Stack Overflow question Why don't number literals have access to Number methods?.

It's just a language grammar limitation.

Since 1. is a legal literal number (and 1.t is not) the tokeniser will split this into the following tokens:


And that's an illegal sequence of tokens. It's object method, instead of object . method.

In the working versions in @Joey's answer, the braces prevent the tokenizer from treating the dot as part of the number literal instead of as a separate token, as does writing:




since the tokenizer knows that the second dot must be a token on its own, and not part of the number literal.

I am curious as what else the new keyword does in the background apart from changing what the this scope refers too.

For example if we compare using the new keyword to make a function set properties and methods on an object to just making a function return a new object, is there anything extra that the new object does?

And which is preferred if I don't wish to create multiple objects from the function constructor

var foo2 = function () {
  var temp = "test";

  return {
    getLol: function () {
      return temp;

    setLol: function(value) {
      temp = value;


var foo = new function () {
  var temp = "test";

  this.getLol = function () {
    return temp;

  this.setLol = function(value) {
    temp = value;

The firebug profiler tells me using the new keyword is slightly faster (2ms instead of 3ms), on large objects is new still significantly faster?


Another matter is on really large object constructors is having a return at the bottom of the function (It will have a large amount of local functions) or having a few = ... at the top of the function more readable? What is considered a good convention?

var MAIN = newfunction() { = ...

    // Lots of code

var MAIN2  = function() {
    // Lots of code

    return {
        bar: ...

Quoting Douglas Crockford from the Good Parts book (page 47), to answer the title of this question:

If the new operator were a method instead of an operator, it could be implemented like this:

Function.method('new', function () {

   // Create a new object that inherits from the 
   // constructor's prototype.

   var that = Object.create(this.prototype);

   // Invoke the constructor, binding -this- to
   // the new object.

   var other = this.apply(that, arguments);

   // If its return value isn't an object,
   // substitute the new object.

   return (typeof other === 'object' && other) || that;

The Function.method method is implemented as follows. This adds an instance method to a class (Source):

Function.prototype.method = function (name, func) {
   this.prototype[name] = func;
   return this;

Further reading:

From someone with few experience in JS, what do you recommend for learning Node.js?

I read a lot in the forum about event driven, non-blocking , async, callbacks, etc but I don't know what's that!

Where can I learn the basics in order to understand all that terms and in the future, node.js?


«Javascript: The Good Parts» is one of the best books ever for learning the ins and outs of the language and not just DOM stuff.

I am a .NET webdev using ASP.NET, C# etc... I "learned" javascript in college 5+ years ago and can do basic jobs with it. But I wonder if it is useful to become proficient in it.

Why should I learn Javascript? Is it more advantageous then learning JQuery or a different library?

Yes, absolutely you should learn JavaScript if you are doing web development. I highly recommend JavaScript: The Good Parts, by Doug Crockford. And, JQuery is a great framework to use (this site uses it) -- it kind of depends on what you are trying to do -- YUI and ExtJS are also very nice.

I recommend Jeremy Keith's books: DOM Scripting and Bulletproof Ajax. After you become more fluent in JS I would recommend a JS library(I use jQuery, but that is not important).

JS is important to learn. You cannot use a framework without the proper understanding of how it works. That is doing things backwards.

I am trying to do this, I'm a full time front-end dev and am aware that I am yet to achieve this. When I am referring to OOP skills I am referring to understanding and being familiar with concepts like inheritance, polymorphism, encapsulation, abstraction. I am aware that it may be more likely to achieve what I'm after by focusing on another language in my spare time. This is the plan, but I'd be really intrigued to hear if anybody has managed to achieve this purely through JavaScript and how you did it.

It'd be even better to hear from strong OOP developers from who use different programming languages to know if they have worked with developers who have managed to achieve this.


Just in case people are wondering where I went from this -

  • I've taken a closer look at what prototypal inheritance means and how to use it better.

  • I've decided to spend more time properly learning ruby (could be any language that is class based) in my spare time.

  • I've decided to experiment (nonchalantly) with different languages so that I can gain not the intricacies/exact syntax of them, but more of an overview of how they approach OOP. I've started with Self, Scheme is next on my list.

Thanks a lot for the really helpful answers.

There's no reason you can't develop strong object-oriented skills via Javascript - but Javascript is a prototype-based object-oriented language, which is quite different from other mainstream object-oriented languages (C++, Java, etc.), which are class-based.

You should familiarize yourself with both models as soon as you can (once you've mastered the basics of javascript), so you can learn from discussions about class-based models without too much friction.

Finally, in case you aren't already familiar with Douglas Crockford, I highly recommend visiting his site, reading his article JavaScript: The World's Most Misunderstood Programming Language, then reading his book Javascript: the Good Parts.

Possible Duplicate:
Why avoid increment (“++”) and decrement (“--”) operators in JavaScript?

I've heard in a few places that it is not recommended to use ++ & -- in javascript, and we should be using += 1 or -= 1 instead. Can anyone clarify why for me?

The only time I saw these operators discouraged was in Douglas Crockford's JavaScript: The Good Parts book.

Quoting from the "Bad Parts" Appendix:

The increment and decrement operators make it possible to write in an extremely terse style. In languages such as C, they make it possible to write one-liners that could do string copies:

for (p = src, q = dest; !*p; p++, q++) *q = *p;

They also encourage a programming style that, as it turns out, is reckless. Most of the buffer overrun bugs that created terrible security vulnerabilities were due to code like this.

In my own practice, I observed that when I used ++ and --, my code tended to be too tight, too cryptic. So, as a matter of discipline, I don't use them anymore. I think that as a result, my coding style has become clearer.

In addition, quoting from the JSLint documentation (the code quality tool which he has written):

The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by encouraging excessive trickiness. They are second only to faulty architecture in enabling to viruses and other security menaces. There is a plusplus option that prohibits the use of these operators.

He really doesn't fancy these operators... But come on! I think we can still use the ++ and -- operators without writing cryptic code. I use them, and I like them. Everyone uses them.

Note that although JSLint has the option to disallow these operators, this option is not enabled by default.

Before asking my question, let me give a disclaimer. I know what var does, I know about block scope, and I know about variable hoisting. I'm not looking for answers on those topics.

I'm simply wondering if there is a functional, memory, or performance cost to using a variable declaration on the same variable more than once within a function.

Here is an example:

function foo() {
  var i = 0;
  while (i++ < 10) {
    var j = i * i;

The previous could just have easily been written with the j variabled declared at the top:

function foo() {
  var i = 0, j;
  while (i++ < 10) {
    j = i * i;

I'm wondering if there is any actual difference between these two methods. In other words, does the var keyword do anything other than establish scope?

Reasons I've heard to prefer the second method:

  1. The first method gives the appearance of block scope when it's actually function scoped.
  2. Variable declarations are hoisted to the top of the scope, so that's where they should be defined.

I consider these reasons to be good but primarily stylistic. Are there other reasons that have more to do with functionality, memory allocation, performance, etc.?

In JavaScript - The Good Parts Douglas Crockford suggests that by using the second method and declaring your variables at the top of their scope you will more easily avoid scope bugs.

These are often caused by for loops, and can be extremely difficult to track down, as no errors will be raised. For example;

function() {
  for ( var i = 0; i < 10; i++ ) {
    // do something 10 times
    for ( var i = 0; i < 5; i++ ) {
      // do something 5 times

When the variables are hoisted we end up with only one i. And thus the second loop overwrites the value, giving us an endless loop.

You can also get some bizarre results when dealing with function hoisting. Take this example:

(function() {
  var condition = true;
  if(condition) {
    function f() { console.log('A'); };
  } else {
    function f() { console.log('B'); };
  f(); // will print 'B'

This is because function bodies are hoisted and the second function overwrites the first.

Because searching for bugs like this is hard and regardless of any performance issues (I rarely care about a couple of microseconds), I always declare my variables at the top of the scope.

I'm working on a project and I'm really trying to write object-oriented JavaScript code. I have just started reading Douglas Crockford's JavaScript: The Good Parts and I'm quickly beginning to realize that writing Java-esque OOP in JavaScript will be a difficult task.

Thus far, I've written something like the following...

// index.html
$(document).ready(function() {


// this is in a different js file
$.fn.SetUpElements = function() {

    // do stuff here

// this is in yet another different js file
$.fn.UpdateElement = function() {

   // do stuff here
   var element = new Element(id, name); // continue doing work

function Element(id, name) {

   var id = id;
   var name = name;

   // other stuff

... the idea being that I want objects/functions to be refactored and decoupled as much as possible; I want to reuse as much code as I can. I've spread a lot of my code across different .js files with the intention of grouping specific relevant code together, much like if you would write different classes in Java.

As I've been learning more about jQuery, I realized that the notation $ = function() { ... }; is actually adding this foo function to the prototype of all jQuery objects. Is this something I should be doing? Am I misusing jQuery somehow?

I would appreciate suggestions on how to improve my approach to OOP in JavaScript and I would love to see references to sources/tutorials/articles/etc... that discuss this topic. Please feel free to provide feedback even if an answer has been selected. I am looking for your advice... this is why I posted :)

** Note: I'm not developing a jQuery plugin. I'm developing a web app and heavily making use of jQuery.

I would say the first way you're creating methods is a misuse of jQuery. The syntax is generally reserved for functions that act upon a DOM element but you're using them as static functions, by using an empty jQuery object.

If you want to create static functions under the jQuery namespace, you can do: = function(){};

then call it via:;

instead of: = function(){};

which allows you to do:


In terms of OOP. there are many different approaches (module pattern, prototype, factory...). The way I generally approach it, is create a Class as a static function, then invoking it with the keyword new

    var undefined;

    $.ClassName = function(options){
        var self = this;
        var cfg = $.extend(true, {}, this.defaults, options);

        // ********************
        // start:private
        // ********************
        function _init(){


        // ********************
        // start:public
        // ********************
        this.methodName = function(){



    $.ClassName.prototype.defaults = {};

In terms of reusing functionality, there's a threshold after which decoupling is more detrimental than anything. Make sure you keep the right balance of modularity and organization.

I am currently developing apps for the iPhone and iPad with Objective-C. I found some code related to using JavaScript in the iPhone.

  1. Can we create apps more easily and accurately with the help of JavaScript?
  2. Does Apple approve apps created at least partially with JavaScript?
  3. How should one begin learning JavaScript?
  4. Are there any tutorials that can help me to understand and learn JavaScript, particularly for iPhone/iPad programming?

Web Apps

Web Apps are highly optimized special websites that are accessed from any device but still look and feel like a full-fledged application. An early example would be GMail. Here is an old blog post by jQuery's John Resig on early web app development.

1. Can we create apps more easily and accurately with the help of Javascript?

This is a bit mis-leading as the intents may be different. The goal of web apps to hit the widest possible audience with minimal effort, however, you are restricted to non-native functions.

Native functions include use of the device hardware such as camera, gps, touching other apps, notifications etc. There are several libraries that provide a wrapper around your web app to expose these underlying calls but then you must do that for each device. Libraries include: Phonegap, Titanium.

2. Does Apple approve apps created at least partially with JavaScript?

Most certainly! They even have a special section. With most webapps it is just a bookmarklet the user drags to their home screen for quick access. If you want to do the true app in the store you will need a wrapper library as mentioned before to package your app together.

3. How should one begin learning JavaScript?

Out of scope for this question, but Douglas Crockford is one of the better teachers, he has a multi-part video series as well as a book to get you learning the "good parts".

4. Are there any tutorials that can help me to understand and learn JavaScript, particularly for iPhone/iPad programming?

Honestly, it would best to learn javascript first, as it is a prototypical object based puzzle then worry about how to utilize the various frameworks for best mobile performance.

Adding 5. What are some javascript mobile frameworks?

These are just the most common but I would browse each of them a bit as jQuery, dojo and sencha have different approaches on how javascript should be used.

I am trying to understand the internals of how jquery framework is written and finding it hard to understand the code.

Does anyone have any suggestions regarding a good way to get started.

Thanks for all the useful input. Editing the topic since I had limited space for adding individual comments. I have written a lot of basic javascript code. I know basic DOM, have used event handlers, know CSS basics. I have read about many of the topics you have mentioned and I am familiar with it although not an expert and have not coded some of the advanced topics like closures. Here are the books I have used so far Head first javascript - good in the beginning as a starter. Books my friends have recommended and I use regularly are Javascript - The Definitive Guide, Javascript - The good parts (I read this a while ago and it was hard for me at the time). My friend just recommended Secrets of Javascript Ninja - John Resig. Seems like a good one. I ordered the Javascript Design patterns book you recommend last week

I have read the you pointed me to. I will checkout some of the other resources you pointed me to.

Let me think a little more regarding if I want to do a little more reading before I post specific questions I have on jquery.

Thanks Susan

To comprehend the actual source would require some degree of Javascript knowledge - If you don't already know what's going on then you basically need to learn more Javascript.

Key things to learn:

  • Prototypal inheritance ( the inheritance used in ECMAScript, the core language on which Javascript is based upon )
  • Lambdas ( inline functions )
  • Closures ( outer variables from outer scope accessible from inner functions )
  • Regular expressions ( used for matching the selector strings fed to jQuery )
  • DOM ( The DOM API which is used to interact with markup languages )

When learning, use Firebug so you can evaluate your expressions interactively and immediately see what's going on

An excellent free resource for learning that I would recommend:

If you're a beginner to DOM Scripting/Javascript:

If you're intermediate level:

If you're past intermediate level and want to be an expert:

Other technical references:

If you have specific questions about a certain code snippet just ask here. Another resource that I can recommend for more advanced questions would be the jQuery mailing list or irc:// where jresig hangs out himself and comes by and answers questions. There are other guru ops who reside there like ajpiano/paulirish/nlogax.

I have the following code:

// Creates a timer to check for elements popping into the dom            
timer = setInterval(function ()
    for (p in pixelTypes)
}, 10);

// Add Document finished callback.
$(document).ready(function ()
    // Document is loaded, so stop trying to find new pixels

In Firefox, it works great, but in IE6, I get a "Object Expected" error on the $(document).ready line.

I can't figure out what would cause IE6 to not recognize it, jquery is fully loaded by this point.

Is this a known issue?

Just a few pointers for anyone that's interested:

$(document).ready(function() {...}); and $(function() {...}); means exactly the same thing. The latter is a shorthand for the former.

If you develop for a large site, using multiple Javascript libraries, or you develop plugins meant to be compatible with other peoples work, you can not trust the dollar sign ($) to be associated with the jQuery object. Use the following notation to be on the safe side:

(function($) { [your code here] })(jQuery);

This passes jQuery into a self-executing function, and associates $ with the jQuery object inside this function. Then it does not matter what the $ represents outside of your function.

To get back to your question, have you checked whether the timer variable is assigned when you get the error? I believe the browser will see the $(document).ready(function() {...}); all as one line, so if you have some kind of debugger that tells you that's the offending line, it might be the timer variable...

Last thing: In Javascript, it is not correct to place open curly braces on a new line. This can cause really bad errors due to Javascripts semicolon-insertion. For further info, read Douglas Crockford's Javascript: The good parts:

Anyway, really hope I didn't upset anyone. Hope you solve the problem!

EDIT: I'm not sure if this is what robertz meant by fully qualified, but as far as I know, when a URL is fully qualified it means no parts are missing, ie. it's an absolute URL starting with http:// or https:// (or some other protocol). Please correct me if I'm wrong!

I'm using the Raphael JS library, and I'm trying to figure out how to make a point appear on screen, then disappear.

I use a for loop to create the points, and then I make them fade in. Is there a way that they can also fade out, and I can remove them?

I'm quite new to Javascript, so I don't know the best strategy for dealing with this. I could not see how to to this in the Raphael documentation.

<!DOCTYPE html>
<html lang="en">
        <meta charset="utf-8">
        <title>blink point</title>        
        <script src="js/raphael.js"></script> 
        <!--<script src=""></script>-->
        <script type="text/javascript">
        window.onload = function () {

            //Point Array
            pointList = new Array ();

            // Create Canvas
            var r = Raphael(10, 50, 600, 600);            

            // Make a 'group' of points
            for( i=0; i<20; i++){   

                    //Create Point            
                    pointList[i] =*i, 10*i,5);
                    pointList[i].attr({stroke: "none", fill: "#999", opacity: 0});

                    //Fade in   
                    pointList[i].animate({opacity: 1}, 1000 );  


            // Remove points, starting with the first
            for( i=0; i<20; i++){           

                    //Try fading them out
                    //pointList[i].animate({opacity: 0}, 1000 );


        <div id="holder"></div>         

I also was not able to get the online link to the Raphael library to work, so it might be necessary to download the library.

To clarify -

Raphael's animate() will start happening as soon as you make the function call and will keep happening while the rest of your JavaScript is executed.

I've modified Eldar's example code to demonstrate this. See:

Note that the yellow circles are drawn at the same time as the grey ones even though the call to animate() them occurs later in the code.

Hitting a callback function upon the completion of an asynchronous code path is a common pattern in JavaScript and it is essential to understand it in order to be productive with JS.

In Eldar's example, an anonymous function is attached to the first animate()'s callback handler. Upon completion of the initial fade-in animate(), the function gets called, and performs a fade-out.

I recommend Douglas Crockford's JavaScript: The Good Parts (which is, somewhat amusingly, the slimmest programming book I've ever read) and running through JavaScript Koans. Doing that should set you on the right track.

I am beginner to webprogramming & Javascript. I have went through few tutorials and learned the basics. Could someone suggest me the best resource with practical exercise with solutions.

I found "" which has practical javascript exercises, but it's paid! Please suggest any paid sites too which is really worth for practical learning.

you could try it's a very basic intro to the language.

Also I would recommend JavaScript: The Definitive Guide

very nice book, describes the language in details.

Also Douglas Crockford's JavaScript: The Good Parts

And probably some good blogs:

for exercise I would recommend jsFiddle

I learned that from books. Basics: W3schools javaScript

For advanced I suggest these books: Advanced JavaScript(TM), Third Edition Pro JavaScript Techniques

Professional JavaScript for Web Developers (Wrox Programmer to Programmer)

Books are cheap :)

Also I bought W3Schools books about HTML, JavaScript and CSS and I like it :)

Now that frameworks like GWT, Morfik etc exist which compile Java client side code into major JavaScript dialects, is it still worth learning JavaScript?


...and I speak with experience: I've never learned javascript and only used parts of it, when I encountered it in google searches for questions.

Now that I'm building a Web application, I notice that not all abstractions away from javascript have the desired functionality, and I need to go into javascript to solve it.

I notice that I miss the fundamental knowledge I have with other languages, just like I miss the 'javascript programming language' book (I'm not sure it exists but I have similar copies for C, C++ and Java). So today I ordered Javascript:The good parts and I will learn it...

OK, so I'm trying to learn JavaScript properly so that I can write good, clean client-side code, but whenever I think I'm making progress, something stops me dead in my tracks!

I want to know:

  1. What is the different between JavaScript, ECMAScript and JScript?

  2. Which should I focus on learning?

  3. If these are versioned, which version should I be supporting?

  4. Are there any really good references (web / books etc) that are a must have/read?

  5. How do I ensure that what I write will be compliant with all major browsers (IE, FF, Safari, Chrome, Opera etc.) ?

  6. MOST IMPORTANTLY...Is there a reference of the core objects (Array, Number etc) so I know what is implemented already and what I need to do myself?


  1. ECMAScript is the scripting language standardized by Ecma International in the ECMA-262 specification and ISO/IEC 16262. The language is widely used for client-side scripting on the web, in the form of several well-known dialects such as JavaScript, JScript, and ActionScript.

  2. Depends on you, but I think most commonly used for web dev is JavaScript

  3. JavaScript was formalized in the ECMAScript language standard and is primarily used in the form of client-side JavaScript

  4. I would recommend this book

  5. By learning more and more about the language itself and writing tests

  6. Look here

  1. ECMAScript is the language, JavaScript and JScript are dialects

  2. I would, personally, look at and learn JavaScript.

  3. It depends on what browsers you want to support, easily googled.

  4. MDN is a pretty good web source. JavaScript: The Good Parts and JavaScript: The Definitive Guide are both very good books, the first short and concise the latter very detailed.

  5. JavaScript libraries like jQuery is very good for this reason. It all comes down to learning all the quirks of the browsers. Google is your friend.

  6. MDN.

I know that there are several ways to define a function in JavaScript. Two of the most common ones are:

(1)  function add (a, b) {
         return a + b;

(2)  var add = function (a, b) {
         return a + b;

I am comfortable with the idea of a function as an object that can be passed around just like any other variable. So I understand perfectly what (2) is doing. It's creating a function and assigning to add (let's say this is in the global scope, so add is a global variable) the said function. But then what is happening if I use (1) instead? I already know that it makes a difference in execution order: if I use (1) then I can refer to add() before the point in the code where add() is defined, but if I use (2) then I have to assign my function to add before I can start referring to add().

Is (1) just a shortcut for (2), albeit one that happens to behave like other C-style languages in allowing us to define a function "below" the point at which it's used? Or is it internally a different type of function? Which is more "in the spirit" of JavaScript (if that isn't too vague a term)? Would you restrict yourself to one or the other, and if so which one?

It looks like you are already aware of the main characteristics of function declarations1 (1) and function expressions (2). Also note that in (1) there is still a local variable called add containing a function value, just like in (2):

function hello () {
   alert('Hello World');

console.log(typeof hello);  // prints "function"

setTimeout(hello, 1000);    // you can still pass functions around as arguments,
                            // even when using function declarations.

One other point worth mentioning is that function declarations (1) shouldn't be used to define functions conditionally (such as in if statements), because as you have mentioned, they are automatically moved to the top of the containing scope by the JavaScript interpreter2. This is normally referred to as hoisting.

As for which approach is more in the spirit of JavaScript, I prefer using function expressions (2). For a more authoritative opinion, Douglas Crockford lists function declarations (1) in the "Bad Parts" chapter in his popular The Good Parts book2.

1 Also known as function statements (See @Tim Down's comments below).
2 Actually some browsers are able to handle function declarations in if statements (Again refer to comments below).
3 JavaScript: The Good Parts - Appendix B: Page 113.

I realize that title may require explanation.

The language I first learned was C, and it shows in all my programs... even those not written in C. For example, when I first learned F# I wrote my F# programs like C programs. It wasn't until someone explained the pipe operator and mapping with anonymous functions that I started to understand the F#-ese, how to write F# like a F# programmer and not a C programmer.

Now I've written a little javascript, mostly basic stuff using jquery, but I was hoping there was a good resource where I could learn to write javascript programs like a javascript programmer.

Douglas Crockford's - Code Conventions for the JavaScript Programming Language would be a good place to start.

I learned a lot of useful information in regards to code convention through his video tutorials, which I suggest viewing. I posted the link to the first video out of the four in the series.

Also, as suggested by Ben, (which is a book I would also highly recommend) is Douglas Crockford's book JavaScript: The Good Parts

If you want to find good explanations on jQuery, check out the creator, lead developer and fellow StackOverflower John Resig's website/personal blog.

Who can explain why result are [20, 20, 10, 10] in this code:

var x = 10;
var foo = {
  x: 20,
  bar: function () {
    var x = 30;
    return this.x;

  ( =,

Links to specification are welcomed

Can't point you at specification, but i can highly recommend reading Douglas Crockford's "Javascript: The good parts". This book will help you understand most of the weird but great features of JavaScript.

As of your question:

  1., this keyword in bar function is bound to foo object
  2. ( is the same as above,
  3. In javascript you can assign variables from right to left multiple times

    z = 3; x = (y = z); console.log(x); //3

functions are variables as anything else. So you are assigning the function to, but the parenthesis causes the assigned function to be returned, and then executed.

( =; 
//is the same as
var f = ( =;
//and this also the same as:
var f=;

The function returned from parenthesis is not bound to anything, so this will refer to global object, in case of browsers - to the window object.

4.. The clause (, is just alike:

a = (3, 4); //last value is returned, first just parsed.
//a contains 4

var f = (,; 
//f contains body of function, 
f() // is executed  in the context of `global` object, eg. `window`. 

Please read about binding of functions in JavaScript.

The browser based app is said to be done using Canvas 2D or Web GL.

I tried to view source using chrome by using "Inspect Element" button, but my chrome crashes each time.

I am just trying to find out how one can begin to develop such awesome games. Looking for pointers to online resources,books, and specific tips for beginners.

If you want a book, Foundation HTML5 Canvas: For Games and Entertainment just came out. It is fairly basic but will be useful to you if you are completely new to JavaScript and Canvas.

A faster-paced introduction would be the Mozilla Canvas tutorial, which is very clear.

To get a grasp on going from drawing things to being able to interact with them, I'd suggest my own tutorials on the matter, here.

For a general book on Javascript (regardless of your prior experience), it is probably worth reading Javascript: The Good Parts

As for general advice, I give you the words of Ira Glass:

Nobody tells this to people who are beginners, I wish someone told me. All of us who do creative work, we get into it because we have good taste. But there is this gap. For the first couple years you make stuff, it’s just not that good. It’s trying to be good, it has potential, but it’s not. But your taste, the thing that got you into the game, is still killer. And your taste is why your work disappoints you. A lot of people never get past this phase, they quit. Most people I know who do interesting, creative work went through years of this. We know our work doesn’t have this special thing that we want it to have. We all go through this. And if you are just starting out or you are still in this phase, you gotta know its normal and the most important thing you can do is do a lot of work. Put yourself on a deadline so that every week you will finish one story. It is only by going through a volume of work that you will close that gap, and your work will be as good as your ambitions. And I took longer to figure out how to do this than anyone I’ve ever met. It’s gonna take awhile. It’s normal to take awhile. You’ve just gotta fight your way through.

I wonder if someone could be kind enough to explain the function.prototype thingie (thingie!!??) in OO javascript.

I come from a server side programming background, and may be I am not grasping the whole concept of prototypes,

Given the following snippets of code:

var animate=function(){};
animate.angular=function(){/*does something here*/};
animate.circular=function(){/*does something here*/};


var animate=function(){};
animate.prototype.angular=function(){/*does something here*/};
animate.prototype.circular=function(){/*does something here*/};

as far as I can tell, both the latter functions are callable via animate.angular(/*args*/) and animate.circular(/*args*/) so, I guess my question is, what are the merits of defining the functions in the second way? and how or why are they different?

Hope I made sense...

EDIT: Thankyou all for the enlightening answers, It's very hard to judge an answer here as being "Correct", so I'm gonna mark the one I feel made the most contribution...

You all have certainly given me more food for thought...

Javascript is a weird language ... very powerful but not all that strongly structured compared with other languages...

The prototype is how JavaScript lets you save memory if you're going to be creating multiple instances of a class... So if you're using JS in an OOP way you should define your functions as part of the prototype. Also, there are ways to simulate inheritance using the prototype.

I highly recommend the book "Javascript, the Good Parts" for lots of great explanation about this.

So I've been reading through Javascript - The Good Parts and one thing that Crockford points out is the use weakness of global variables in Javascript, in such a way that if your product is expanded in some manner, and it relies on a 'global' variable it could be inadvertently set.

That's all good and fine and I understand the pros/cons of protecting variables, in other manners such as closures as well. However, I was doing some thinking, and wrapping code in a function like so:

(function () {
    var x = 'meh';
(function () {
    alert(typeof x); // undefined

gives it variable scope, which thereby prevents cross contamination of variables. I'm not sure if there's a blatant downside to this approach though and wondered if the community had any input, or if I'm just overthinking things and ignoring the main point.

That's a perfectly legal way of doing things -- the variables inside of your function (as long as they are prefaced by var) are local to the function. It's called the module pattern, and it's very well accepted.

What is a good javascript (book or site) that is not just focused on syntax but does a good job explaining how javascript works behind the scenes? Thanks!

crockford does a good job of explaining JS. check out the articles on his website and his new book:

Both scenario, the typeof the variable will be "undefined". But undeclared variable will raise a exception.

Is there a easy way to handle this?

You should never be attempting to access undeclared vars if you're writing clean JS. To avoid such pitfalls (among many others) start LINTing your JS with or .

A good read to help you understand the LINT tools and reasoning behind their findings is Crockford's Book, JavaScript: The Good Parts ( ).

Currently, I am using Javascript - The Definitive Guide for learning Javascript from scratch. Having learnt Java, PERL and other programming languages, I am in a habit of solving small exercises to check/better understand what I have been learning as well. In case of Javascript, I found the book to be severely lacking in exercises. Infact, I did not find exercises in the only other book [ Beginning Javascript ] I have either.

Is there any source that I can refer to for exercises in Javascript?

I would suggest reading everything Douglas Crockford has to say about JavaScript, reading The Good Parts, writing as many programs as possible and running them all through JSLint with "the Good Parts" and rewriting them until it stops complaining, and reading the source of jQuery. It also wouldn't hurt to read Dmitry A. Soshnikos' rendition of the ECMA-262 spec. (It's very specific and goes into minute detail but it also covers every possible aspect of the language)

It would probably be good to mention that you don't need to follow Crockford's conventions to the letter if you don't want to (though I would recommend writing for ES5 strict) but limiting yourself to them while you learn the language is definitely the way to go.

Once you get a good grasp on the syntax, Crockford has a page that compares javascript with Scheme and takes you through a short book The Little Schemer. The article is appropriately named The Little JavaScripter.

After reading the book, I was changed. Or perhaps transformed. Or altered. In a good way. There are very few books that deeply change the way that you think. This is one of those books.

He's gone through the chapters and translated the functions into javascript. As an exercise, you could do the same and compare your solutions.

I am reading Douglas Crockford's book "Javascript: The Good Parts". He is talking about scope and saying that JS doesn't have block scope:

In many modern languages, it is recommended that variables be declared as late as possible, at the first point of use. That turns out to be bad advice for Javascript because it lacks block scope. So instead, it is best to declare all of the variables used in a function at the top of the function body.

However, I couldn't think of a good example why this statement makes sense and it would be really nice to see some examples which verify this statement.

Declaring variables at the top helps you avoid situations like this:

function outer() {
  var i = 50;

  function inner() {
    var i= 30;


Many people would expect the alert to show 50, and they would be surprised to see undefined. That's because the i variable is declared within the inner function, but it isn't initialized until after the alert. So it has full function scope, even though it's declared after its initial use.

I am really a big fan of javascript. It is really a great prototype based OOP language. Now I want to learn some other prototype based language. Really really interested in some design guideline i.e How can I manage the code without classes etc. Which language should I choose ? Some resource in design patterns for prototype based language ?

The best guidelines that I have read to take advantage of JavaScript's prototypical nature were in the book JavaScript the Good Parts and you can apply these guidelines to other languages also. I changed the way I code in Python after reading this book.

If you want to learn a language similar to JavaScript, try ActionScript first. Both are based on the same standard. It will be easy and rewarding.

I'm a relatively newbie to object oriented programming in JavaScript, and I'm unsure of the "best" way to define and use objects in JavaScript. I've seen the "canonical" way to define objects and instantiate a new instance, as shown below.

function myObjectType(property1, propterty2) {
    this.property1 = property1,
    this.property2 = property2
// now create a new instance
var myNewvariable = new myObjectType('value for property1', 'value for property2');

But I've seen other ways to create new instances of objects in this manner:

var anotherVariable = new someObjectType({
    property1:    "Some value for this named property",
    property2:    "This is the value for property 2"

I like how that second way appears - the code is self documenting. But my questions are:

  1. Which way is "better"?

  2. Can I use that second way to instantiate a variable of an object type that has been defined using the "classical"way of defining the object type with that implicit constructor?

  3. If I want to create an array of these objects, are there any other considerations?

Thanks in advance.

Best way to create javascript objects is quit using new (at least if you subscribe to the crockford camp)

myObjectType = function(props) {
  // anything defined on props will be private due to the closure

  props.privateVar = "private";

  // anything defined on obj will be public
  obj = {};

  obj.testing = new function() {

  return obj;
instance = myObjectType({prop1: "prop"});

// if we want inheritance, it just means starting with the base type instead of
// a new object
subType = function(props) {
  obj = myObjectType(props);
  obj.subTypeProperty = "hello.";

  return obj;

Page 52 of Javascript: The Good Parts, I highly recommend it :-)

I'm interesting in improving my javascript code to be properly OOP.... currently I tend to do something like this:

jQuery(document).ready(function () {
    Page.form = (function () {
        return {
            //generate a new PDF
            generatePDF: function () {

            //Update the list of PDFs available for download
            updatePDFDownloads: function () {

             * Field specific functionality
            field: (function () {
                return {
                    //show the edit prompt
                    edit: function (id, name) {

                    //refresh the value of a field with the latest from the database
                    refresh: function (id) {


In the end it's just mainly organized functions I suppose... what's a good resource where I can learn to program javascript in an OOP manner, or what suggestions would you have for improving my current style of programming?

It seems like I should do a sort of model prototype and have my form object inherit from that prototype.

(I'm using jQuery instead of $ because of conflicts with prototypeJS)

I've been instantiating subclasses in javascript using

object = new class ()

but I notice some people instantiate using

object.prototype = new class ()

Question: What's the difference? To me it seems like the latter is respecting the inheritance chain more because if class () has a bunch of "this.variable = x" statements, and object is something you want to inherit from it rather than an instance of class, you are accurately assigning those variables to object's prototype rather than to the object itself as in the former case. So in effect it's like this?

object = new class () |vs.| subclass.prototype = new superclass ()

However, functionally in the program both are the same?

Side question: Also I'm a bit unclear as to what the new operator actually does. It seems to me to do something like just create an empty object and assign it's proto property?

The code samples in your question reflect a couple of misunderstanding. Let's address them first:

  • class is a reserved keyword in Javascript. You cannot use class as the name of any variable or function. This is not because the Javascript language makes any use of the keyword, but because it was planned for a possible future use.
  • there are no real classes in Javascript. What you may have seen, is different flavors of attempts to simulate class inheritance by using the available inheritance mechanism in Javascript, which is based on prototype objects, sharing properties with linked instances
  • very important: the prototype property used in this inheritance mechanism is set on a function, not directly on objects

Quoting Douglas Crockford in Chapter 5, Inheritance, of JavaScript: The Good Parts:

Instead of having objects inherit directly from other objects, an unnecessary level of indirection is inserted such that objects are produced by constructor functions.


When a function is invoked with the constructor invocation pattern using the new prefix, this modifies the way in which the function is executed.

Douglas Crockford then explains how the new operator could be implemented as a JavaScript function. This function makes use of several other functions defined in the book, so I rewrote it in a (somewhat) simpler form below:

function createNew(constructor) {
  // a function to explain the new operator:
  //   var object = createNew(constructor);
  // is equivalent to
  //   var object = new constructor();
  // param: constructor, a function
  // return: a new instance of the "constructor" kind of objects

  // step 1. create a new empty object instance
  //         linked to the prototype of provided constructor  
  var hiddenLink = function(){};
  hiddenLink.prototype = constructor.prototype;
  var instance = new hiddenLink(); // cheap trick here: using new to implement new

  // step 2. apply the constructor the new instance and get the result
  var result = constructor.apply(object); // make this a reference to instance within constructor

  // step 3. check the result, and choose whether to return it or the created instance
  if (typeof result === 'object') {
    return object;
  } else {
    return instance;

In simple English, if you call new constructor(), where constructor is a function, the operator creates a new object with a link to inherit properties from the constructor, applies the constructor function to it, and returns either the value returned by the constructor, or the new object in case the constructor returned something else which is not an object.

At any time, before or after creating new instances using a custom constructor, you may modify the prototype (object) on the constructor (function):

function constructor(){}  // the most simple constructor function: does nothing
var before = new constructor();
var different = new constructor();
different.answer = "So long, and thanks for all the fish";

constructor.prototype = {};             // set an empty object to the prototype property
constructor.prototype.answer = 42;      // create a new property on prototype object
constructor.prototype.answer = Math.PI; // replace an existing property

var after = new constructor();

Through the hidden link added to all objects created using this constructor (see "cheap trick" in createNew), the properties of the prototype object can be accessed on all these instances, unless overridden by properties defined on the objects directly.

before.answer === Math.PI; // true
after.answer === Math.PI;  // true
different.answer === "So long, and thanks for all the fish"; // true

Using this newly acquired knowledge, how would you create a new "class" of objects that inherit all the properties of arrays, together with a new method empty() to remove all elements?

First, there are no classes in Javascript, so in order to create a new "class", I have to define a new constructor function. Let's call it CustomArray, with a capital C to follow the convention that constructor functions should start with a capital.

function CustomArray(){}

I can now create custom instances:

var myArray = new CustomArray(); 

Second, I want instances created with CustomArray to inherit Array properties:

myArray.prototype = new Array(); // WRONG EXAMPLE: we must set CustomArray.prototype
CustomArray.prototype = Array;   // WRONG EXAMPLE: prototype expects an object, Array is a function
CustomArray.prototype = new Array(); // OK, BUT: the simpler form [] should be used instead
CustomArray.prototype = [];

Third, I want all instances created with CustomArray to have the empty() method:

function empty(){
    // empty this array by setting its length to 0
    // function to be called in the context (this) of an array
    this.length = 0;
CustomArray.prototype.empty = empty; // set the function named empty to the property "empty" of the prototype

Finally, I can rewrite the whole example in a more concise way:

function CustomArray(){}
CustomArray.prototype = [];
CustomArray.prototype.empty = function(){ this.length = 0; }

I can now create a custom array, set a couple of values and empty it:

var myArray = new CustomArray();
myArray[0] = "abc";
myArray[1] = "def";
myArray[2] = "ghi";

The issue is: the above code does not work as expected. Why? Because unlike in regular arrays, setting values in our custom array does not automagically increase the length property of the array. Likewise, calling empty() only sets the length property of our custom array to 0, it does not delete all the values within.

Besides, we could not use the array literal syntax to initialize our custom array:

var myArray = ["abc","def","ghi"]; // this creates a regular array

All in all, it is important to understand how Javascript inheritance works, but you may often find it less useful than expected and there are simpler ways to achieve the same result, for example by using builder functions instead of constructors. We can solve the problem by using a builder function customizeArray to extend regular arrays:

function customizeArray(array){
  array.empty = function(){
    this.length = 0;
var myArray = ["abc","def","ghi"];

This code works as expected because myArray is a regular array in this case, extended with a new method named empty. The main advantage and drawback of this approach in comparison with using prototypes is that it modifies only the selected instance, and if you were working with lots of similar objects at the same time, setting this extra property would use more memory than setting a single shared property on a common prototype.

To avoid that, you may be tempted to modify the Array prototype directly:

Array.prototype.empty = function(){
  this.length = 0;
var myArray = ["abc","def","ghi"];

It works, but I would advise against it: you are attaching a custom property to every array instance, including all those created by those fancy libraries, plugins, frameworks, advertising and analytics scripts, all the code on your page. Needless to say that it may break something in a place where you cannot fix it.

Edit: Interesting post on kangax's blog as a follow-up: "How ECMAScript 5 still does not allow to subclass an array"

This is what I got so far, and it's not working at all :( all the variables are null in my player class and update never gets called.

I mean a programming class, not a css class. I.E. not (.movingdiv{color: #ff0000;})

<!DOCTYPE html>
<html lang="en">
        <title>Class Test</title>
        <meta charset="utf-8" />
            body { text-align: center; background-color: #ffffff;}
            #box { position: absolute; left: 610px; top: 80px; height: 50px; width: 50px; background-color: #ff0000; color: #000000;}

        <script type="text/javascript">
            var box = 0;

            function Player () {
                var speed = 5;
                var x = 50;
                var y = 50;

            function update() {
       = this.x + "px";
       = this.y + "px";
                box.innerHTML = "<h6 style=\"margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px;\">X: "+ this.x + "<br /> Y: " + this.y + "</h6>";

            var player = new Player();
            var keys = new Array(256);
            var i = 0;
            for (i = 0;i <= 256; i++){
                keys[i] = false;

            function keyDown(event){
               keys[event.keyCode] = true;

            function keyUp(event){
               keys[event.keyCode] = false; 

            function update(){
                if(keys[37]) player.x -= player.speed;
                if(keys[39]) player.x += player.speed;


            setInterval(update, 1000/60);

        <div id="box" ></div> 
        <script type="text/javascript">
            box = document.getElementById('box');
            box.innerHTML = "<h6 style=\"margin: 0px 0px 0px 0px; padding: 0px 0px 0px 0px;\">X: "+ player.x + "<br /> Y: " + player.y + "</h6>";


Edit: alright, I think I messed up here. The first time I tried to make a class I seem to have messed up. After retrying I seem to be able to now using the "1 Using a function" in Meders post.

the real problem seems to be that javascript doesn't know what to do when it gets to this line in my real code: = "" + -(this.frame * this.width) + "px " + -(this.state * this.height) + "px";

It also seems to choke anytime I put

So the question I need answered now is how do I set a value to style variables in javascript that have a "-" in the name. I'll post a test in a second

You're using Player like a constructor, but it is not set up like one.

Rather than using var inside the constructor function, like var speed = 5; you need to use


Then it wil return an instance of Player. As it is, you're just setting some variables and returning nothing in particular.

Now, as far as learning JS object creation and inheritance, I suggest checking out Douglas Crockford's resources. As you may know, it's not intended to be class-based like Java, PHP, Python and so on. JavaScript has prototypal inheritance based on cloning objects that already exist.

Crockford discusses doing class-based inheritance in JS in this older article. The problem is, you're not using JS to it's best trying to do that. This treatise may be interesting where he explains one way of cloning objects. That is the Object.beget method, which is good, but has limits as well. The best way is the 'functional' method. Sorry for the PowerPoint links, but you should read this: and this: is one version of a video where Crockford discusses the ins and outs of JS. is another of the same.

I really recommend getting the book JavaScript: The Good Parts for a thorough run down of pragmatic advanced JavaScript.

Beginner in JS :) needs an explanation of code piece from Crockford's book, section 4.15:

var memoizer = function (memo, fundamental) {
    var shell = function (n) {
        var result = memo[n];
        if (typeof result !== 'number') {
            result = fundamental(shell, n);
            memo[n] = result;
        return result;
    return shell;

var fibonacci = memoizer([0, 1], function (shell, n) {
    return shell(n - 1) + shell(n - 2);

Question: How do we calculate fibonacci(15), and if it is simple fibonacci(15) call, then how it works in detail?

Thanks for help.

As the comments to your question suggest, you should walk through the code in a debugger to get a good understanding of what's going if you can't follow the explanation in the book. But I'll give you a brief overview of what's happening:

What's being demonstrated is 'memoisation' which is a common optimisation technique used in functional programming. A function is said to be pure if the result depends only on the arguments passed into it. So, if a function is pure you can cache the result based on the arguments - this technique is called memoisation. You would do this if a function is expensive to calculate and is called multiple times.

The classical example used to demonstrate this (as here) is generating Fibonacci numbers. I'm not going to go through how those are worked out, but basically as you go to higher and higher numbers you repeat yourself more and more as each number is calculated from the preceeding two numbers. By memoising each intermediate result you only have to calculate them once hence making the algorithm much faster (much, much faster as you go higher up the sequence).

As far as this code is concerned the memoizer takes two parameters - 'memo' which is the cache. In this case it's going in with the first two values already filled in the '[0,1]' - these are the first two Fibonacci numbers.

The second parameter is the function to which the memoisation will be applied. In this case a recursive Fibonacci function:

function (shell, n) { return shell(n - 1) + shell(n - 2); }

i.e. the result is the sum of the previous two numbers in the sequence.

The memoizer first of checks to see if it already has a cached result. If it does it returns that immediately. If not it calculates the result and stores it in the cache. Without doing this it'd be repeating itself again and again and rapidly gets impossibly slow once to get to the higher numbers in the sequence.

Can anyone show me some complex JSON structure and tutorials where i can excel more on this JSON topic using javascript. So far i am able to understand JSON, its basic structure and how to parse and alert out properties.

I can search in google or other search engines, but i want links from you expert guys who can lead me to right direction than a BOT which displays result.


Get (a lot) more involved...

Check out JSON processors and libraries

If you have some knowledge of other languages, you could look at some JSON processors' implementations and get to know what makes them better or worse than their competitors, read their code, etc...

For instance, for Java:

For other languages: see (at the bottom of the page) for tons of links.

Learn about JSON variants and JSON-based concepts

Experiment with some JSON endpoints

Look online for webservices exposing JSON-enabled endpoints to play with them. Head over to ProgrammableWeb for that, or use any search engine.

For experimenting, use either:

Actually you could very much just use your javascript console to experiment without any end-point and test whether you manage to create objects.

I have been coding for a few years and still feel that my knowledge is not broad enough to become a professional. I have studied some books related to design patterns, but I know there are many others.

So could somebody list the patterns and principles which you think are good to learn to become a better programmer and more professional?

Programming Languages I work on: C#, Ruby, Javascript.

Encyclopedic knowledge of design patterns will get you nowhere. Plenty of experience applying them will. This will teach you when to use them and when not to.

That said, the original Design Patterns book is still one of my favorites. Pick up other patterns as you go along.

Martin Fowler's Patterns of Enterprise Application Architecture to build up a shared vocabulary with other developers (e.g. Repository, Active Record, Domain Model, Unit of Work).

Douglas Crockford's Javascript: The Good Parts to actually understand how Javascript works.

And I'd really recommend getting into TDD (Test Driven Development). There are a bunch of good TDD books but if you are doing brownfield development (which most of us are) then I'd really recommend Michael Feather's Working Effectively with Legacy Code.

And finally the book that shows you just how refactored and clean code can be: Uncle Bob's Clean Code.

I know let is to declare block scope local variables, but why doesn't it support redeclaration and hoisting like var does?

What's the design purpose of this limitation?

    'use strict';
    alert(a);       // undefined
    var a;

    'use strict';
    alert(a);       // error
    let a;

    'use strict';
    var a;
    var a;
    alert(a);       // undefined

    'use strict';
    let a;
    let a;          // error

The idea is to create a tool that's more unambiguous and more strict than the original var.

As a human, the following is valid JavaScript but nearly impossible to understand:

alert(a); // Where does a come from? Why does this not throw?
/* 1000 lines later, or even in an entirely different file */
var a;

Moreover, imagine code with 5 var declarations for the same variable on the same scope, some in if statements, some in fors. Which is the first? What value will end up being created?

The idea was to fix some of the bad parts of var.

I'm reading some tutorials now about jQuery.. function creating,plugin creation etc. but these tutorials are missing some basic explanations like they mention things like

function prototype, anonymous functions, umm putting (jQuery) after the }); .. and stuff like that .. is there a tutorial/website/book that explain these I'm not sure how to call them "terms" from beginner level to advance. I'm mean I have a knowledge of some jquery syntax but not enough to understand this, can anyone recommend useful resource?

Google doesn't help much, I googled "advance features of jquery" don't really get me the things I wanna know.


Also if someone can share his/her story steps on how to become comfortable with javascript, how to overcome this "terminology" or whatever is called

For JavaScript, there is: Javascript The Good Parts

For jQuery, I'd suggest: The jQuery CookBook

I'd also suggest some podcasts and screencasts:


jQuery for Designers

I would consider myself to be reasonably competent with JavaScript and familiar with many of the different ways of achieving the same thing. But today I came across some function syntax which I hadn't seen before:

function document.body.onload()

If I were to write such code I would have done it like this:

document.body.onload = function()

Ignoring the fact that this is not the best way to handle the onload event, is this actually valid JavaScript? It appears to causes syntax errors in FireFox (and JSLint), so I am guessing that it is Internet Explorer only syntax? If it is IE only then I would like to remove it but I am concerned that it might have some quirky side effect.

No, it's not valid. the function X() {} variant requires that the name of the function only contains letters, digits, '$' and '_'.

If you want to check other syntax, you can get the standard here, but the syntax diagrams in the back of JavaScript: The Good Parts are much easier to digest.

I would like to develop some apps for the JVM using a concise, dynamic language. The most popular choices for this seem to be Jython, JRuby, Groovy, and maybe Clojure.

Rhino appears to be fast and very stable, but I see no books on Rhino development and little discussion. Why is there apparently little use of JavaScript for other than embedded scripting?

Edit: I found this question informative on the viability of Rhino-based development.

I've used Rhino as a part of a production-grade VoiceXML interpreter written in Java and running on the JVM. It works extremely well for this purpose. If I were reimplementing this interpreter from scratch, I would have leaned towards doing even more of my development in JavaScript. So it's definitely an option. You'll need to explore how mature the surrounding libraries are for your application area (you can always write logic that calls out from JavaScript to Java libraries, but that might be too laborious).

But I also agree with @Peter Recore: do give the other JVM languages a second look. I'm impressed with the object-functional Scala language: its performance is nearly as good as Java, and it has a lot of expressive power.

Update: Good books to read on JavaScript are: JavaScript: The Definitive Guide and JavaScript: The Good Parts. The only Rhino-specific stuff you'll need is here.

Using the tiny Diggit/Blog feature of StackOverflow described here:

I would like to post the following Google tech talk video I have just saw and that I found quite interesting.

I have always had problems understanding javascript "nature".

Here, the JavaScript good parts are described by Douglas Crockford

I hope you find this link useful.

Now the question part:

What are your complaints about javascript? Do you use an IDE for javascript editting? Do you think this video helps to understand the "good parts"?

alt text   Javascript the Good Parts is a pretty decent book too.

For Javascript Firefox+Firebug and Notepad++ are my IDE. jQuery (and assorted plugins) is my Framework. My biggest complaint about Javascript is IE6

Possible Duplicate:
Is it a good idea to learn JavaScript before learning jQuery?

I have been trying to teach myself Javascript recently, and I have gotten a lot of comments from people telling me that I should just teach myself jQuery.

I see uses to both - and obviously understanding Javascript lets you understand what is going on in jQuery to a greater extent. But jQuery seems easier, more intuitive and quicker to get to production level code (always useful when you're in a business environment).

Learning a framework (jQuery) without learning the language (javascript) it is based on is not the best way to go about it.

If I was starting out fresh and wanted to get productive quickly I would read Douglas Crockfords Javascript the good parts first. This books gives a good background on using the good parts of javascript and is the basis for many of the design ideas used in jQuery. Then I would get started with jQuery.

Iam trying to get better in javascript coding. Away from 1000 lines of code in one file. But iam not sure if this is the "right" way:

RequireJS to load files when needed inside "boot.js":

], function() {
    $(function() {


var MyApp = {
init: function() {

// this is our controller, only load stuff needed..
mainController: function() {

    //controller = set from php/zendframework
    switch (controller) {
        case 'admin':

// action for admin controller
initAdmin: function() {
    //lazy load
    require(["app/admin/admin"], function(){


MyApp.admin = {
init : function() {
    if (permisson != 'admin') {
        console.log('Permission denied.');
        return false;


MyApp.admin.dashboard = {

init: function() {

connectEvents: function () {
    EventManager.subscribe("doClearCache", function() {

    EventManager.subscribe("doDeleteUser", function() {


What other "styles" are common? or this a goodway to structure code? THere a lot of examples in the net, but i was not able to find "real life" code..

And one of biggest "problems" when does i need ".prototype" ?

I defer to Douglass Crockford on all matters pertaining to JavaScript best practices.

Here is his homepage:

Here is a great book on what to do and what not to do in JavaScript.

Here is his amazing tool which can automatically tell you if you are employing any worst practices.

As to the prototype question, you use prototype when you want to employ prototypal inheritance, or create a "static" class function which will be present for all instances of that class without consuming memory for each instance.

I do not like saving files, switching to a web-browser and refreshing and seeing if it worked.

That is why I am asking.

When I must touch PHP I use Eclipse, and I can create unit tests and make sure it works properly, I don't write a bit, test then write a bit and test. So I expect to "develop" Javascript the same way, write a chunk, make sure it works, but I'm not sure how I can test actions triggered by a button say.

I've searched for "Javascript development" and other terms, I get the expected slews of crap on ... well hello world Javascript snippits really.

Can someone point me in the right direction? I currently use Eclipse (Eclipse CDT, PyDev, Eclipse PHP, so forth) and I can debug. I could make do without the step-by-step debugging for Javascript, but I'd really like unit tests.

The other problem I have is the difficulty finding out what went wrong, Even PHP can give you a call trace, I'm stuck with Firefox's annoying-to-access error thing in the web-developer settings.

There must be a better way, but I'm struggling to find it.

Step one; static analysis:

Step two; testing: Automatic tests in Eclipse for JavaScript

Step three: JavaScript The Good Parts

I have learned basic JS knowledge, and read "Javascript definitive guide" book, but best way to improve is learning by doing, so any opensource project for practice, or any good suggestion for improving JS?

As an example of an open source project you could look into I would recommend to check the dojo sources. It's easier to grasp the advanced concepts there than e.g. in JQuery since there is a much wider code base for many different aspects. There is a lot to go through in the dojox packages. The code is also nicely documented, and recently they added nice online documentation, too, something that was missing for a long time. I learned a lot by peeking into dojo's internals, so I can only recommend it.

You should pay attention to their way of coding object-orientedly and how it differs from what plain JS offers you.

In addition to great code you can learn the concepts of code minification there, which is a big deal for the dojo project. There's also material on unit testing with Javascript code, something that is often overlooked but as important as back-end unit tests imo.

By reading "Javascript - The definitive guide" you now know a good bit about the language itself and its usage for browser-based applications. But with the recent popularity gain of Javascript it has also found its application on the server side. E.g. node.js is a very interesting project you could look into.

The concept of "Closures" is something you could look up, then find examples in existing code and finally use them in your own.

"Ajax" is another buzzword and concept you should be familiar with, it lets you do all the nice things in your browser that some years ago were only possible in desktop applications.

Modern web applications make heavy use of Javascript, but since standard Javascript and its prototypical inheritance are a bit clumsy to use, frameworks were written that simplify common tasks. You should familiarize with one or more of them to get an understanding of what they simplify compared to plain Javascript - this way you will automatically learn the drawbacks and shortcomings of pure Javascript. A good example is the with keyword. It's there, but nobody uses it. If your time just allows you to delve into one of these frameworks then my recommendation would be jQuery - it's the most widely used Javascript framework out there.

Some Frameworks

Read blogs and technical articles on the web, skim through Javascript questions here at Stackoverflow to keep up to date and learn about interesting corner cases.

Some book recommendations

I looked it up and this pattern is Hofstadter Female sequence. The equations are:

M(n) = n-F(M(n-1))

F(n) = n-M(F(n-1))

but I'm not sure how to put that into code.

So far I have:

while () {
    if (_p % 2 === 0) {
        _r = _p - 1;

Any help?

Similar to GaborSch's answer, you could use Doug Crockford's memoizer function, which can be found in Chapter 4 of Javascript: The Good Parts. Using memoization took the calculation time for the first 150 terms of the male and female Hofstadter sequences down to 256 ms as compared to almost 8 seconds without memoization.

var memoizer = function (memo, formula) {
  var recur = function (n) {
    var result = memo[n];
    if (typeof result !== 'number') {
      result = formula(recur, n);
      memo[n] = result;
    return result;
  return recur;

var maleHofstadter = memoizer([0], function (recur, n) {
  return n - femaleHofstadter(recur(n-1));

var femaleHofstadter = memoizer([1], function (recur, n) {
  return n - maleHofstadter(recur(n-1));

var N = 150;
var f = [];
var m = [];
for (var i = 0; i <= N; ++i) {

console.log('F: ' + f.join(','));
console.log('M: ' + m.join(','));

I was wondering how one would go about making "classes" similar to those in Python in Javascript. Take the Python classes and functions listed here:

class one:
    def foo(bar):
        # some code

The function "foo" would be called with
What would the JS equivalent be? I suspect it would be something like this:

var one = {
    foo: function(bar) {
        // JavaScript


Have a look at this link. There a different ways to do OO programming in Javascript. The details are too much to be explained here.

If you are serious about Javascript programming, you should read this book.

If you want to do real heavy OO programming, I would recommend to have a look at Coffee Script.

Ok so as I understand my code, I created a promoSlides object, I a private function called init and in the return of a js closure (which I am not too familiar with) I returned init so I can use it outside globally kind of. When I run the file I get promoSlides is undefined, says error console of FF. I am not sure where I went wrong. I am new to this so probably something is wrong. Oh and slides was defined in my original doc but I took it out for simplicity sake

var Slider = (function (name) {return name;}(Slider || {}));

Slider.promoSlides = ( function()
var slides;

var init = function(s)
    slides = s;
    init : function a(s)



Semicolon insertion strikes again!

    init : function a(s)

needs to be

return {
    init : function a(s)

This is a result of a "feature" in JavaScript that looks at your line with just return on it, and says: "oh, you forgot your semicolon, I'll add it for you."

It changes return to return; so your function now returns undefined, and then you have some naked JSON sitting below it, which is the source of your error. Douglas Crockford actually describes this as one of the "awful parts" of JavaScript.

So the moral of the story is: always put your opening brace on the same line when you're coding in JavaScript.

function wrapper() {
    var $R = {};

    $R.expandFont = function (direction, max_time) {
        // wtf? $R jslint error
        var self = this,
            el_prim = self[0],
            $R = {};

        alert(direction + max_time + el_prim + $R);

This snippet gives error:

line 573 character 13
'$R' is already defined.

I think it is clear that it has not been previously defined.

$R was defined in the outer scope, but this should not be relevant. I should be able to define a local variable with the same name as JavaScript ( the language ) is function scoped. Yes, I know it is not block-scoped, but it is function scoped.

It is basic scoping rules. What gives?

Is this a jslint bug?

I think that your understand yourself, that if you rename $R in outer or in inner scope of the function the JSLint "error" will be fixed.

I decided to write my answer only because I think there are misunderstanding about the goal of JSLint. It's not just a tool which helps you to find errors from the point of view of JavaScript language. You can consider the tool as AddOn to the book JavaScript: The Good Parts. Douglas Crockford tried to show which constructions of the language could be misunderstood by people which read the code. Some from the potential misunderstandings he declared as "warnings", another as "errors". Some from the "warnings" or "errors" can be suppressed by comments like /*jslint ... */ another not (like declaration of var inside of for-loop header). The choice which potential misunderstandings should be interpret as a "warning" and which one as an "error" is very subjective and represents only the personal meaning of Douglas Crockford.

I'm not always agree with recommendations of Douglas Crockford, but the warning ("error"): '$R' is already defined I would personally find also as critical because of difficulties to read such code. I would recommend you to rename one from $R variables too. I want to emphasize one more time that the goal of such changes not fixing of an JavaScript error, but improving of readability of your program for other people.

By the way I would recommend you to use variables with all capital letters only on the top level ($R looks so, independent from the first $ letter). See the last sentence of the JSLint recommendation about the naming convention.

Why in javascript if you reference objects method to some variable it loses that objects context. Can't find any link with explanation what happens under the hood. Except this one which states: ‘this’ refers to the object which ‘owns’ the method which doesn't seam to be true.

var Class = function() { = 1

Class.prototype.method = function() {

var obj = new Class();
console.log(obj.method() === 1);

var refToMethod = obj.method; // why refToMethod 'this' is window

console.log(refToMethod() !== 1) // why this is true?

var property = 1;
console.log(refToMethod() === 1)

From Douglas Crockford's book JavaScript: The Good Parts

The this parameter is very important in object oriented programming, and its value is determined by the invocation pattern. There are four patterns of invocation in JavaScript: the method invocation pattern, the function invocation pattern, the constructor invocation pattern, and the apply invocation pattern. The patterns differ in how the bonus parameter this is initialized

The Method Invocation Pattern

When a function is stored as a property of an object, we call it a method. When a method is invoked, this is bound to that object. If an invocation expression contains a refinement (that is, a . dot expression or[subscript] expression), it is invoked as a method

In your example method invocation pattern is

console.log(obj.method() === 1);

and this in this case is bound to the object "Class" and it works as you expected.

The Function Invocation Pattern

When a function is not the property of an object, then it is invoked as a function:

var sum = add(3, 4); // sum is 7

When a function is invoked with this pattern, this is bound to the global object. This was a mistake in the design of the language. Had the language been designed correctly, when the inner function is invoked, this would still be bound to the this variable of the outer function. A consequence of this error is that a method cannot employ an inner function to help it do its work because the inner function does not share the method’s access to the object as its this is bound to the wrong value

In your case

var refToMethod = obj.method; // why refToMethod 'this' is window
console.log(refToMethod() !== 1) // why this is true?

refToMethod is bound to the global object "window" in this case

You can find more information about this at JavaScript “this” keyword

Would it be better to learn C before learning any type of WEB and desktop programming?

I don't know how to program, I want to learn Javascript and my friends suggested to me that I should learn C first.

I actually think that JavaScript is one of the best languages to start programming with. Later, when you you really get it and you want to go deeper, C is something great to know. It gives you a much deeper understanding of how computers really work.

JavaScript really lets you get started fast, see immediate results, and ramp up to more complex concepts very fluidly.

The rest of my answer assumes you know practically nothing about programming - web or otherwise. Maybe you know a little html basics.

Open up a text editor. You can even just start with notepad or something. And put in the following:

            alert("Hello, World!");

Save the file as hello.html and open it in a browser. Poof! You've written a program. Doesn't get easier than that. No need to get into the command line or download or build anything. I remember when I first started being frustrated trying to get PHP running on my machine and wishing it was as simple as getting started with JavaScript.

The next step is just to read and explore. Documentation is freely available all over for learning more. I highly recommend anything from Douglas Crockford and JavaScript:The Definitive Guide.

A pretty good basic project would be a calculator program, but there's lots of fun things you can do. When you've gotten your feet wet, and you feel a little more confident, explore some other languages. Ruby is a pretty good step from JavaScript. By that point you'll probably know where to go yourself. You may never take the road to learning C. Even if you learn it, you will likely never really have to use it.

I think it depends on your motives - are you aiming to become a professional programmer? If so, there could be some value in learning C first.

Most entry-level programming subjects at University are taught in terms of C; it can give you a deeper insight into how software works. Also, K&R is a valuable programming manual in its own right.

If your aim is to create a simple set of DHTML pages, then by all means, jump straight into JavaScript. However, I think C can offer you a lot, if you're serious about programming.

as a developer with OOP background(c#, Java) OOP JavaScript is wild horse for me. I am trying learn nuts and bolts of language and then jump on libraries (Am I wrong?);

so, I checked dozen of books/tutorials about objects, functions...etc..learned several ways to create objects but syntax used in almost every JS library confuses me. namely

var Person = Backbone.extend.Model({
 //pretty complex staff

what is Model behind the scenes? object? function?

Welcome to stackoverflow,

I strongly advise you to have a look at Douglas Crockford's Website and there are also insightfull videos in YUI Theater - start with the ones of Douglas. He's the one who discovered JavaScript has good parts. I also found John Resig's Secrets of the JavaScript Ninja very helpfull for grocking the language (John is the creator of the omnipresent jQuery Library). I would further advise you to look at some libraries (and their code - that's how I learned it - just start with jQuery). There are a ton of other libraries out there but one step at a time :-).

Now to your question: The Backbone.Model is a constructor function, normally you would use it like in Java new Backbone.Model({ configOption: true, ... }). But juicy as JavaScript is it allows you to do crazy things under the hood. For example you can implement your own OOP Class implementation or you can program in a functional style like you would do in Scheme or Lisp. What you see here is Backbone's own subtyping wrapper in action (virtually any decent JS library provides some way to do this). The code is actually doing something along the lines of this:

// Creating a sub type of the Backbone.Model *class* - it's not really 
// a class like in Java or C# but rather a (constructor) function.
var Person = Backbone.Model.extend({ 
    defaults: {
        hasTheOneRing: true
    initialize: function (hasTheOneRing) {
        // Note that Backbone is implementing getters/setters
        // under the hood so you can listen for change events later
        this.set('hasTheOneRing', hasTheOneRing);
    // More configuration ...

// Person now is a constructor function that creates instances
// of it's *class* when you create an object with it
var frodo = new Person(true),
    sam = new Person(); // Note that you can supply as many arguments as you wish

// Frodo has the ring

// Sam doesn't have the ring (well not all the time)

// In plain old JavaScript the sub typing mechanism works a little bit like this:

// A constructor function is just a function
function Person() {
    // JS doesn't have the notion of *super* or *base* but you
    // can emulate the behavior as many libraries do in the wild;

// The prototype of a person is based on that of a Backbone.Model
Person.prototype = Object.create(Backbone.Model.prototype);

// Object.create has not been there since the beginning. After
// Douglas Crockford discovered the good parts this function
// has been adapted into the standard portfolio of every modern browser
// what it does is essentially just:
function create(object) {
    // There's actually more going on in here but you get the idea
    function F() {}
    F.prototype = object;
    return new F();

// So this means almost the same
Person.prototype = new Backbone.Model();

My way of getting to love JS was to read library code - and Backbone is open source so have a read and be amazed by the awesomeness g. I think the fact that JS is just plain text send over the wire had a big influence on the language getting that strong in the ecosystem, even Microsoft couldn't stop it.

Give the language a try, when it clicks you'll most likely actually begin to like it :-).

Happy coding!

Being a web developer I have noticed that anything I create works absolutely great in all browsers, but always always always has a speed issue in Internet Explorer. Please note I am referring to speed, as I always take care that it displays and works across all browsers.

Is there anywhere, or does anyone have, good programming tips for internet explorer? I mean how to do things, so as that it's more or less optimized for internet explorer.

I mean my latest example is that I return JSON data from DB (via AJAX) and then I build the page with the results. The response from the server is minimal, and it loads instantaneoulsy in aaaaall browser, but takes 5-10 seconds in internet explorer depending on OS and ie version.

I am lost for words, and I was just wondering if there's anything I can do.



Javascript performance in IE is currently the worst among all of the popular browsers. The suggestion to use IE as your baseline for performance is well grounded. I'll add that using an accepted js/ajax library (jQuery, YUI, etc.) will ensure a lot of browser-specific optimizations have been done and heavily tested for you.

If you are doing a lot of custom js in your web application and are just looking for some best practices, I can recommend a few websites:, IE + JavaScript Performance Recommendations. This is a good chance to plug Douglas Crockford's Javascript: The Good Parts for general js zen.

Hey everyone I just purchased the book JavaScript demystified to read and learn JavaScript but I just noticed that it was published in 2005 and it references netscape browsers and other "pratices" I believe are out dated like using the language attribute in the script tag and also not ending each line with a semicolon

My main question is has javascript changed so much since this book was published that reading this book not teach me what I need to know or could it still be a good reference?

Yes, the language has changed way too much in the past 6 years. All those changes I'm talking about here come along with ECMAscript edition 5 which is now pretty much available in any browser. If that is not covered in the book (I doubt it) its only good for the basic Javascript syntax.

However, there are "oldish" books which also do not cover ES5 but still are great to understand the language. I don't know the book in question, but still a hot candidate is "Javascript - the good parts" by Douglas Crockford.

Again, the basic Javascript syntax has not changed all that much, but there are TONS of new native methods / techniques which really are the future of this language.

I am a C/C++ programmer with more than 10 years of experience. I also know python and perl, but I've never used this languages for a web development.

Now for some reasons I want to move into the web development realm and as part of that transition I have to learn css, javascript, (x)html etc.

So I need an advice for a good sources of information for such topics. For a while I don't want to read lengthy tutorials, I want something quick and dirty, something to start with.

Since you are an experienced programmer, a good place to start with javascript might be Javascript: The Good Parts by Douglas Crockford. It is a brief but thorough tour of, well, the best parts of javascript (and pretty much all you'll need for quite a while).

Your approach to CSS and HTML will have to be very different. I suggest trying to make a static site or two, checking reference material if you get stuck. Pick a site that you like, and try recreating the basic layout in HTML. Got the layout? Try making it look pretty. Repeat.

I am beginner in javascript. my usage for javascript is for server side applications. e.g. Node.JS

but wherever i see any tutorial/example for javascript it always starts with html tags, script tags, invoking browser window functions etc. e.g.

<!DOCTYPE html>
<script type="text/javascript">
function displayDate()

<h1>My First Web Page</h1>
<p id="demo">This is a paragraph.</p>

<button type="button" onclick="displayDate()">Display Date</button>


Where can i find a javascript tutorial which only teaches the language, not the webpage/browser usage of it.

I want to know language aspects like

  1. regexp in JS

  2. functional prgramming in JS

  3. any good javascript design patterns (if there are any)

  4. program structure in JS in general

Thanks a lot.


If you're new to Javascript, you should start with the book Javascript: The Good Parts by Douglas Crockford:

That will give a great and concise introduction to the language.

If you're starting with node, it might also be a good idea to check out Express JS which has a pretty good guide, and you get to work with a higher level API:

Note that you'll also miss out on some of the great low level action, using Express :)

i am just finished college and worked with the java language for the past few years. i want to change,

what do you guys think is the most usefull web development language to use? what would you guys recommend for me to learn

rite so guys u have all explained a different language,

lets say i would like to create a file sharing web service, if i was to develop in one language for the client side, how could i use a different language server side? how could i get them to interact?

Javascript - You need to work on the client side. I suggest the book Javascript The Good Parts. Javascript is also an interesting language due to its prototypical nature. If you want to do Javascript on the server side, look at node.js, which is interesting due to code reuse possibilities.

Python - Multi-faceted language with great web toolkits. Not as expressive as other languages (doesn't match the DSL capability of Ruby), but clean and expandable. Look at Pylons, Django, CherryPy.

Perl - Perl web applications work great, even if the language isn't "cool". Mason, Template Toolkit are contenders.

Ruby - Rails is a great RAD framework. There are questionable practices galore (monkey patching), but they don't ruin the platform from a usability point of view (maintainability on the other hand...). If you don't want rails, there are minimal Ruby web frameworks as well.

PHP - Tragedy of the commons. It works, its installed everywhere, but the language and runtime is terrible.

Factor - Be non traditional, use concatenative languages!

Smalltalk - Seaside is fun to use.

Common LISP - UnCommonWeb is a great continuation style web framework.

Erlang - This language is fantastic for its integral hot reloading and high availability features. You can also use the built in database (Mnesia) or CouchDB.

Scala/Groovy/Clojure - More JVM languages to try, to stay true to the Java platform. The most interesting language in that grouping is Clojure.

C/C++ - Why not, it works, and can be fast.

Bourne Shell - Perl with less features.

C#/VB.Net/Other CLR language - An easy jump from Java in terms of model. Good RAD support in in ASP.NET MVC. Using all of ASP.NET restricts you to Windows only (Mono is good, but not 100%). Drinking vendor kool-aid is always fun.

ColdFusion - When just Java and all of the inherent flexibility is not enough, throw in some bizarre database table to website middleware. It works just as well as the ColdFusion reactor on my desk.

I found one interesting project on github which deals with pdf rendering in the browser.

I tried to read the code because I'm interested in this topic but I realized that my javascript knowledge is poor (insuficient).

There are constructs like:

var Obj = (function() {
    function constructor(type, value) {
    this.type = type;
    this.value = value;

    constructor.prototype = {

    var types = [
    "Bool", "Int", "Real", "String", "Name", "Null",
    "Array", "Dict", "Stream", "Ref",
    "Cmd", "Error", "EOF", "None"

    for (var i = 0; i < types.length; ++i) {
    var typeName = types[i];
    constructor[typeName] = i;
    constructor.prototype["is" + typeName] =
    (function (value) {
     return this.type == i &&
     (typeof value == "undefined" || value == this.value);

    constructor.prototype.lookup = function(key) {
      function lookup(key) {
        if (!(this.value.contains(key)))
          return Obj.nullObj;
        return this.value.get(key);

    Object.freeze(constructor.trueObj = new constructor(constructor.Bool, true));
    Object.freeze(constructor.falseObj = new constructor(constructor.Bool, false));
    Object.freeze(constructor.nullObj = new constructor(constructor.Null));
    Object.freeze(constructor.errorObj = new constructor(constructor.Error));

    return constructor;

You can see more of them in the link above.

Could you please advise me some resources which to study to be able to understand the code in the project with ease and even better to contribute later to the project?

Douglas Crockford's book JavaScript: The Good Parts is a great place to gain an appreciation of the power in JavaScript, while steering you away from the ugly (or downright dangerous) parts. His website also has a collection of interesting articles about the language. I recommend both.

I have some experience in ASP.Net and can work my way around it without much trouble, however there are a lot of gaps in my knowledge of and .net in general.

I know the basics of c# and so I can accomplish most things. But I don't know anything at all about LINQ, Entity Framework, ADO.NET, delegates, ASP.NET Ajax, ASP.NET MVC, Providers, the different api's provided with (such as membership), the default controls that come with as well as the normal patterns used to create rich, stable and high performance sites. The list goes on and on....

I have really been wanting to upgrade my skills now and become a well rounded .net developer before I get left too far behind in the curve. I also have been meaning to look into ASP.NET MVC partially because I`d like to extend an open source project.

The problem is every time I get down to learning I get too overwhelmed. I dont know where to start, whats relevant, whats not. I basically need to figure out in what order should I be approaching all these different things and tackling them?

Should I get down with one of those monstrous 3.5 books (such as unleashed...1500pages) and read it from start to finish? And then pick up some book on ASP.NET MVC? Do I need to actually read such books from start to finish or are there topics I can safely skip?

Sorry if the question is badly worded but I think my problem should be evident. I feel .net is evolving very fast and I am getting left behind more and more. Aside from that I really want to be a good developer because web development is somewhat of a passion of mine.

Books I currently have in my possession...

ASP.Net 3.5 Unleashed

Building a Web 2.0 Portal with ASP.NET 3.5

Pro ASP.NET 3.5 in C# 2008

Javascript: The Good Parts

Pro C# 2008 and the .NET 3.5 Platform

To echo what others have said, you have to write code. However, don't stop moving forward when you hit a wall. If you're stuck on "the best way to do X" (best practices) either look it up if it's simple enough, or pull it off to the best of your knowledge THEN look it up and either go back and refactor it, or the next time you come across it implement it with the new techniques you've picked up.

As for what to learn and the order to do so, I suggest focusing on what you feel you really want to pick up OR what you think is going to be the most relevant and applicable to your job. Granted, you might not work somewhere that is constantly using the latest technology, in which case you'll need to learn things on the side through some mini-projects. There's a lot out there, so narrow it down.

Another suggestion would be to start a simple project and decide to implement parts of it using a particular technology. So, for example, you might pick LINQ to SQL or the Entity Framework for your data access side. Then pick AJAX or jQuery to verify a form using simple validation. Store some data in XML and read it using LINQ to XML. LINQ to Objects opportunities are many with in memory collections, string parsing, etc. In other words think small and implement some items with a particular technology and you'll touch upon many things. From there you can begin to expand your scope and may decide to explore a particular technology further and do more with it.

I agree with David Basarab's recommendation for the free ASP.NET MVC ebook. In addition, be sure to check out the site. There are many videos and the StoreFront series is a well known example to follow along with.

I'm a beginner w/ Javascript. I'm looking at the following code that someone else wrote:

function MeetingPage()
   MeetingPage.colors = new Object();


var meeting = new MeetingPage();

From what I've seen, I believe that the MeetingPage function creates an object that later someone holds onto in meeting. What is the MeetingPage.colors? Is the MeetingPage prefix some kind of global? Is it a "this" pointer of some kind?

Any suggestions would be appreciated.

This talk was really helpful when I got into different object patterns in javascript. Example code is included in the second link (the video introduces it).

Of course, you should also definitely read


I must apologize if this is a duplicate question, but I can't seem to find one close enough to what I'm asking. I'll happily close this one if someone can point me to the duplicate.

Just for some background. I'm a developer that started in the .NET space with WinForms. While I did do some WebForms work, most of that work was spent very much in the classic Postback style of WebForms development and firmly routed in that particular abstraction. I very quickly found myself in the XAML world (primarily Silverlight). All of that is to say that all of my web development work has been primarily in a particular abstraction, with little or no "Close to the Metal" type work. I have very briefly looked at the Microsoft ASP.NET MVC stuff and found it very interesting, but it had to be put on the "back burner", while I focused on the things I worked with day-to-day.

I finally find myself in a place where I have enough time and determination to work with technologies (like MVC) that allow me to reach outside of those pre-made abstractions. The challenge is, that with all the time spent there, I don't know what I don't know. So, to the true question.

Can anyone recommend some good resources as a starting point for learning the technologies involved. I understand that I'll nee to brush up more on good HTML markup, JQuery, maybe an MVC framework or two. But also, where do I go to learn, what I as as a developer should understand about the HTTP Protocol, headers, etc...? Where can I go to learn what other base level technologies I should understand (as in what they even are) if I want to work in this more granular fashion? I cut my teeth in a Microsoft-centric space, and while working from that perspective may speed things up for me, I don't feel like using JUST those tools is a requirement by any stretch.

I truly hope that the question makes sense and is able to properly explain what I'm asking for. I have had difficulty articulating what I'm trying to understand. I very much feel that there are holes in my knowledge, that I'd like to fill. I'm just not certain I understand what and where those holes are.

Thanks in advance for your anticipated support.



You are definitely on the right track... but a couple points..

  • Don't work with jQuery until you learn the javascript language, it has many nuances that can easily trip up experienced classical programmers like yourself. I recommend Javscript: The Good Parts. Not to mention to stay true to you're commitment to learn "Close to the metal" Web Development...

  • Understanding that the HTTP model is stateless is BIG... ASP.NET WinForms tries to give the developer a state-full experience, which is going directly against the grain of the web. Request > Response... no persistent state is retained.

  • With the rise of RESTful web services really learning the HTTP model is a big help going forward.

  • MVC is essentially the industry standard and Microsoft has finally came on board. MVC3 is good and is leaps and bounds an improvement over WinForms, but still has that bloated feel. I would recommend PHP's Codeigniter as a good starting point... they don't do a lot of magic for you and you really learn a lot while using it. The PHP syntax is a bit verbose for my taste, but it should be fairly similar for you coming from a C based lang background.

I actually found myself in the exact opposite recently, going from a more "close to the metal" approach to (through work) moving to the ASP.NET Winforms model... really frustrating experience...

<script type="text/javascript">
    function CustomAlert() {
        this.render = function() {
            var winW = window.innerWidth;
            var winH = window.innerHeight;
            var dialogOverlay = document.getElementById('dialogOverlay');
            var dialogbox = document.getElementById('dialogbox');

   = "block !important ";
   = winH+"px !important ";
   = (winW/2) - (550 * .5) + "px !important ";
   = "100px !important ";
   = "block !important";

        this.ok = function () {

    function HighScore( arg )

Why is it telling me that CustomAlert is undefined? I also attempted to assign CustomAlert() to a var but then the console tells me that the var is now undefined.

Why is it telling me that CustomAlert is undefined? I also attempted to assign CustomAlert() to a var but then the consol tells me that the var is now undefined??

Because you should create an object of this

var customerAlert = new CustomAlert();

and then call the render method of it.

Or in one statement:

function HighScore( arg )
    new CustomAlert().render();

This is called the Constructor Invocation Pattern.

Actually in JavaScript functions can be invoked with one of the following ways:

  • The method invocation pattern
  • The function invocation pattern
  • The constructor invocation pattern
  • The apply invocation pattern

Method Invocation pattern

This method of invocation is used when the function is stored as a property of an object. Hence we call this function a method, like in other object oriented languages. When we call the function this is bound to the that object. For instance:

var app = {
    render: function() {
                var winW = window.innerWidth;
                var winH = window.innerHeight;
                var dialogOverlay = document.getElementById('dialogOverlay');
                var dialogbox = document.getElementById('dialogbox');

       = "block !important ";
       = winH+"px !important ";
       = (winW/2) - (550 * .5) + "px !important ";
       = "100px !important ";
       = "block !important";
        ok : function () {


In this case we would call the render method as below:


Function Invocation Pattern

This is the case where the function is not the property of an object. In this case the function is bound to the global object -which usually is the window object in web applications-.

var render = function(){
    var winW = window.innerWidth;
                var winH = window.innerHeight;
                var dialogOverlay = document.getElementById('dialogOverlay');
                var dialogbox = document.getElementById('dialogbox');

       = "block !important ";
       = winH+"px !important ";
       = (winW/2) - (550 * .5) + "px !important ";
       = "100px !important ";
       = "block !important";

Then we just call it as below:


Constructor Invocation Pattern

This is the case where we invoke a function with the new prefix. In this case a new object will be created. It is a good way to create object with the same properties. These functions are called constructors and by convention their names starts with a capital letter.

Apply Invocation Pattern

The apply method give us the opportunity to construt an array of arguments that will be used for the invocation of the function. Furthermore, it give us the ability to choose the value of this.

For more information on the above, please refer to JavaScript: The Good Parts

The variable value is not correctly set inside getJSON function. The variable $videoId displays 396 and 397 as expected in the first Alert.

But in the second alert, the value 397 is displayed twice.

Am I missing anything here? I could not find any other post here discussing this kind of issue. If so please point me over there.

Below is the jQuery code.

 $( "div .ow_video_list_item").each(function(){         
     $videoId = $(this).children("a").attr("href").split("/")[5];
     alert($videoId);    ==> First Alert

     $.getJSON("video/get-embed/" + $videoId + "/", function (data)   
         $.each(data, function (key, code) {                                  
             alert($videoId);   ==> Second Alert


Below is the HTML code:

<div class="ow_video_list_item ow_small">
    <a href="">Video 1</a>

<div class="ow_video_list_item ow_small">
    <a href="">Video 2</a>

A couple things.

  • In your code nowhere is $videoId defined, I'm assuming that $videoLink is really supposed to be $videoId. For future reference if might be easier to do something like these to access that data point

<a href="" data-video-id="396">Video 1</a>

That way you can access that video id easily with $(element).data('videoId'). There are other strategies for this, like using classes.

  • If $videoLink is NOT supposed to be $videoId in your code sample, then $videoId is defined somewhere outside of the scope of that function. There are lots of resources out there about scope/closures in JS. If you are doing a decent amount of JS dev work I would suggest Javascript: The good parts.

  • Going back to assuming $videoLink is actually $videoId in your code sample. You are assigning it's value inside of that .each loop BUT that variable itself isn't "closed" inside of that function. It's either global, or defined somewhere else outside the scope of that each loop. throw a var in front of the $videoLink = statement to keep that var contained.

  • Another potential issue is that you are calling an async call to the server, but depending on a variable outside of the scope of that async call. Most of the time these calls will be milliseconds, but a good way to understand what is going on is to mentally step through the code and pretend that each server call will take 1 minute. In your example the outer loop runs through once, gets the id of 396 then fires off an AJAX request, then loops again and does the same thing for id 397. The server hasn't responded in the time it took for the 2nd ajax request to fire off. So you have 2 ajax requests hanging out now. A minute later they come back and oh look, your $variableLink variable has the value of 397 because it was defined outside of the ajax callback function. Solutions to this? There are a few. You can use some data you get back from the server for what you need or you can keep an array/hash of potential videos being accessed from the server.

There are other ways to do it, but without knowing the exact use-case of what you are trying to do beyond tracking that variable it's hard to say. But this should give you a good starting point for it.

This is from Crockford's JavaScript: The Good Parts

var is_array = function (value) {
   return Object.prototype.toString.apply(value) === '[object Array]';

Would this code have worked just as well if he had used a simple equality compare == instead of the identity compare ===?

My understanding of identity is that it allows you to check if a value is really set to something specific, and not just something equivalent. For example:

x == true

Will evaluate to true if x is 1, or true, but

x === true will only be true if x is true.

Is it ever possible for the is_array function above to work with either == or ===, but not the other?

In this particular case == and === will work identically.

There would be no real difference in this case because both sides of the quality test are already strings so the extra type conversion that == could do won't come into play here. Since there's never any type conversion here, then == and === will generate the same result.

In my own personal opinion, I tend to use === unless I explicitly want to allow type conversion as I think there is less likelihood of getting surprised by some result.

Possible Duplicate:
What is tail-recursion?

What is tail recursion optimization?

In JavaScript: The Good Parts, Crockford says, "Some languages offer the tail recursion optimization. This means that if a function returns the result of invoking itself recursively, then the invocation is replaced with a loop, which can significantly speed things up."

Possible Duplicate:
JavaScript Variable Scope

I am (obviously) pretty new to Javascript, and I've seen several different points on other threads about the usage of Global and Local variables, but I'm trying to lock down some basic points on the subject in one place.

What is the difference between the following, declared outside (or used inside) of a function?

var thing = 1;

thing = 1;

I understand that using var declares the variable in it's current scope. So leaving out var makes it global. What are some pitfalls that can show up? Could someone give a simple example of where variables might step on each other in this case?

Thanks in advance.

Unlike many C-style languages, JavaScript supports block syntax but does not support block scope, so the following may not run as you would expect:

var foo = 'bar';

  var foo = 'baz';

console.log(foo); // 'baz'

This is also evident in other JavaScript constructs that support blocks like if:

var foo = 'bar';

if (true) {
  var foo = 'baz';

console.log(foo); // 'baz'

Moreover, as Bergi pointed out, your i counters for fors will override each other because a for will not create a new scope.

Crockford considers JavaScript's lack of block scope an "Awful Part" of the language. Instead, JavaScript has lexical scoping, so only functions will create a new scope:

var foo = 'bar';

(function() {
  var foo = 'baz';
  console.log(foo); // 'baz'

console.log(foo); // 'bar'

Every function in JavaScript has access to the variables in the function that contains it; inner has access to outer, but not vice versa. In the case of the above example, the IIFE (immediately-invoked function expression) has access to the foo = 'bar'; defined in the global scope, but instead we choose to override foo with a local var declaration and set it equal to 'baz'.

Bonus Point: Shog9 found that with can simulate block scope with an object literal like so:

var foo = 'bar';

with ({foo: 'baz'}) {
  console.log(foo); // 'baz'

console.log(foo); // 'bar'

Crockford discourages with due to its ambiguity, but if you really desire block scope, I see no harm in the with workaround.

Can someone suggest good learning materials or websites to learn JavaScript and jQuery? Am pretty new to this and want to learn right from basics.

Thanks in advance, Geetha

How do you manage Javascript content on a larger website? I'm especially struggling with various $(document).ready()'s and the fact that I need to juggle all those id ($('#id')) strings. I thought of combining the necessary $(document).ready() with each "module" that uses them but this results in visible speed degradation as I don't have my javascript at the bottom of each page anymore.

What is a good way to manage Javascript of a fairly large site efficiently and keep it easy to maintain?

If you are looking for a good resource on writing good and clean JS, you might want to look at Douglas Crockford's book JavaScript: The Good Parts as it contains many useful resources including tips on how to structure code well.

When I write apps which have a lot of JS, I typically create a single object (so as not to clutter the global namespace) and then divide it into sub objects which contain various bits of application data and behavior. A small example:

var PandaApp = {};
PandaApp.setup = {};
PandaApp.setup.init = function init() {
  // do something neat
PandaApp.utils = {};
PandaApp.utils.showMessage = function showMessage(msg) {
  // do some jQuery goodness or something

That way I have exactly one global object with all of my data in it and everything is neatly-namespaced in a manner of my choosing.

I am creating a custom object to be used in some internal applications where I work. I researched some ways to go about doing this - and this is what I came out with.

function ISGrader(text)
this.text = text;

this.printInfo = function(){
    alert("Object working " + text);    

this.putGrade = function(score)

I believe this shows constructor-type functionality, as well as some simple starter methods that I will build on.

Is the above good practice or is there another way that is more standard?

While not really an answer, I recommend Douglas Crockford's book JavaScript: The Good Parts as it does a good job of introducing you to the "good parts" of the language and discusses the pros and cons of the different ways to create objects in JavaScript.

You can also review this resource if you're just looking for an explanation of member visibility in JavaScript objects:

i am new of javascript, i have been told by someone, he said "speak strictly, javascript doesn't have multidimensional Array and associative array ". but in a book, i saw the following

var my_cars=Array();


so the opinion form he is wrong? am i right?

JavaScript has arrays of whom their elements can be other arrays.

However, JavaScript has Objects with properties, not associative arrays.

Buy a better book.

  1. [] is much better than Array(). Also, why not instantiate an Array object explicitly then rely on Array returning a new object?
  2. The example is setting the property cool on the Array.
  3. Why the $a sigil? Why no new operator again?

I just decide to learn backbone.js. I am a between junior and intermediate level front-end developer. my current job is dealing with html, css and jQuery. My boss asked me to learn this backbone.js and want to know how long it gonna take me to learn. so can anyone who experienced before tell me how long it gonna take?

thank you

If you don't know javascript, it will take awhile. I know this because I didn't really understand javascript when I got started with it. By know javascript, I mean being able to understand and fully explain:

  • Variable Scope
  • Object.prototype
  • .call, .apply, and .bind
  • Closures/Lexical Scope
  • Anonymous functions
  • Function Hoisting

If you don't know all that, get and read Crockford's Javascript: the Good Parts

If you do know all that, then you need to understand how to use Backbone properly otherwise it won't make any sense. When using Backbone, you really shouldn't have any non-backbone javascript outside of a sparse initialization of your base Views...also learning how to use the built in event binding is essential. This is a pretty good guide, as (obviously) are all the sources here

So I would say it could take a few days to a week or longer to fully comprehend whats going on, and much longer to get to the point of being very skilled with it.

I'm spending a lot of time to learn how OOP is implemented in Javascript as in ECMA 262 of 1999: now I want to know if someone think that the new JS 2.0 will arrive soon and I'am studying uselessly because with this new version will be the OOP implemented in a classical way (Java etc.) and will be interfaces, generics and other classical languages features...

So do I must stop and wait...........?????


I would highly recommend you learn JavaScript as it is. Whatever changes may come, you'll still be forced to deal with the historic usages sooner or later, and probably very often if you are a web developer. I would also recommend Crockford's JavaScript: The Good Parts, as it covers all modes of inheritance and strips away the bad stuff you shouldn't use.

I need to , well, dive into client side programming. Is there an equivalent to 'Dive into python' for jquery?

I see that jquery 1.4 has been released. Does this change anything w.r.t answers?

Well python is a language and jQuery is a framework, so I'll give you one for javascript and then you can move to jQuery:

This book should be a required read for front end devs:

JavaScript: The Good Parts by Douglas Crockford


The jQuery Cookbook

This one is a pretty awesome dive into all the different aspects of programming real world applications with jQuery, whereas "Dive into Python" and "JS The Good Parts" are more like poignant language overviews.

I've been learning Js recently from "JavaScript the Good Parts", and according to my understanding

Object.propertyName yields same result as Object["propertyName"](Please correct me if I'm not right and describe the difference of the two).

I'm trying to augment the Function.prototype to make a method available to all functions as below:

Function.prototype.method = function (name, func) {
            this.prototype[name]= func;

And it's working fine.However, when I'm replacing the this.prototype[name] with, it'll fail functioning as expected!

This is how I'm testing it:

 Number.method("myRoundFunction", function () {
        return Math[this < 0 ? "ceil" : "floor"](this);
    console.log((-10 / 3).myRoundFunction());

This shows the expected value (-3) when using this.prototype[name], but

(-3.3333333333333335).myRoundFunction is not a function

on changing it to

Could someone possibly clarify why this is happening?

Thanks in advance for any help.

What's happening is that name is a variable, and cannot be used directly with dot notation. To better illustrate the issue, let's say you pass a value of "newMethod" for name. Now when you do:

this.prototype[name] = func; is equivalent to writing:

this.prototype["newMethod"] = func;

But when you do: = func; are assigning to the name property of the object, and not to the newMethod property. The variable that you passed under the parameter name is not referenced at all in the above statement.

The syntax that would preform the assignment you expect is:

this.prototype.newMethod = func;

But you cannot express that using dot notation and the name variable (except perhaps by cheating and using string concatenation and eval()). In such a case you have to use the array-subscript notation instead.

I've been reading through JavaScript: The Good Parts and I'm currently on "Chapter 5: Inheritance."

From what I understand, using functional inheritance is preferred because it allows privacy for the properties and variables of an object while still allowing them to be called using methods outside of the object. However, it does seem like there is an advantage for prototypal inheritance because you can create a prototype object fairly easily (which makes understanding what the object is, to me, a little more concrete).

When should I choose one over the other? Should I always use functional inheritance whenever possible? Or are there "better" guidelines that I can follow to make that determination?

I've seen very little code that uses functional techniques as the primary form of inheritance. The vast majority I've seen uses prototypal inheritance. It's fast and easy to implement, and seems most natural to JavaScript.

That's not to say that functional inheritance should never be used, but I think you'll find prototypal more than sufficient for most applications.

Let's not also forget that you can still use some functional techniques within your prototypal inheritance, like giving each object it's own version of a function that closes over a variable in the constructor. So it doesn't need to entirely be one or the other.

Most important is to understand the concepts of prototypes and functions/closures. This alone will give you what you need to know in order to make appropriate decisions.

I was wondering whether it would be ok to name the variable name for a promise just like the argument passed to a callback:

var dbItems = db.find();
dbItems.then(function(dbItems) {
    // Do some stuff with dbItems here...

I think that would be syntactically correct, but are there any arguments (like possible confusion or readability) against using this from the perspective of code style?

var dbItems = db.find();
dbItems.then(function(dbItems) {
    // Do some stuff with dbItems here...

Is the same thing as writing:

var dbItems = db.find();
dbItems.then(function(xxxxx) {
    var dbItems = xxxxx;
    // Do some stuff with dbItems here...

which means that inside the anonymous function, dbItems is a completely different thing, and you do not have access to the "outer" dbItems variable.

I don't usually recommend purchases on this site, but I feel that you could have very good use for this book.

Maybe is tutorial's, article's, book's or something other to how design Game Engine(-Library, Framework) Architecture in JavaScript(HTML5 Canvas or DOM)? I am searching in Google but don't find. And have one more question: Why one framework's use Anonymous functions in this style(1) and other in this style(2)? 1:

var Engine = (function() {
    var version = '0.0.1';

    return {
        version : version


(function(window) {
    window.Engine = {
        version : '0.0.1'

Or something like. Which is better?

Neither of those are better, they are functionally pretty similar. The second one is guaranteed to attach Engine to window and the first one will only do so if it is executed in the top-level.

The second one is used by jQuery and is arguably more common.

If you are very new to Canvas, there is the book Foundation HTML5 Canvas: For Games and Entertainment. It is a pretty average book, and only really useful if you are very new to this stuff. It might help you get started though.

Designing a good game-engine is a pretty broad and platform-agnostic topic though. If I were you I would seek out articles on designing engines in particular, moreso based on the type of engine you want to make (FPS? Point and click game? Side scrolling game?)

How you design it will depend on the type of game a lot more than it will depend on than the language and platform involved.

So what I'd really suggest is that you read JavaScript: The Good Parts by Crockford to get an idea of how JavaScript is different from other langauges. Then search the net for more general articles on game engine development, considering the type of game engine over the language.

   out = rogueArray[13];
   for (var arrayItem in vanWilder) 

I'm a noob, so I need help :P

This is what I am told on JSLint:


Problem at line 52 character 18: Move 'var' declarations to the top of the function.

for (var arrayItem in vanWilder)

Problem at line 52 character 18: Stopping. (30% scanned).

Implied global: requestOne 19,22,25,27, XMLHttpRequest 19, document 29, out 51

Unused variable: evilVariable 25 "onreadystatechange", redBull 25 "onreadystatechange", wildGoose 25 "onreadystatechange", monkeyWrench 25 "onreadystatechange"

How would I fix this? If not the second error, the first one at least!

Problem at line 52 character 18: Move 'var' declarations to the top of the function.

Because JavaScript doesn't have block scope, and variable definitions are hoisted, Crockford recommends you place all variable definitions at the top of the scope.

Implied global: requestOne 19,22,25,27, XMLHttpRequest 19, document 29, out 51

Because out doesn't have the var keyword to the left, it will be attached to window, essentially making it a global.

Unused variable: evilVariable 25 "onreadystatechange", redBull 25 "onreadystatechange", wildGoose 25 "onreadystatechange", monkeyWrench 25 "onreadystatechange"

You must have defined a variable evilVariable somewhere and not used it.

Remember, Douglas Crockford is a smart man and his JavaScript book is excellent, but take his word and JSLint as one man's recommendations and not the gospel. :)

Regarding this question: What is the purpose of NodeJS module.exports and how do you use it?

I'm a Javascript beginner. In the referenced question...

mymodule.js code

var myFunc = function() { ... };
exports.myFunc = myFunc;

main js file

var m = require('./mymodule.js');

Is mymodule essentially a class file defining objects?

Node.js allows code to be separated into different modules. This modules are just javascript files that can expose functions or objects using the exports object.

  1. There are more details of this convention
  2. Nice documentation of the Node.js modules

There are no Classes in JavaScript but you can use patterns to emulate that behaviour. There is a question about implementing OOP patterns in JavaScript: what pattern to use when creating javascript class?

As a beginner there are very good books for JavaScript:

  1. JavaScript: The Good Parts
  2. JavaScript Patterns

They are short and will give you a very good insight of the JavaScript Language.

This isn't as progressive as it sounds. Im not taking the whole "Oh I know Java, that must mean I can write in JavaScript too!" attitude. I have some education on Java under my belt, but now find myself having to do some PHP web development (which I have little experience in) using Java Script to handle some of the logic. But before going out and buying 2 or 3 books on JavaScript and diving right into it, I figure I might ask those that might have gone through the same experience. It appears that JavaScript lives and acts in its own environmnet which makes want to take the approach taking in JavaScript and PHP as a bundled package in my learning endeavors. JavaScript is similar just enough to Java that I will tend to make some dangerous assumptions. Should I treat JavaScript and PHP as one item, or should I still take this step by step and learn one at a time? What are some pitfalls that I might run Into? What are the main differences between the languages? Is there any litterature that has helped? Thanks Everybody.

I learned Java script coming from Java myself. I had a bit of trouble with it until I worked with NodeJS a little bit. Learning JS by itself when I wasn`t warring with html and css at the same time made the experience much less painful and made it take less then a couple days.

I would really recommend these two books

Don`t be turned off by the fact the first book is related to a frame work. The first 250 pages are a fantastic JS basics crash course.

Of course you are super comfortable with objects and you can find that in Javascript if you really wanted to and never even learn about prototyping and closures. Take the time though to read into these things there are a lot of timing problems that you really can`t solve any other way with respects to asynchronous actions and animation locks.

Research functional programming.
The hardest thing about the transition is javascripts wonky syntax at first you will hate it but it does finally catch a rhythm. Which reminds me use Lint a lot that will help you catch your syntax issues early.

UPDATE: Perhaps this wasn't clear from my original post, but I'm mainly interested in knowing a best practice for how to structure javascript code while building a solution, not simply learning how to use APIs (though that is certainly important).

I need to add functionality to a web site and our team has decided to approach the solution using a web service that receives a call from a JSON-formatted AJAX request from within the web site. The web service has been created and works great. Now I have been tasked with writing the javascript/html side of the solution.

If I were solving this problem in C#, I would create separate classes for formatting the request, handling the AJAX request/response, parsing the response, and finally inserting the response somehow into the DOM. I would build properties and methods appropriately into each class, doing my best to separate functionality and structure where appropriate.

However, I have to solve this problem in javascript. Firstly, how could I approach my solution in javascript in the way I would approach it from C# as described above? Or more importantly, what's a better way to approach structuring code in javascript?

Any advice or links to helpful material on the web would be greatly appreciated.

NOTE: Though perhaps not immediately relevant to this question, it may be worth noting that we will be using jQuery in our solution.

This is just the sort of thing people use jQuery for. It has Ajax and DOM manipulation covered, so the learning jQuery site and the jQuery docs should help you hack something together.

In general, JavaScript is tough to work with because it looks just like a typical Algol-family language, but misbehaves in subtle ways. (For instance, JavaScript does not have block scope.) If you want to invest some time, the basic book to get is Javascript: The Good Parts. The author has some interesting articles at his website.

Your design, btw, is perfectly fine, and JS is object-oriented, so you could certainly implement it. JS just does inheritance and encapsulation differently (prototypes and closures, respectively) than mainstream OO languages. This is all covered in adequate detail in the book cited above.

As someone who will be working extensively with JavaScript and JQuery, I hear the community is strong so I figured I would ask what a beginner should been keen in understanding when developing mobile applications. Like any other language, I wish someone would have walked in the first day of class when programming with C and said to me, "if you don't learn everything about malloc() and free() today, you will fail!" Or when I was writing with Java and heard that private and static are essential for every function and variable too late. See what I mean about learning the most important so I don't get frustrated with the details later. My current attempt at figuring this question out is reading a book, but like most books, they don't expect you to ask what is the high-level re-occurring concepts. I have used CSS and HTML and have not used scripts or Jquery as much when developing websites.

Read "JavaScript the Good Parts" by Douglas Crockford

This will give you what you need for JavaScript. I don't know "the best" source for jQuery, but start here:

I'd like to implement URL shortening service in my application and from's API docs I read It uses JSON to short a link...
Unfortunately, I never used JSON and I don't know where to start.
Can anyone explain me how to implement URL shortening service in my application?


JSON is just a (Javascript) way to encode you're data in name value pairs in an http POST request. So you just need to use a good encoder/decoder API for you're iphone application. See also this tutorial:

tutorial: Json over http on the Iphone

Want to know more about how JSON works, this book has an excelent chapter on it:

JavaScript: The Good Parts

Can any one here suggest a good Dojo and JSON book or a site for tutorials please for a graduate student.

Many Thanks!

I wouldn't really recommend reading a book since you can get very close to the same content online if you know how to look for it, but if you insist, the definitive guide books are always very helpful (you'll need to purchase two off them though to get info about dojo and json):

Javascript: The Definitive Guide will teach you everything you need to know (and more) about JSON, and will prepare you for using frameworks like Dojo, Mootools, jQuery... etc.

I own David Flanagan's Most Excellent "Javascript: The Definitive Guide" and I agree - it's a must-have for any Javascript developer.

... however ...

The one framework Flanagan covers is jQuery (not Javascript).

I'd recommend the on-line IBM Redbooks for Dojo and JSON:

Etc. etc

And, even more than Flanagan ("The Rhino Book"), I'd very strongly recommend Douglas Crockford's "Javascript: The Good Parts" as a must-have for every Javascript developer:

Douglas Crockford makes reference to Simplified JavaScript in this article about Top Down Operator Precedence. Unfortunately he only makes references to it in this article. The best explanation I found here. But I still don't have a clue what it actually is.

What is Simplified JavaScript?

This is probably a reference to Crockford's book Javascript: The Good Parts. In this book, he describes which features of Javascript he feels are "good", as well as those that are "bad" and shouldn't be used.

First what i mean by patterns.. Basically in Js there are multiple ways to do something but some ways of doing things offer greater benefits in terms of portability, performance, modularity, and extension. One of the patterns i like most are of jquery.

But when writing my own code i feel urge to just keep on writing function after function...and i don't want to create an object just for the sake of organization. There should be a reason like reusability for object to be created.

I want to learn patterns that make more use of closures, prototype, objects and chaining. So i can write better code.

I know keeping code simple is best but when things are wide spread keeping code less intrusive and reusable is maybe more important.

I watched this Google talk a few weeks ago and was inspired to read Crockford's entire book, "JavaScript: The Good Parts". Watch the talk and I think you'll find it's exactly what you're looking for, full of best practices for using closures & prototype. It's a little old and just covers core JavaScript, nothing about JQuery, ect. but if that's what you're looking for, this is your book.

I am about to move to a job where I will be doing front end web development (mainly CSS and jQuery).

What are good resources (books, websites, blogs etc.) for learning more about those technologies in particular and anything front-end web development related (good technologies to know, user interface ideas etc.) in general?

Thank you!

ETA: Just to give some idea of where I'm holding, I have about 1.5 years of experience in web development. So I already have a pretty good grasp of CSS and know the basics of jQuery. I also know a fair amount about user interface design.

i assume you will also be doing HTML since this is at the core of FE dev. HTML, seems simple and is easy to ignore as a technology, but you should not turn your nose up to it. Writing terse, clean and semantic HTML is a skill and requires lots of learning and practice just as CSS and JS.

Right, now onto things you actually requested :)

For jQuery i would definitely consider learning as much as you can about JavaScript proper. Whilst you can write jQuery without knowing all that much about JavaScript, you need to understand JavaScript to make the most of jQuery and write better code. And of course to know when you can get away with using plain ol' JS.

JS resources:

CSS resources:

Good websites to have in your RSS client:

hope that helps in your quest into front-end development!

I am new in Javascript but I did a lot of C#, VB.NET and Java programming that those languages are fully object-oriented. It seems Javascript cannot support all OO features.

I am looking for a Javascript object-oriented syntax reference.

What should it include is

  • Inheritance syntax
    • Call parent constructor in child constructor
    • Refer to the instance of parent object
    • Multiple inheritance (It seems it is OK for javascript)
    • Inheritance type checking
  • Static/Shared methods
  • Public fields
  • Protected/private fields (I am not sure Javascript have it)
  • Interfaces?

Read Javascript, the Good Parts by Douglas Crockford, and you will get what you are looking for.



On Stack Overflow


I am new to JavaScript and am trying to learn how to upload images on my screen and then swap it. The way I manage it is using the following code:

 for(i = 0; i <= 5; i++) { 
  N= " + i;
  document.write("<img id= " + N + " src='graphics/" + N + ".jpg' onclick='swap(id)'/>");  

However, I want to learn how to use an object orriented way to do it and work with objects, but I found it very difficult to make it work. How to use OO? Using OO, I want to use an array of 3*3 size and swap the images on mouse click.

OOP with JavaScript is a bit different. Like you, I'm relatively new to this topic so I have been trying to teach myself over the past couple of months. I would recommend reading over some of the articles posted by the other users as well as some of these:

You didn't really specify what exactly you wanted to do with OOP in terms of code, so I can't really provide specific code, but I highly recommend reading these articles and others that you find on the web to get a general idea of what JavaScript is like, how it works with the DOM, and how it is related to OOP.

I hope this helps.


I am working on a small JavaScript application that will users to click on buttons on the page and pass it through to thier basket. The problem I have with doing this is I am unsure as to handle multiple buttons within the same function. I do not want to have to write out different functions for each button.

I am trying to do it OOP and have this so far:

var shop = {};

shop.items = [];

shop.Item = function(item, description, price) {
    this.item = item;
    this.description = description;
    this.price = price;

shop.print = function() {
    var itemCon = document.getElementById('items'),
        html = "";
    for(var i = 0; i < this.items.length; i++) {
        html += '<div id="item">';
        for(prop in this.items[i]) {
            html += '<p><span class="title">' + prop + '</span>: ' + this.items[i][prop] + '</p>';
        html += '<button id="' + this.items[i].item + '">Add to Basket</button>'
        html += '</div>';
    itemCon.innerHTML += html;

shop.items[shop.items.length] = new shop.Item("Coat", "Warm", "20");
shop.items[shop.items.length] = new shop.Item("Coat", "Warm", "20");
shop.items[shop.items.length] = new shop.Item("Coat", "Warm", "20");
shop.items[shop.items.length] = new shop.Item("Coat", "Warm", "20");

var basket = {};

basket.items = [];

basket.Item = function(item, description, price) {
    this.item = item;
    this.description = description;
    this.price = price;

basket.add = function(data) {
    this.items[items.length] = new Item(data.item, data.description, data.price);

basket.costCalculate = function() {
    var cost = 0,
        html = "Total: " + cost;
    for(var i = 0; i < this.items.length; i++) {
        cost += items[i].price;
    return html;

basket.print = function() {
    var output;
    for(var i = 0; i < this.items.length; i++) {
        for(prop in this.items[i]) {
            console.log(prop + ":  " + this.items[i][prop]);

function init() {
window.onload = init;

How would I determine what item has been clicked in order to run basket.add(data). How would I also pass through the data to that function for each item.

Also how would one go about implementing closure? I understand that it is inner functions having access to the variables of the outer functions, is what I am doing working with closure so far?

Okay, you've made a pretty good start but here are a couple suggestions:

  1. It's probably a good idea to only have one instance of each Item. By that I mean it looks like you create a bunch of Items for to populate your shop's inventory, so for example:

    var coat = new Item("Coat", "Warm", 20);

    Now when you click on your UI element, you ideally want this same instance of coat to go into your basket as well, so:

    // User clicks on UI element, which triggers the following to execute:
    basket.add( someItemIdentifier );

    So now if you ever decide to increase all your prices by $10, you can simply do:

    shop.increasePricesBy = function(amount) {
        for(var i = 0; i < shop.items.length; i++) {
            shop.items[i].price += amount;
        // execute some function to update existing baskets' totals

    I hope this makes sense for why there should be one instance of each item that multiple collections refer to.

    This begs the question how you can tie the customer's interaction to adding the correct item. One solution could be to use arbitrary IDs to track items. For example:

    // Create new item with some randomly generated ID
    var coat = new Item({
        id: "93523452-34523452",
        name: "Coat",
        description: "Warm",
        price: 20
    shop.items = {}; // Use a hash so it's easier to find items
    shop.items[] = coat;

    And your UI element could be some div like so:

    <div class="add-product-button" data-id="93523452-34523452">

    Add your click handler:

    // Pure JS solution - untested
    var clickTargets = document.getElementsByClassName("add-product-button");
    for(var i = 0; i < clickTargets.length; i++) {
        var clickTarget = clickTargets[i];
        clickTarget.onClick = function() {
            var itemID = clickTarget.getAttribute("data-id");
            var item = shop.items[itemID];
    // Equivalent jQuery code
    $(".add-product-button").click(function() {
        var id = $(this).attr('data-id');
        var item = shop.items[id];

    While your basket implements add something like:

    basket.add = function(items) {

    And your costCalculate method gets a whole lot easier:

    basket.costCalculate = function() {
        var cost = 0;
        for(var i = 0; i < this.items.length; i++) {
            cost += this.item[i].price;
        return cost;
  2. Instead of doing this:

    shop.items[shop.items.length] = new shop.Item("Coat", "Warm", "20");

    You can instead do:

    shop.items.push(new shop.Item("Coat", "Warm", "20");
  3. Probably a good idea to use a number instead of a string to represent the price.

  4. In your shop.print loop, you probably don't want to hard code <div id="item"> because that will result in multiple divs with the same id.

  5. Finally, I'm not going to try to answer your closure question here because I think that's been answered better than I can already so I'll just link you to some great resources that helped me understand it:

Let me know if you have any questions, I'm totally down to discuss them.

I have a Struts + Jsp + Java application and I have .js files for javascripting my jsp files. I need to use some (same) constants both in Java and Javascript files.

I have defined the constants in my java classes. I also need to have those constants in my javascript files. Is there a way such that I can use my Java constants in my javascript? What is a good practice?

Right now, I am defining them twice, once in Java classes and then in Javascript files.

At the top of the JSP that includes the .js file, emit a javascript block that declares the javascript constants. For example:

<script type="text/javascript>
var myConstant1 = <%= MY_CONSTANT1 %>;
var myConstant2 = <%= MY_CONSTANT2 %>;

This is a very simplistic answer - note that you probably shouldn't really be creating a bunch of global variables in JavaScript - you should create one object that wraps all of your constants (see, but this demonstrates the general concept.

I have a medium size legacy php application with almost no javascript integration. I've recently been learning javascript (yes actually learning it) using Douglas Crockfords excellent book and taken YUI as my library of choice. I've tried out a few things and got a few things working but now I want to integrate the various components etc into my application properly, my question is how to go about doing this for ease of maintenance and code reuse.

Currently the application consists of

  • php pages
  • smarty templates (html templates with some special template markup) for each section of a page so multiple templates may be used for a single page.
  • single css file.

I have the following ideas about how to integrate my javascript into the pages.

  1. Write inline javascript in each smarty template with the code required for that section.
  2. Write a seperate .js file to go with each smarty template that is linked in and then a single inline script to run it.
  3. a seperate .js file for each php page which would have all the functionality required for the entire .php page. A small inline function would call whatever functions were required.
  4. Something I havent though of?

Does this make any sense? Does anyone have a good suggestion for this?


One extra bit of info is that its an internal application, so its not so important to restrict everything to a single file.

Two other options:

  1. A single JS file that contains all the JS for your entire site. Depending on your caching settings, you should be able to get the user to download just one file for the entire site and use a cached version for every other page.
  2. Divide your JS up according to function, rather than page, and include whatever functionality each page requires. E.g. one page may require tabs, form validation and animation, while another may only require tabs.

Or you can have a hybrid of these: one JS file that contains the vast majority of your code and an extra file if needed for particular pages or templates.

None of the approaches mentioned are wrong (though I'd skip the inline JS one as much as possible); which one is best will depend on your precise situation and your personal preferences.

I have just started writing my own JavaScript Framework (just for the learning experience), and have prefixed some private members with a _, like such:

var _isFireBugEnabled = function () {
    return (window.console && window.console.firebug);

When I ran my code against Crockford's JSLint (as always), with Recommended Options on, I was told about not using a _ as an identifier.

My question is, Why does JSLint warn me as regards not using a _ as an identifier?

Are there some side effects or implications I am missing here?

PS. As far as I could scan just now, this is not documented in the book

The reason is that Douglas Crockford hates about 78% of Javascript*. Many people think he's a bit strict, and in fact many libraries do use leading underscores in production code. I don't see much wrong with it. There are no side effects.

Additionally, the '$', not the underscore, was the symbol set aside for "system" code by the ECMA spec.

from ECMA 262, section 7.6:

This standard specifies one departure from the grammar given in the Unicode standard: The dollar sign ($) and the underscore (_) are permitted anywhere in an identifier. The dollar sign is intended for use only in mechanically generated code.

*Note: I'm being facetious. He really only hates about half, and he typically has good reason. I'd disagree with Crockford here, but he's usually very right.

I have started to use jQuery.. I am struggling to understand how the organise the code and how to use it properly. At the moment I am using code similar to:

    alert('all of the jquery goodness here');
    /* some manipulation stuff here */

Is there a better way of having loads of click handlers after the dom has loaded ?

Also is there some links to where I can get information regarding code layout in jquery ? I've been looking around source code but cannot find anything useful..

Thanks guys


Another quick question whilst I remember - Is it bad practice to use something similar to:

function clickedevent(){
    $('').toggle or other random jquery function

Look into the Module Pattern to write more Object-Oriented javascript. While on that topic, an excellent read is Douglas Crawford's 'Javascript: The Good Parts'. Here is an example of the module pattern with jQuery:

  window.MyCoolModule= (function(){
    var doCoolStuff = function(){
    var otherCoolStuff = function(){
        alert("someone..moved their..mouse.. all over me");

    var superSecretPrivateFunction = function(){
        // come at me bro

        somePublicFunction: function(){
            //hello, i can be called by other people

        init: function(){
                    .bind("click", doCoolStuff)
                    .bind("mouseover", otherCoolStuff)

                .bind("click", superSecretPrivateFunction)


Some points to note:

  • Everything under "return" is public (it can be called by other objects) and everything above that is private (cannot be accessed outside this object)

  • I lump all my bindings into one block of code '.bind("click", doCoolStuff)', so at a glance you can see all the DOM elements your module is listening to.

  • I give the event handlers descriptive names rather than defining them inline '.bind("click", function(){}'.

  • User 'bind("click", ...)' rather than '.click', even though they do the same thing. This is because jQuery also has a 'unbind' method which is useful, and I like having the mirrored reciprocal naming. But the bigger reason is that you can namespace functions. i.e you can do 'bind("click.customNamespace, ...)'. A reason to do this is that you can later do '.trigger("click.customNamespace") and it'll trigger only those namespaced events as opposed to all click events.

  • You could do the $.ready check inside of init instead of outside - matter of coding style.

I have this code i am working on but every time i call init method I keep getting an error

this.addElement is not a function

is it because i can't call methods from event handlers ?

function editor () {

    this.init = function () {
        $("#area").bind('click' , this.click_event );


    this.addElement = function () {
        console.log("adding element");

    this.click_event = function(event) {
        console.log("click event in x : ";
function editor () {
    var that = this;

    this.init = function () {
        $("#area").bind('click' , this.click_event );


    this.addElement = function () {
        console.log("adding element");

    this.click_event = function(event) {
        console.log("click event in x : ";

You should read this book, JavaScript: the Good Parts and visit the Crockenator's web site here,

You can also read about the JavaScript "this" issue here,

I have tried:

<script type="text/javascript">
  var myVar = "some string";
<input name="&{myVar};" ... />

But using FireFox, the name is set to the literal string: "&{myVar};" instead of the value of myVar...

UDPATE: I see this called JavaScript Entities and hasn't been supported for a long time - but there must be way if one can include JavaScript directly in events (I realize attributes are not events, so JavaScript probably isn't evaluated).. ?! It would be a lot nicer than hardcoding the value as it used elsewehere a lot..

Here's what you need to do.

Start by never reading javascript tutorials from a Java site again. Different monsters entirely, plus the tutorials on the site you're referencing are horrible.

Second, get a copy of Javascript the Good Parts, This book is perhaps the most useful book ever written (in my opinion) about the language itself. It doesn't say anything about dealing with DOM API's.

I encourage you to learn the language itself before getting too deep into javascript libraries like jQuery. It'll do you a load of good sooner rather than later.

Once you're at least somewhat familiar with the proper ways to use javascript as a language, start investing your time into one library or another. jQuery is probably the most used, well loved, and kindest library out there. It will make dealing with cross-browser crap SO much easier for you.

I know you should avoid it, thus although annoying I always protect myself against it.

But what exactly causes extensions to a prototype to show up when using "for in"? Sometimes it is (or seems to be) safe to use "for in" and other times it isn't.


I'm talking about for example:

Array.prototype.last = function(){ return this[this.length-1]; }

Showing up as:

for(var k in someArray){
    console.log("%o %o", k, someArray[k]); // eventually outputs "last 'function(){ return this[this.length-1]; }'

This behavior is by design.

for in loops over all enumerable properties, including those inherited from the prototype.

I'm confused by this example from Google's Apps Script Guide. This function iterates over given range and performs a computation on each cell.

function DOUBLE(input) {

  if ( {            // Test whether input is an array.
    return; // Recurse over array if so.
  } else {
    return input * 2;


Things I don't understand:

  1. What object is the input in this function? typeof tells me it is a number, but shouldn't it be an array? It is after all a range of values (e.g. A2:B).
  2. What is the .map thing after the input variable? I cannot find it in the reference page. It is also not highlighted, as variables or functions are.
  3. The purpose of the conditional statement is unclear to me. Does return mean "do whatever you find in the corresponding else statement over the whole array"? Why is it structured like so?

Any insights (or pointers to the right sources) much appreciated.

This code is an example of using introspection to conditionally execute the code. if ( will return truthy if input is an Array (and has a map function) and will return falsy in all other cases.

This code is therefore testing to see whether input is an Array and if not, it is treating it as a number, otherwise it is treating it as an Array.

You can see the definition of the map function on MDN

Best book to learn about JavaScript is "JavaScript the Good Parts"

I'm fairly new to JavaScript. Can anyone share some good advice on getting started? I have a little experience in ActionScript 3 and have taken a few Java classes toward my CS degree but my background is of a designer transitioning into development. My goal is to become a well rounded front-end developer and I'd like to move beyond the simple slideshow animations and rollover effects. Any guidance/wisdom will be much appreciated!

I'll recommend some reading materials:

Beginner: JavaScript: The Definitive Guide

Intermediate: JavaScript Patterns

Advanced: JavaScript: The Good Parts

The best way to learn is practice. Write a simple application. When you are done, rewrite it so you learn what you did wrong last time. Perhaps, rewrite it again. Then, take on a new project. Repeat :).

I'm trying to learn JavaScript, but seem to be going around in circles regarding primitives, objects, functions, etc. I can code fairly well in Python, so the JavaScript part is now mostly about syntax and idioms.

I am overwhelmed by the choices and I'm not sure how to choose: Prototype, jQuery, Dojo, Node.js, Backbone.js, etc.

What would be good JavaScript framework/s to pick up after mastering the basics? At the risk of betraying my JavaScript naivete, I'd like one (or a combination of) framework wherein I can do asynchronous requests, data visualization, and UI implementation.

I wouldn't be right to not first say to make sure you understand JavaScript itself first. It's a rather unique language with both good parts and bad parts. If you take the time to understand closure, prototypal inheritance, this keyword, constructor functions, etc, you will thank yourself. JavaScript, The Good Parts is an excellent place to start. Anyways...

For basic DOM manipulation, event handling, ajax, etc jQuery is the clear winner. In the past, Prototype/Scriptaculous was a common alternative.

For more advanced browser-based applications, Backbone.js, Angular.js, and Ember.js are the winners.

Dojo, Mootools, ExtJS, and Knockout.js are some alternatives to Angular and friends... all with varying strengths and focuses.

There are countless libraries for charting. HighCharts is a popular one. For more advanced visualizations, check out D3.js and Raphael.

Node.js is different beast. It's a server-side, network IO platform. It's competitors are things like Python's Twisted and Ruby's EventMachine.

Of course this topic has been covered in great length here:

I need to know how I can use a class in angularjs.

A simple class like this:

function Person(name,age){;
       return age;

I am learning angular but I can't find an answer to this. I want to create Person instances and use the name, age etc. in the view.

Please a simple solution because I am from a C# OOP background and don't know js frameworks. But I want to use the MVC pattern. Thanks!

AngularJS is a framework that is written in and used through JavaScript. Although JavaScript has many object oriented features, it handles inheritance quite differently. This used to be confusing to me too until I read the excellent: JavaScript: The Good Parts by Douglas Crockford. I suggest you read this, it's quite a brief book and points out differences in approach in a very clear and concise manner.

I've always been dabbling in javascript, but never really got hugely into writing a lot of javascript until last year or so. One thing I noticed is that my javascript started to grow so complex, that parts of it were more complex than the server's application code (minus all the framework code of course, such as Spring or Hibernate).

This caused me to realize that if you want to write a complex javascript application, in the same way you've been writing complex web applications on the server, you have to start thinking about best practices, architecture, how you structure your files, how you test your code, what abstractions do you use to create smaller, more reusable components, what is the best way to pass parameters and send messages, should i pass parameters or object literals, and just best practices all around. None of this provided or encouraged by Javascript itself, and everyone seems to have its own way of going about everything.

And of course, because Javascript offers such very poor api out of the box, I often spend a countless amount of time researching what the best tools for the job are. Facilities like importing files and dependencies, or even a basic collection library, are things NOT handled by the language. Let's not forget that IDE support, even in something like Idea 10.5, is actually pretty bad and nowhere near as rich as say Java due to its dynamic nature and the lack of these hard-bindings for packages and imports.

Outside of jquery, which I really like and feel comfortable with, I still haven't made any decisions as to the "right" way to do things either. This is odd to me.

Everyone seems to have their own coding idioms too - they either write in a pure functional style, or they try and create a whole classical programming model and then use that. People's coding standards and idioms vary from library to library and person to person. All of this makes knowing what the "right" thing to do an incredible task.

Even worse, there doesn't seem to be books on this sort of thing. It's like nobody has bothered to tackle it - which is totally contrary to what we have in the Java space, or many other spaces for that matter.

What is the right/successful path to having a refined way to successfully write nice-looking and robust javascript for complex web applications?

I feel like my knowledge of Javascript expanded and became more complete after reading Douglas Crockford's Javascript: The Good Parts. He really clarifies the most difficult and important parts of the language.

Reading it made clear the different types of inheritance: neoclassical, functional, prototypal. And the different ways to invoke a function: constructor invocation, apply invocation, function invocation, and method invocation.

I would start there.

I want to learn how to write the Javascript/CSS/HTML side of my applications but I want to skip the CSS kludges, bad Javascript, and non-semanitic HTML of the past and jump directly to HTML 5, CSS 3, clean Javascript libraries. I've been reading Mark Pilgrim's Dive In HTML 5 which I think is awesome and now I'd like the equivilent books (or blog posts) for Javascript and CSS.

Any suggestions?

These are my recommendations exactly in the same order. The first 3 books are very light reads & are sufficient enough to get started with client side programming. However, learning JQuery will make your Javascript development much easier. It is similar to learning to use regular expressions (but JQuery offers more than regex).

  1. Learning Web Design: A Beginner's Guide to (X)HTML, StyleSheets, and Web Graphics

  2. Bulletproof Web Design: Improving flexibility and protecting against worst-case scenarios with XHTML and CSS (2nd Edition)

  3. DOM Scripting: Web Design with JavaScript and the Document Object Model

  4. jQuery in Action

Javascript is an incredible language and libraries like jQuery make it almost too easy to use.

What should the original designers of Javascript have included in the language, or what should we be pressuring them into adding to future versions?

Things I'd like to see:-

  • Some kind of compiled version of the language, so we programmers can catch more of our errors earlier, as well as providing a faster solution for browsers to consume.
  • optional strict types (eg, being able to declare a var as a float and keep it that way).

I am no expert on Javascript, so maybe these already exist, but what else should be there? Are there any killer features of other programming languages that you would love to see?

Read Javascript: The Good Parts from the author of JSLint, Douglas Crockford. It's really impressive, and covers the bad parts too.

The 'K&R', 'Red Book', 'Camel' of JavaScript and CSS? When you see a site like or, what reading material do the developers likely have on their shelves?

For JavaScript it's probably JavaScript: The Good Parts and/or JavaScript: The Definitive Guide.

JavaScript vs. Just the good parts

I don't know if there's an equivalent book for CSS yet.

Which is better, learn the basics of JavaScript, and then jQuery

Or master JavaScript and then learn jQuery

Now I know the basics well But I did not write many exercises of javascript


sorry about My bad English

It depends on what you want to do with javascript.

If you want to go deeper into the javascript, want to experiment with it, then become a master in javascript. In that case I will suggest you to read this excellent book by Douglas Crockford. Becoming a master of something never hurts. But if you want to become a developer and want to only build websites with javascript, then learn the core basics and move on to learning jquery.

Again, whatever you do, you should have a clear understanding about the basics of javascript. You should, at least, read this excellent article and understand how objects in javascripts work, what are prototypes, what datatypes are there. There are also many other resources on javascript on MDN and Opera Developers Network. Google also has some excellent resources on javascript.

Possible Duplicate:
Javascript === vs == : Does it matter which “equal” operator I use?

when i checked my code with JSLINT, it was full of works perfectly even in Ie6 but for some reason because i'm not an elegant coder i got more than 100 errors...

so i'd like to learn how to code better, error free... but when i used some suggestions JSLINT gave me like was to replace == with ===, well i did, and nothing was working...

so my question is: do we have to follow literally all the JSLINT suggestions?

JSLint tests a professional subset of Javascript, created by Douglas Crockford. Essentially, he seeks to carve only the "good parts" out of the JavaScript language, to make life for programmers easier and code more legible and predictable. So, the short answer is NO. You do not have to follow the instructions. Perfectly valid JavaScript code will, and does, fail JSLint all the time.

But the long answer is that your life will be significantly easier in the long run if you do.

Take === vs. ==, for example. The difference is testing for EQUALITY versus testing for IDENTITY. Or, as Crockford says in his book, JavaScript: The Good Parts:

JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. The rules by which they do that are complicated and unmemorable.

So, if you're using === instead of ==, your code will almost always perform as you expect it to, a small price to pay for typing an extra character. But if you use == and the operands are not of the same type -- a string and an integer, for instance, JavaScript will first translate those values to the same type, and then compare them. And they might not do what you want or what you expected. And since, in JavaScript, you're often dealing with elements brought in from the DOM, which come in as strings, you run into string conversion issues all the time.

As Crockford writes, here are some of the issues you could run into:

'' == '0'   => false
0 == ''     => true
0 == '0'    => true

false == 'false'    => false
false == '0'       => true

Screwy, eh? JavaScript: The Good Parts is a great book, super thin, and if you've been working with JavaScript for a while, it will change the way you code for the better. So will JSLint, if you bow your head like a good marine.

So. Long answer? No. You don't have to do everything JSLint tells you. But you should.

After working for on JAVA for a long time now i feel like also learn some other language just for a change. This time i want to spend some time learning and reading one of the dynamic languages. Which is the most appropriate one that covers most of the features offered by dynamic languages and the syntax which probably is fun and also one that is closer to the syntax used by most of the dynamic languages.

BR, Keshav

Javascript is by far the most useful of dynamic languages for real-world practical work - not only is it irreplaceable for "client-side" work on the user's browser, but Node.js is rapidly making it very interesting for server-side work, too. Sure, it has many issues, but a book such as Crockford's Javascript: the good parts will help you avoid many of them.

JS's syntax of course is quite different from that of dynamic languages such as Python or Ruby, which try to avoid braces and semicolons (which you'd better not avoid in JS: it tries to guess on your behalf but too often it guesses wrong!-). There is really no "syntax used by most of the dynamic languages" given these huge syntax differences (which grow if you throw into the mix Scheme, Erlang, Perl, PHP, Tcl, ...), so that part of your specs is moot.

Second most useful today is probably Python -- as Allison Randall (program chair of OSCON and a well-known Perl guru) put it, Python has surprisingly become something of a "default language" in many fields. For example, the SEC is considering a regulation to mandate publication of algorithms used in stock trading, and their initially proposed language for such a publication is "of course" Python. As this post explains,

Why Python? The SEC actually asks for comments on whether they should mandate Perl, Java or something else instead. I use Perl quite extensively, but the idea that Perl is a suitable language for implementing a transparency requirement is laughable. Perl is a model of powerful but unreadable and cryptic code. As for Java and C-Sharp, there is little point in having open source code if the interpreter is not also open source. I do not use Python myself, but it appears to be a good choice for the task at hand.

This is what Allison meant by "default language", I think: not necessarily the one you'll choose to implement a given task (e.g. the above post's author would prefer using Perl), but a language everybody's supposed to be able to read in order to understand an algorithm that is published or otherwise presented -- as Bruce Eckel (deservedly-best-selling author of books on C++ and Java) puts it here,

Python is executable pseudocode.

You can look at the "executable" part as a bonus (it does guarantee lack of ambiguity, which non-executable pseudocode might lack;-) even though large systems such as reddit and youtube have been implemented in it.

At the other extreme, if you're not necessarily looking for immediately useful knowledge, but for mind-broadening, Scheme or Erlang might suit you best (but the syntax in each case is quite different from most other languages, be warned;-).

However, in that case, I'd suggest Mozart, to go with the masterpiece that is Van Roy's and Haridi's Concepts, Techniques, and Models of Computer Programming (that book is plenty motivation to learn Mozart, just like SICP is to learn Scheme -- indeed, I've described CTMCP as "SICP for the 21st century"!-).

HI I am learning javascript since last few days, I read it as scripting language. I like to know how it differs from other scriptings. Where does it run ?I mean where exactly my code gets compiled or error is caught? I like to know even any good online tutorial for learning javascript.

I am an experienced programmer, and I have a few little ideas that I think would work really well as PHP based web applications. I have no problem with learning PHP, mySQL, etc, but I do have a problem with the design of a webpage in itself.

I am used to interface design ala Interface Builder and Swing, where there are some clearly defined classes with clearly defined behaviors etc. To me, web design is the wild west where I have to write my entire user interface, complete with little effects and stuff, on my own.

I'm not afraid of this by any means, I just need some advice on where to start. I've like to learn some proper HTML for starters, since everything I know how to do is static and ugly, and I'd like to learn Javascript to be able to make my pages more elegant as time goes by.

In short, I'd like it if someone gave me a few books or suggestions on how to make the programming that I know and love more visible and accessible to internet users.

CSS Mastery is my go-to book for any css/html problems I may have. It works in detail through common elements you may have to create, such as: forms, tables, general layouts etc and suggests solutions based upon standards compliant CSS/HTML.

For JavaScript check out JavaScript with DOM Scripting and AJAX.

Note: As soon as you're comfortable with JavaScript it's worth looking at jQuery or one of the other many JavaScript libraries that take away the headache of cross-browser compatibility.

I am an intermediate javaScript programmer, and i am interested in expanding my knowledge in object oriented programming (especially object oriented JavaScript).

I would prefer a book over browsing scattered web resources, does anyone have an idea of which book will be best to get a head start with?


Definitely worth reading: JavaScript: The Good Parts by Douglas Crockford.

The chapter 5, "Inheritance" covers different types of Object Orientation:

  • Pseudoclassical, simulating Class hierarchies by extending prototype objects with new methods
  • Prototypal, without classes, using prototype objects to create new instances with common functionalities, then attaching new functions to these new objects directly
  • Functional, using constructor functions to create a private scope and return a new object grouping a set of methods with privileged access to the private variables

Refactoring: Improving the Design of Existing Code by Martin Fowler while the examples are given in Java, the principles behind it are applicable to most OO languages including JavaScript.

I am trying to create a copy of object a, without having to manually enter its property's into object b. In this code, b simply refers to a. I want to create a new version of a, so that when I add a property to b, it is not visible through a.

var a = new Object(); // create an empty object
var b = a;             // now b refers to the same object
b.test = 1;            // add a new property to b
alert(a.test);         // => 1: the new property is also visible through a
a === b;               // => true: a and b refer to the same object

In your example, "a" is just a function object and you are just creating additional pointers.

Just create a new instance of them

var a1 = new a();
var b1 = new a();
a1.test = 1;
b1.test = 2;

a1 != b1

The advantage to using a function as a Class is the utilize object.prototype, inheritance and instance checking. If you want just a data store then just change it to a generic object

var a = {};
var b = {};
a.test = 1;
b.test = 2;

"JavaScript the Good Parts" is an absolute must

I am trying to remove a class and add a class to divs using jQuery but it doesn't seem to be working.

My html is like this:

<div id="foo">
  <div class="row">
    <div class="col-sm-4">
    <div class="col-sm-4">

I would like to remove the class col-sm-4 and instead add class col-sm-6

This is what I've done:


I've ensured that I am getting elements back by find

alert($("#foo").find(".col-sm-4").length); //2

Even though I'm not getting any errors, there is no change in my elements.

1) ".col-sm-6" is an example of a JQuery selector - Which, from the JQuery site is: "Borrowing from CSS 1–3, and then adding its own, jQuery offers a powerful set of tools for matching a set of elements in a document." The methods addClass and removeClass are functions that except a class name to add or subtract to the element's class attribute. You wrote it like a JQuery selector. You are using the concept of selectors correctly when you reference your object with the JQuery selector $("#foo div.col-sm-4").

2) You say: "Even though I'm not getting any errors, there is no change in my elements." - This is a great observation. You should know that much of JavaScript fails silently. Between 1 and 2 of this answer, I highly recommend the book JavaScript: The Good Parts.

I got a minor brain-teaser thats keep bothering me. I'm unable to control the numbers of decimals written by my scripts.


<script type="text/JavaScript">


$tekn_2_1 = "28"
$tekn_2_2 = "7600"

I want this to return the value '271' instead of '271.42857142857144'. I apologize, I'm aware that this should be a small case, but I can get anything to work.

Edit: Originally I had voted for toFixed but was not aware that this function also rounds. It looks like a simple floor is all that you need.

Math.floor($tekn_2_2/$tekn_2_1) == 271

Edit: +1 for Javascript: The Good Parts it goes over basic operations such as this. In a short but very informative manner.

I have a variable called "result",

var result;

that result value is equal to following value, please presume that is just a string :)

---------result value -----------

for (;;);{
             "title":"welcome to site",

---------result value------------

From that value, I would like to extract tableid which is "id.272772962740259" with classic Javascript.

How can I extract the code, please let me know how can i do with simple javascript, please don't use Jquery, all I just need is simple javascript.

You need to remove the empty for loop, then parse the string. DO NOT use eval; most modern browsers provide built-in JSON-parsing facilities, but you can use json2.js if yours does not. Assuming that you assign the results of parsing the JSON to result, you should be able to get that value using result.payload.config.tableid.

You should probably read a good JS reference. JavaScript: The Good Parts or Eloquent JavaScript would be a good choice.

I have two buttons on the form I'm getting, this first piece of coce allow me to know which was the button clicked by getting the id of it.

var button;
var form = $('.register_ajax');

$('#vote_up, #vote_down').on("click",function(e) {
    button = $(this).attr("id");

and this other send the form data through AJAX using the info already obtained from the button using the script above.

form.bind('submit',function () {
        url: form.attr('action'),
        type: form.attr('method'),
        cache: false,
        dataType: 'json',
        data: form.serialize() + '&' + encodeURI(button.attr('name')) + '=' + encodeURI(button.attr('value')) ,
        beforeSend: function() {
        success: function(data) {
            if(data.message == 0){
            if(data.message == 1)
            if(data.message == "plus")
                $("#vote_up").attr('class','options options-hover');
            if(data.message == "sub")
                $("#vote_down").attr('class','options options-hover');
        error: function(xhr, textStatus, thrownError) {
return false;

The problem is that the data is not being passed to the ajax function, the button info is being saved on the button var, but it's not being obtained at time on the ajax call to work with it (or at least that is what I think). I'd like to know what can I do to make this work, any help appreciated.

1st edit: If I get the button data directly like button = $('#vote_up'); it doesn't work either, it only works if I get the button directly like this but without using the function.

2nd edit: I found the solution, I posted below.

You are being victim of a clousure. Just as adam_bear said you need to declare the variable outside of the function where you are setting it, but you are going to keep hitting these kind of walls constantly unless you dedicate some hours to learn the Good Parts :D, javascript is full of these type of things, here is a good book for you and you can also learn more from the author at

I'm confused where should I use prototype to declare a method ? What I read is, if I create a method that is declared by prototype, all instances are using same reference so is it static or something different ? Because I can reach instance properties in a prototype method ? But in c#, you cannot reach class variables(not static) in static methods?

An Example:

function Calculator()
     if(this === window){
          return new Calculator();

     this.Bar = "Instance Variable";

Calculator.prototype.SaySomething = function(thing){
     return thing + " " + Bar;

Calculator().SaySomething("Test"); // Test Instance Variable

I would suggest you read JS The Good Parts by Douglas Crockford. It will give you a better understanding of JS's prototypal object model.

I'm reading Crockford's book on Javascript and trying its inheritance method "Beget", but I'm puzzled by the result.

Could you explain why the following code returns "Values: blue_small / blue_big"? I would expect it to return "Values: blue_small / red_big".

if (typeof Object.beget !== 'function') {
   Object.beget = function (o) {
      var F = function () {};
      F.prototype = o;
      return new F();

function calculate(){  
    var object1 = {
        color: "red",
        size: "small"

    var object2 = Object.beget(object1);

    object2.size = "big";

    object1.color = "blue";

    return "Values: "+object1.color +"_" + object1.size +" \/ " + object2.color+"_" + object2.size || "unknown";

In Javascript, when the value of a property is not set on an instance, getting the value refers to the prototype chain.

In this example, the object2 is created and object1 is its prototype. But the value of the color property is never set on object2 in an explicit way.

This means that reading the value refers to the prototype which is object1 and since the value there is set to blue, you have the result.

Your confusion probably stems from the fact that you would expect creating new object to create a copy that includes all properties. In fact however, the newly created object has no properties set in an explicit way. Whenever you get a value of a property, prototype chain is referred.

I'm trying to learn how to make my application has the same "face" in all files, the same pattern, but I do not know if this is the right thing to do.

I want know if the more correct in software development, is to limit the application to only one type of pattern.

For example, that's how my application looks like (just a piece)


'use strict'
var Server = require('./server');
var Api = {
 init: function() {


'use strict'
var Server = {
 init: function(command) {
  this.command = command;

  if (command === 'start') {

I'm using the "initializer object pattern" in all my application. So i'm avoiding decorator pattern, facade, everything.

Should i avoid or i can use more than one? If the right answer is use several, depending on the needs, i have other question. This doesn't make the maintenance more difficult? Is not make the code like a spaghetti?



I'm going to try explain again, this time with a bounty.

i already try to ask but seems that no one really can give me a concise answer.

I would like to know what are the secrets from making a good app, a good web app, talking about code appearance. I want know if I should maintain the same standard code throughout my hole application, if this is GOOD, or really doesn't matter.

For example, i have two EXAMPLES files


var server = require('./server');

var app = {
 init: function() {

module.exports = app;


var server = {
 init: function(env) {
  if (env === 'DEVELOPMENT') {
    // CODE
  } else {
    // CODE

module.exports = server;

In this case, i'm using one object with method init, which is the pattern that i'm using in my hole app..

Or it doesn't matter, i should write anything:

first object:

var server = require('./server');

var app = {
 init: function() {

module.exports = app;

than server as a function:

var server =function(env) {
  if (env === 'DEVELOPMENT') {
    // CODE
  } else {
    // CODE

module.exports = server;

I can give 100 of my points. it's incredible how i can't find a good answer for this particular issue.


Should I using other patterns?

No, you should not insist on a single pattern.

No design pattern books will ever advise you to use a single pattern. Just like you cannot chop all ingredients in one single way (are you going to dice the spaghetti?), you cannot organise all logic in one single pattern.

Sure, you can make all your Objects use the initialiser pattern, and don't use constructors at all. This is ok. Been there, done that. I like it.

But these objects can be used with Builder or Abstract Factory (if it make things simpler). As long as the builders/factories themselves have initialiser, and that they properly initialise the created objects, then your use of the initialiser pattern will be consistent. Outside of creational patterns, it is usually good to organise objects with structural and behavioural patterns. They do not conflict with initialiser at all.

For example, look at DOM. All nodes are created by the Document object - elements, text nodes, comments, even events. This is the Factory pattern.

Yet the Document object is also a Facade! From it you access the whole system's status, objects, data, you can even write to it! Every DOM operation starts from the Document, it is the Facade of the DOM system.

DOM nodes also implements multiple patterns. They are organised in Composite, let you listen to events with Observer and Command, and handle events in a Chain of Responsibility. They are certainly parsed by an Interpreter, DocumentFragment is a Proxy, svg elements are implemented as Decorators, and createNodeIterator obviously gives you an Iterator.

The point is, good object-oriented design will yield multiple design patterns as a result, intentional or not.

What are the secrets for good code appearance

I think the best looking code is the one that is easiest to understand to you, and the way you read code changes as you gain more experience.

For example my style is too condensed for most programmers, but to me it strikes a good balance. So do develop your own style - you are not me, and you are not yesterday's you either.

Remember this as we go through the styles.

At the lowest level we have coding style - most importantly indent and bracket.

This one is simple, pick the one you like and stick with it. There are language specific styles, and they are often good starting points. Configure your IDE's formatter so that you can format all your code with hotkey.

Above the code syntax we have comment style and naming convention.

Setting rules on comment is fine, sometimes it is necessary for documenting tools. Avoid too much comment in practice. You may also want to decide your namespace and your stand on naming function expressions.

Above these structures, we have logic conventions.

The same code logic can often be done in many ways, some more 'beautiful' than the others in your eyes. Look at this example.

I picked the second style on first sight: no duplicate, logic is sectioned cleanly, format is not my style but reasonable. But many programmers would prefer the first style: logic is plain as day, a few duplications is worth it. While abstract, this level is quite deep - present your logic the wrong way actually increase the chance an experienced programmer read it wrong.

Finally, we arrives at the level of design pattern, about as far as code beauty goes.

The key to keep your code structure beautiful, is using the right patterns at right level to consistently accomplish loose coupling and code reuse, while avoiding pitfalls and over-design.

There are quite some books about beautiful code, and then there are even more books about designing and implementing beautiful software. (Decide for yourself which are beyond your level.) Knowledge is as important as experience, and you can gain them only by spending your time to study, to write, and to revise/refactor your apps.

Feel free to change your mind as you explore and experiment with your code. Changing your mind is a good sign of learning.

But first, familiarise yourself with design patterns. Just don't forget, they are the generic result of applying object-oriented principals to common tasks. It is still up to you to do the design.

Design Patterns Are Not Silver Bullets.

In Java/C/C++ (and, with the exception of Python, every other language I can think of) whitespace is ignored.

I've just spent several hours trying to work out why I was getting an error on a return statement. The answer was whitespace.

So here are the two code snippets that I thought were functionally equivalent.

return { a:b, c:d};


But I now understand that the first one works but the second one throws an error on the c:d line.

Can someone explain why these are not syntactically equivalent?

The problem here is that JavaScript has a "feature" called automatic semi-colon insertion.

So, your second snippet was actually being executed like this (note the semi-colon after the return):


Basically, you were returning undefined, rather than the object literal.

JavaScript has so called "bad parts" and you ran in to one of them. I would highly recommend reading this book regarding the subject.

See this article for more information about automatic semi-colon insertion.

If you still wanted to format your code similarly to what you originally had, this might be the closest that wouldn't bite you:

return {

It seems that many of the JavaScript questions are answered by the simple use of pushing a library, without taking into account the person asking the question. I think libraries are great myself, but sometimes I think that we're too quick to throw a library down someone's throat.

Imagine a person asks a question and it's apparent that they barely know JavaScript. They're just using code they found and piecing it together with other code, and really have no firm foundation to work on. To add a library on top of that flimsy foundation seems like a disaster waiting to happen.

With that in mind, what JavaScript / programming / web browser concepts do you think are necessary to understand before a library/framework is introduced to a person? Should a framework / library be part of the learning process?

I don't think someone has to grasp absolutely everything to use a library, I just think some people would be better served with a "Library X might help solve your problems, but before you do that, you might want to read up on the following concepts", rather than just a "use library x" answer.

They should read this And check out some of the links here

I've taken courses, studied, and even developed a little by myself, but so far, i've only worked with Microsoft technologies, and until now I have no problems with it. I recently got a job in a Microsoft gold partner company for development in C#, and

I'd like tips on how to diversify, learning technologies other than those from Microsoft. Not necessarely for finding another job, I think my job just fits me for my current interests. I think that by learning by myself other languages, frameworks, databases.. I may become a better programmer as a whole and (maybe) at the end of it all having more options of job opportunities, choosing what i'm going to be working with.

What should I start with? how should I do it?

Ideally, one should know at least one example from each of the major "paradigms":

  • Assembly (nowadays a dying art, and not that useful)
  • plain C
  • one of the OO-variants of C (C++, objective C)
  • Java or C# (they are very similar, probably no need to learn both)
  • a scripting language like Ruby or Perl
  • Javascript (preferrably via Crockford's book)
  • a non-pure functional language, e.g Scheme (PLT Scheme is a nice learning environment)
  • a pure-functionalal language like Haskell or OCAML
  • Erlang (somewhat of a class of its own)
  • a mathematical/statistical language like R, or J (an APL-successor)

I want to create an array by extracting the dates of some other array and then comma separate the values into a string.

      for (i in array) {
      var combined=new array();
      combined = array[i].date;

I am new to javascript and hard to follow in arrays.Thanks !! Can anyone also recommend me a good book for javascript?

Try this

var originalArray = [{date:"2012-01-01", username: "first"}, {date:"2012-01-02", username: "second"}];

// First step: Get a dateArray with only the dates
var dateArray = [];
for (var i in originalArray) {

// Or if you prefer to cut a few lines
// dateArray = { return; } );

// Second step: Get it as a comma separated string
var datesString = dateArray.join(",");

console.log(dateArray); // ["2012-01-01","2012-01-02"]
console.log(datesString); // 2012-01-01,2012-01-02

One of the more popular books is "Javascript The Good Parts" by Douglas Crockford

I want to learn JavaScript nicely and become very good at it. I want to form a systematic learning plan before I start reading the books. Don't want to end up wasting my time reading the wrong books.

I want to learn from books that will teach me enough to be able to learn all the things that are commonly used in today's websites.

For example, if you look at this website

His page source doesn't show the full content of the web page. How does he do all those animated transition effects?

How do I learn all that stuff? Please help me. I want to learn all that stuff. Which book should I start reading?

Another example is the Stack Exchange websites. For instance, the Writers website itself. When you hover over the Questions link on the top or any of such links, it displays a yellow background highlight. How do they do that?

Where do I learn all these tricks? I see two options:

a) Look up the web on an ad hoc basis when you need to learn some trick.

But I don't like this technique.


b) Systematically learn and read some books. I will read all the books if I have to. Please tell me what technologies other than JavaScript are at use to do these things.

And if it is just JavaScript, what books will teach me the level of JavaScript that Google employees and FogCreek and StackExchange employees use.

And if it is just JavaScript, what books will teach me the level of JavaScript that Google employees and FogCreek and StackExchange employees use.

This is the easiest to answer: none. Yes, get started with Danny Goodman's tome or JavaScript: The Good Parts if you have some programming experience and want a quick intro, but both will only get you started. I mean, I'm sure they had some textbooks they read in college, but it's kind of like asking what books made pro athletes so good, or what book you read to get good at guitar.

It's maybe 10% textual material and 90% constant practice -- finding new problems to solve and figuring out how to solve them.


I don't intend to imply that avoiding books is admirable, merely that experience is the best teacher, and that a theoretical understanding is only a means to an end: practical understanding. Books are absolutely necessary here; I'm mostly disputing the connection between books and the kind of expertise that lands you a high-flying job. For a perhaps more relevant example, imagine language learners. You can study the textbooks all you'd like, but absent experience you'll stutter like a first-year student. (Even if, for example, you can recite correctly the grammatical differences of some construction better than a native speaker.)

So no, don't just copypasta and come to SO when things break. But do start early in your reading, and the mistakes you make (rather than some script you copied) are often the best teachers.

I was going over Javascript the good parts and I came across this example, where the author was trying to explain how to be able to call a superclass:

Object.method('superior', function (name) {
    var that = this,
        method = that[name];
    return function (  ) {
        return method.apply(that, arguments);

an example of using this code:

super_get_name = that.superior('get_name');

however chrome wouldn't recognize method on Object. I tried doing the same thing using defineProperty but that didn't work either.. any help?

update: does this method cause any known conflicts with jQuery? As soon as i put the following at the first js file in my page:

I get this error in line 2062 in jquery-1.11.0.js:

Uncaught TypeError: Object function (name) {
    var that = this,
        method = that[name];
    return function (  ) {
        return method.apply(that, arguments);
} has no method 'exec' 

this is the effected code:

    // Filters
    for ( type in Expr.filter ) {
        if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
            (match = preFilters[ type ]( match ))) ) {
            matched = match.shift();
                value: matched,
                type: type,
                matches: match
            soFar = soFar.slice( matched.length );

any idea what's going on?

Javascript do not have structures.

So can i create a GLOBAL object like struct abc in javascript .

Struct abc contains some variables & array of another structure struct xyz.

struct xyz {

  var age;
  var name;


struct abc {

  var start;
  var end;
  var length;

  struct xyz  xyz_array[100];


If structures is not possible in javascript how can i save data in this format ?

============================= Edit some solution i found =================
Javascript: How to create an array of object literals in a loop


var details = {
    Start: 0,
    End: 0,
    length: 0

var arr = [];
var len = 100;

for (var i = 0; i < len; i++) {
        direction: "out",
        message  : ""


Array inside a Javascript Object?

var details = {
    Start: 0,
    End: 0,
    length: 0
    info_text : []

var len = 100;

for (var i = 0; i < len; i++) {
        direction: "out",
        message  : ""


Cited from JavaScript: The Good Parts

The simple types of JavaScript are numbers, strings, booleans (trueandfalse),null, and undefined. All other values are objects. Numbers, strings, and booleans are object-like in that they have methods, but they are immutable. Objects in JavaScript are mutable keyed collections. In JavaScript, arrays are objects, functions are objects, regular expressions are objects, and, of course, objects are objects.

So you can use object, example :

function xyz(age, name){
    this.age = age; = name;

var abc = {
    start : null,
    end : null,
    length: null

    xyz_array: []

abc.xyz_array.push( new xyz(33, 'johnDoe') );
abc.xyz_array.push( new xyz(32, 'jeanDoe') );


Just came across JSLint so decided to pass my JS through it but got lots of errors but not sure if they're bad. I have tried a few things I found online to get rid of them but can't seem to make the budge.

JS code

$( document ).ready(function() {
!function (d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0],
        p = /^http:/.test(d.location) ? 'http' : 'https';
    if (!d.getElementById(id)) {
        js = d.createElement(s); = id;
        js.src = p + "://";
        fjs.parentNode.insertBefore(js, fjs);
}(document, "script", "twitter-wjs");
$('div.icon').click(function () {
function search() {
    var query_value = $('input#search').val();
    if (query_value !== '') {
            type: "POST",
            url: "../_Scripts/search.php",
            data: {
                query: query_value
            cache: false,
            success: function (html) {
    return false;
$("input#search").on("keyup", function (e) {
    clearTimeout($.data(this, 'timer'));
    var search_string = $(this).val();
    if (search_string == '') {
    } else {
        $(this).data('timer', setTimeout(search, 100));
$('#pmForm').on('submit', function (e) {
    $('input[type=submit]', this).attr('disabled', 'disabled');
    var pmSubject = $("#pmSubject", this).val();
    var pmTextArea = $("#pmTextArea", this).val();
    var url = "../_Scripts/private_msg_parse.php";
    if (!pmSubject) {
        $('input[type=submit]', this).removeAttr('disabled');
        $("#jqueryReply").html('<img src="../_Images/round_error.png" alt="Error" width="31" height="30" /> &nbsp; Please type a subject.').show().fadeOut(6000);
        return false;
    } else if (!pmTextArea) {
        $('input[type=submit]', this).removeAttr('disabled');
        $("#jqueryReply").html('<img src="../_Images/round_error.png" alt="Error" width="31" height="30" /> &nbsp; Please type in your message.').show().fadeOut(6000);
        return false;
    } else {
        $.post(url, $('#pmForm').serialize(), function (data) {
            $('input[type=submit]', this).removeAttr('disabled');

$('#newblog').on('submit', function (e) {
    $('input[type=submit]', this).attr('disabled', 'disabled');
    var blogTitle = $("#blogtitle").val();
    var blogText = CKEDITOR.instances['blogbody'].getData();
    var url = "../_Scripts/post-blog.php";
    if (!blogTitle) {
        $('input[type=submit]', this).removeAttr('disabled');
        $("#jqueryReply").html('<img src="../_Images/round_error.png" alt="Error" width="31" height="30" /> &nbsp; Please type a Title.').show().fadeOut(6000);
        return false;
    } else if (!blogText) {
        $('input[type=submit]', this).removeAttr('disabled');
        $("#jqueryReply").html('<img src="../_Images/round_error.png" alt="Error" width="31" height="30" /> &nbsp; Please type in your Blog.').show().fadeOut(6000);
        return false;
    } else {
        for (instance in CKEDITOR.instances) {
        $.post(url, $('#newblog').serialize(), function (data) {

function _(x) {
    return document.getElementById(x);

function report(id, uid) {
    var url = "../_Scripts/report.php";
    $.post(url, {
        blogid: id,
        userid: uid
    }, function (data) {

function toggleElement(x) {
    var x = _(x);
    if ( == 'block') { = 'none';
    } else { = 'block';

var friendRequestURL = "../_Scripts/request_as_friend.php";

function addAsFriend(a, b) {
    $.post(friendRequestURL, {
        request: "requestFriendship",
        mem1: a,
        mem2: b
    }, function (data) {

function acceptFriendRequest(x) {
    $.post(friendRequestURL, {
        request: "acceptFriend",
        reqID: x
    }, function (data) {

function denyFriendRequest(x) {
    $.post(friendRequestURL, {
        request: "denyFriend",
        reqID: x
    }, function (data) {

function removeAsFriend(a, b) {
    $.post(friendRequestURL, {
        request: "removeFriendship",
        mem1: a,
        mem2: b
    }, function (data) {
var date = new Date().getFullYear();
$('#year_' + date).children('ul').addClass('active').children('li').slideDown();
$('#' + date).children('img').attr("src", "../_Images/arrow-down.gif");
$('li:not(.recent)').click(function (e) {
    if ($(this).find('>ul').hasClass('active')) {
        $(this).children('img').attr("src", "../_Images/arrow.gif");
    } else {
        $(this).children('img').attr("src", "../_Images/arrow-down.gif");


'$' was used before it was defined.
$( document ).ready(function() {
line 1 character 4Unexpected space between '(' and 'document'.
$( document ).ready(function() {
line 1 character 13Unexpected space between 'document' and ')'.
$( document ).ready(function() {
line 1 character 29Expected exactly one space between 'function' and '('.
$( document ).ready(function() {
line 2 character 1Missing 'use strict' statement.
!function (d, s, id) {
line 3 character 5Expected 'var' at column 9, not column 5.
    var js, fjs = d.getElementsByTagName(s)[0],
line 4 character 9Expected 'p' at column 13, not column 9.
        p = /^http:/.test(d.location) ? 'http' : 'https';
line 5 character 5Expected 'if' at column 9, not column 5.
    if (!d.getElementById(id)) {
line 6 character 9Expected 'js' at column 13, not column 9.
        js = d.createElement(s);
line 7 character 9Expected 'js' at column 13, not column 9. = id;
line 8 character 9Expected 'js' at column 13, not column 9.
        js.src = p + "://";
line 9 character 9Expected 'fjs' at column 13, not column 9.
        fjs.parentNode.insertBefore(js, fjs);
line 10 character 5Expected '}' at column 9, not column 5.
line 11 character 1Expected '}' at column 5, not column 1.
}(document, "script", "twitter-wjs");
line 11 character 3Wrap an immediate function invocation in parentheses to assist the reader in understanding that the expression is the result of a function, and not the function itself.
}(document, "script", "twitter-wjs");
line 12 character 1Expected '$' at column 5, not column 1.
$('div.icon').click(function () {
line 13 character 5Expected '$' at column 9, not column 5.
line 14 character 1Expected '}' at column 5, not column 1.
line 15 character 1Expected 'function' at column 5, not column 1.
function search() {
line 16 character 5Expected 'var' at column 9, not column 5.
    var query_value = $('input#search').val();
line 16 character 23'$' was used before it was defined.
    var query_value = $('input#search').val();
line 17 character 5Expected '$' at column 9, not column 5.
line 18 character 5Expected 'if' at column 9, not column 5.
    if (query_value !== '') {
line 19 character 9Expected '$' at column 13, not column 9.
line 20 character 13Expected 'type' at column 17, not column 13.
            type: "POST",
line 21 character 13Expected 'url' at column 17, not column 13.
            url: "../_Scripts/search.php",
line 22 character 13Expected 'data' at column 17, not column 13.
            data: {
line 23 character 17Expected 'query' at column 21, not column 17.
                query: query_value
line 24 character 13Expected '}' at column 17, not column 13.
line 25 character 13Expected 'cache' at column 17, not column 13.
            cache: false,
line 26 character 13Expected 'success' at column 17, not column 13.
            success: function (html) {
line 27 character 17Expected '$' at column 21, not column 17.
line 28 character 13Expected '}' at column 17, not column 13.
line 29 character 9Expected '}' at column 13, not column 9.
line 30 character 5Expected '}' at column 9, not column 5.
line 31 character 5Expected 'return' at column 9, not column 5.
    return false;
line 32 character 1Expected '}' at column 5, not column 1.
line 33 character 1Expected '$' at column 5, not column 1.
$("input#search").on("keyup", function (e) {
line 34 character 5Expected 'clearTimeout' at column 9, not column 5.
    clearTimeout($.data(this, 'timer'));
line 34 character 18'$' was used before it was defined.
    clearTimeout($.data(this, 'timer'));
line 35 character 5Expected 'var' at column 9, not column 5.
    var search_string = $(this).val();
line 35 character 25'$' was used before it was defined.
    var search_string = $(this).val();
line 36 character 5Expected 'if' at column 9, not column 5.
    if (search_string == '') {
line 36 character 23Expected '===' and instead saw '=='.
    if (search_string == '') {
line 37 character 9Expected '$' at column 13, not column 9.
line 38 character 9Expected '$' at column 13, not column 9.
line 39 character 5Expected '}' at column 9, not column 5.
    } else {
line 40 character 9Expected '$' at column 13, not column 9.
line 41 character 9Expected '$' at column 13, not column 9.
line 42 character 9Expected '$' at column 13, not column 9.
        $(this).data('timer', setTimeout(search, 100));
line 42 character 9Too many errors. (23% scanned).

Can anyone shed some light on these errors and tell me if they're going to affect me in the future? At the moment, the code runs fine.


JSLint checks for code syntax, including whitespace, not just code errors.

Errors such as Expected '===' and instead saw '=='. are very serious because of the nature of JavaScript. In JavaScript, == means compare value whereas === means compare value and type. Here are a few examples:

1 == '1'  // Evaluates to true because it doesn't check for type
1 === '1' // Evaluates to false because it does check for type (they are 
          // different types)

It is therefore always best to use === and not ==.

The whitespace errors/warnings such as

Unexpected space between '(' and 'document'.


Expected '}' at column 9, not column 5.

are not as serious and will probably not cause any problems with the actual performance of your code, they will, however, help improve the readability and clarity of your code. I recommend using the JSLint formatting/whitespace rules, but if you have your own valid JavaScript code formatting style, don't worry too much about it.

JSLint is a standard, not the standard, for writing JavaSript code. That said, JSLint is a very good standard. If you don't care about whitespace, JSHint is a good alternative to JSLint. JSHint is a fork of JSLint but is not as strict in places where it doesn't matter as much, namely whitespace.

As suggested in the comments above, I recommend concentrating on learning how to write good, clean, readable JavaScript code. For the most part, if your code is well written and readable, JSLint/JSHint won't find many errors. For more information about making good JavaScript code I recommend checking out JavaScript: The Good Parts by Douglas Crockford, the inventor of JSLint.

My Manager wants to learn HTML and JS, and he has no idea of programming. Can you give me any good references from where he can learn?

Do yourself a huge favor: do not use w3schools. A lot of its content has obviously not been updated in around 10 years, and a large portion of the javascript code on it is absolutely attrocious and should not be considered best practice even in a parallel universe.

For more details on this, see - which also suggests some alternative resources.

That said, I've personally found Mozilla Developer Network to be a very well-written resource, though I'll admit it may not necessarily cater to the greenest of audiences.

For JavaScript as a language, I'd highly recommend picking up Douglas Crockford's book JavaScript: The Good Parts, as it discusses the language while specifically trying to emphasize the good parts of the language while steering you clear of the bad. It's important to remember that while JavaScript looks like Java, its similarities pretty much end there.

EDIT: for JavaScript you may be better off starting with a resource like Eloquent JavaScript as Rebecca pointed out in her answer (for which she gets a +1 from me, and for which I kick myself for forgetting about).

I might also point you towards Rebecca Murphey's jqfundamentals - particularly the first chapter, which also briefly goes through some JavaScript basics, though admittedly it does so quickly and thus shouldn't be your only read. But it's also well-written and should be hopefully easy to understand. (For consumable formats, look here:

Ok I trying to learn javascript for my first language but I'm having trouble with the logic/structure of "programming". I know almost everything in javascrupt I can write statements/loops/arrays/objects/ect... but I can't wrap my head around how to use it or put it into action and I can't find what I looking for on the web.

So I guess my question is how do you structure a program in javascript?

does it go like:

variables go here

functions go here

arrays go here


I just dont get it..

If you must start with javascript as a programming language, then a good reference for having good structure and habits for your javascript code would be Douglas Crockford's Javascript: The Good Parts. There are a lot of gotchas in javascript, and Crockford is meticulous about style and structure in it.

I can't stress enough how important a good resource is for learning a language.

MDN is wonderful for learning about each of the available objects/methods. Additionally, treat JavaScript: The Good Parts as required reading.

Use jslint.

Ask lots of questions.

As for the actual structure of the program:

//wrap your code in a self-executing closure to prevent global namespace pollution
(function () {
  //use strict because it's good to brush your teeth
  "use strict"
  //initialize all vars at top of functions
  var a, b, c, d;

  //declare your functions after your variables
  function foo(bar, baz) {
    var fizz, buzz;

    function subfunction() {
      //some code

    //more code

  //whatever code needs to run should follow function declarations
  a = 1;
  b = 2;
  c = foo(a, b);

  //if you need to make something globally accessible, do it explicitly = foo;

Also: HTML, CSS, and JS work together in an MVC pattern if you use them correctly. Keep your HTML in .html files, your CSS in .css files, and your JavaScript in .js files. Don't use inline events <body onload="whatever();"> breaks the separation of content from style from interaction.

    rowData = []

    function something () {
    return rowData


Now lets take the Array contains a lot of Objects. So we say that this would return an Array of Objects.

I am just confused a lot. Does this return an Object or Array of Object Or just an Array.

[] is an array literal so that function returns an empty Array. In JavaScript, arrays are really objects and they are a little different than traditional arrays.

From Douglas Crockford's JavaScript: The Good Parts

JavaScript provides an object that has some array-like characteristics. It converts array subscripts into strings that are used to make properties.


Unlike most other languages, JavaScript's array length is not an upper bound. If you store an element with a subscript that is greater than or equal to the current length, the length will increase to contain the new element. There is not array bounds error.

someSingleton = (function() {    
    var someFunction = function() {

    var someOtherFunc = function() {

    return {
        method: someFunction


If run you this you'll notice the first method will return the object as expected and the second nested method call, someOtherFunction, will return the DOMWindow object.

Other than passing the instance (this) as a parameter to the second method, how do I make it so that the second method call is referencing the containing object and not DOMWindow.

Understanding this in javascript can be a challenge. I can recommend reading Douglas Crockford's Javascript: The Good Parts for a better understanding. Meanwhile, you can check out this link :)

It's quite common to assign the parent object to a variable that. This way, you can access it's properties and functions through it:

  var that = this;
  that.someFunc = function(){};
  that.someOtherFunc = function(){

So I am learning JavaScript right now and I am making this calculator. Started it like any other JavaScript. Make html file, put in all the html tags and so on, make the special <script></script> tags into which I will write the code. Now my solution involved a lot of variables and if statements and so on..

But then I wondered how others have done it and i Stumbled upon this:

<FORM NAME="Calc">
<INPUT TYPE="text"   NAME="Input" Size="16">
    <INPUT TYPE="button" NAME="one"   VALUE="  1  " OnClick="Calc.Input.value += '1'">
    <INPUT TYPE="button" NAME="two"   VALUE="  2  " OnCLick="Calc.Input.value += '2'">
    <INPUT TYPE="button" NAME="three" VALUE="  3  " OnClick="Calc.Input.value += '3'">
    <INPUT TYPE="button" NAME="plus"  VALUE="  +  " OnClick="Calc.Input.value += ' + '">
    <INPUT TYPE="button" NAME="four"  VALUE="  4  " OnClick="Calc.Input.value += '4'">
    <INPUT TYPE="button" NAME="five"  VALUE="  5  " OnCLick="Calc.Input.value += '5'">
    <INPUT TYPE="button" NAME="six"   VALUE="  6  " OnClick="Calc.Input.value += '6'">
    <INPUT TYPE="button" NAME="minus" VALUE="  -  " OnClick="Calc.Input.value += ' - '">
    <INPUT TYPE="button" NAME="seven" VALUE="  7  " OnClick="Calc.Input.value += '7'">
    <INPUT TYPE="button" NAME="eight" VALUE="  8  " OnCLick="Calc.Input.value += '8'">
    <INPUT TYPE="button" NAME="nine"  VALUE="  9  " OnClick="Calc.Input.value += '9'">
    <INPUT TYPE="button" NAME="times" VALUE="  x  " OnClick="Calc.Input.value += ' * '">
    <INPUT TYPE="button" NAME="clear" VALUE="  c  " OnClick="Calc.Input.value = ''">
    <INPUT TYPE="button" NAME="zero"  VALUE="  0  " OnClick="Calc.Input.value += '0'">
    <INPUT TYPE="button" NAME="DoIt"  VALUE="  =  " OnClick="Calc.Input.value = eval(Calc.Input.value)">
    <INPUT TYPE="button" NAME="div"   VALUE="  /  " OnClick="Calc.Input.value += ' / '">

It's not indented really well but the point is that, it's javascript as I understand yes? And the person has not even used the script tags for it. Just putting the code randomly in a html file and bam it work. How can this be?

As I said, this is horrible code. If you are learning Javascript, this is a great example of how not to do it.

It works because they've put Javascript code in the event handlers and even without specifying most (all) browsers will interpret that as Javascript. They can access the various inputs by exploiting that most browsers will automatically create a variable for any named controls.

And then for bonus points they use eval which is evil.

Seriously, this is really bad code. You'd see a lot of code like this in the early 90's. Just move on and learn Javascript properly. Start here: JavaScript: The Good Parts

The code below uses Javascript to create a base class, eventRaiser, that has the internals needed to allow clients to subscribe to events, and subclasses to raise these events. The idea is that other classes, like ThingWithEvent, will inherit from eventRaiser and expose the subscribe method, and fire off the raise method internally. The jQuery init function demonstrates this.

The way this is written, there's nothing stopping a client from directly raising an event. In other words, adding er.raise("Y"); to the jQuery init function causes the Y event to be raised without difficulty.

Ideally I'd like to make it so that outside code, interacting with eventRaiser through some class that inherits from it, with can only subscribe to events, and not raise them.

In other words I'd like raise to be the equivalent of C# protected—visible only to itself, and classes that inherit from it.

Is there some slick ninja closure I should use to achieve this, or should I recognize that Javascript is not meant to incorporate OO Encapulation, rename raise to _raise to imply to client code that _raise is private and should not be invoked, and move on?

    $(function() {
        var er = new ThingWithEvent();

        er.subscribe("X", function() { alert("Hello"); });
        er.subscribe("X", function() { alert("World"); });
        er.subscribe("Y", function() { alert("Not Called"); });


    function eventRaiser() {
        var events = {};
        this.subscribe = function(key, func) {
            if (!events[key])
                events[key] = { name: key, funcs: [] };

        this.raise = function(key) {
            if (!events[key]) return;
            for (var i = 0; i < events[key].funcs.length; i++)

    function ThingWithEvent() {;
        var self = this;

        this.doSomething = function() {
            alert("doing something");

    function surrogate() { }
    surrogate.prototype = eventRaiser;
    ThingWithEvent.prototype = new surrogate();
    ThingWithEvent.prototype.constructor = ThingWithEvent;

I hate answering my own question, let alone accepting my own answer, but it turns out this is not only possible, but insanely easy. The idea behind this code comes from Douglas Crockford's JavaScript The Good Parts. The trick is to ditch constructors (neoclassical inheritance) altogether and use functional inheritance.

This code not only achieves public, protected, and private access levels, but it's much cleaner, and easier to read IMO than inheriting constructors and swapping prototypes and constructors around. The only catch is that this code will be slightly slower since each object creation necessitates the creation of each of the object's functions, instead of getting all that dumped in for free with a constructor's prototype. So, if you need to create tens of thousands of objects in your web site then you might prefer a constructor. For...everyone else, this code is likely for you.

    function eventRaiser(protectedStuff) {
        protectedStuff = protectedStuff || {}; 
        var that = {};
        var events = {};  //private

        protectedStuff.raise = function(key) {
            if (!events[key]) return;
                for (var i = 0; i < events[key].funcs.length; i++)
                    events[key].funcs[i].apply(null,, 1));

        that.subscribe = function(key, func) {
            if (!events[key])
                events[key] = { name: key, funcs: [] };

        return that;

    function widget() {
        var protectedStuff = {};
        var that = eventRaiser(protectedStuff);

        that.doSomething = function() { 
            alert("doing something"); 

        return that;

    $(function() {
        var w = widget();
        w.subscribe("doStuffEvent", function(){ alert("I've been raised"); });

        w.protectedStuff.raise("doStuffEvent"); //error!!!!!  raise is protected
        w.raise("doStuffEvent"); //and this obviously won't work

Titanium SDK version: 1.6. iPhone SDK version: 4.2

I am trying out the cache snippet found on the Appcelerator forum but I get an error: [ERROR] Script Error = Can't find variable: utils at cache.js (line 9).

I put this one ( in a file called cache.js and implemented the code from this one ( in the calling script, but I get the error.

What is wrong? I copied the code exactly.

All input are welcome!

Your problems is whilst the first pastie defines utils.httpcache. The variable utils is not defined outside of this function closure (because it is not defined anywhere in global namespace). As below shows.

(function() {
  utils.httpcache = {


To make it all work in this instance add the following code to the top of your cache.js file.

var utils = {};

This declares the utils variable in global namespace. Then when the function closure is executed below it will add utils.httpcache to the utils object.

The problem is actually not specific to Appcelerator and is just a simple JavaScript bug. Checkout Douglas Crockfords book, JavaScript the Good Parts. Reading it will literally make you a more awesome JavaScript developer.

Using jQuery, I am binding some image tags with a click event like this:

$('.imageClass > a > img').bind('click', onImageClick);

this.onImageClick = function() {
    $.post("/blah/123", { test : 'a' }, function(data) { myCallback(this, data); }, "json");

this.myCallback(event, data) {

My DOM looks like this:

<div class="imageClass">
    <a href="#"><img src="/images/1.jpg" alt="1"></a> <strong>hello</strong>
    <a href="#"><img src="/images/2.jpg" alt="2"></a>

I want to alter the text 'hello' in mycallback somehow using data.Message

I can't seem to pin point the strong tag, and i'm not sure if I am passing the correct value into mycallback either!

To change the text in strong with data from the ajaxcall, try this:

$(".imageClass > a > img").click(on_image_click);

function on_image_click() {
    var image = this, strong = image.parent().next();
    $.getJSON("/blah/123", {test: 'a'}, function (data) {

It seems like you are a little unsure how to use the this-operator, which is understandable. Once understood, it's a powerful concept. I've tried finding a good article on the net. Quirksmode has one, but it is slightly confused as well. I can however heartily recommend Douglas Crockfords Javascript: the good parts.

I'm pretty new to web development and an trying to build a set of rules for good programming practice before I start learning bad habits. Therefore I wanted to ask you all for any wise words on what practices you would recommend to a newbie to adopt early on both in terms of code re-usability and readability for others. Below I've shared a few 'rules' that I've picked up so far for myself (please feel free to correct/update if any of these are 'old' or irrelevant):

Double vs single quotes:

  • Echo statements with double quotes so that variables can be resolved in-line (including html tags and carriage return/tabs - but not functions)
  • Html tag id/name/value values in single quotes


  • Nesting with indents
  • When using echo to output HTML code, use \n for carriage return and \t for a tab (when in double quotes - on linux server)

Classes and Functions:

  • Store in a separate file(s) (eg include('includes/functions.php')) to store all classes/functions to be used on the website
  • Keep below structure so that lines can be cut/pasted in their entirety

    class name {
        function name ($a) {

External scripts:

  • Do not put them directly in the header (it slows the page loading)
  • Do not put them in the footer. Even though the content will be loaded, it delays the load status
  • Combine all slow scripts into one external file and load with the below code (replacing defer.js with your script file):

    <script type="text/javascript">
    function downloadJSAtOnload() {
    var element = document.createElement("script");
    element.src = "defer.js";
    if (window.addEventListener)
    window.addEventListener("load", downloadJSAtOnload, false);
    else if (window.attachEvent)
    window.attachEvent("onload", downloadJSAtOnload);
    else window.onload = downloadJSAtOnload;


  • Use AJAX when REQUESTING data from the server
  • Use POST/GET when SUBMITTING data to the server


  • PDO connections are more versatile than mysqli (procedural or object orientated) as can handle multiple types of databases
  • Use Prepare() and BindParam()/BindValue() to ensure protection against code insertion

PHP miscellaneous:

  • Use require_once() and include_once() to save unnecessary loading (unless using it to reconnect to a database);
  • Define substrings individually and then insert into a compiled variable to echo out, eg:

    foreach($users as $user) {
        $selected=($user['name']=$_POST['username'] ? 'SELECTED' : '');
        echo "<option id='$id' $selected >$value</option>";

Happy coding!

I'm not going to say anything specific about good programming practice with PHP since that subject is very general but I'll share my opinion on your 'good programming practices'.

Double vs single quotes:

  • Echo statements with double quotes so that variables can be resolved in-line (including html tags and carriage return/tabs - but not functions)
  • There's no telling whether resolving variables in echo statements is good programming practice. There's no wrong way of doing it. Do what you find suits your eyes best.
  • Html tag id/name/value values in single quotes
  • I myself like to have them in double-quotes.


  • Nesting with indents
  • Your IDE should take care of your code formatting and indentation in most cases.

External scripts:

  • The only thing that's good practice about JavaScript is to keep your code just above the closing <body> tag. If you wish to be very disciplined over JavaScript I'd recommend JavaScript: The Good Parts - the bible of JavaScript good programming practices.


  • Use AJAX when REQUESTING data from the server
  • I'm not sure what you think AJAX is. You can use AJAX to retrieve and post data to the server. Read up on AJAX and understand it fully before forming opinions on it.
  • Use POST/GET when SUBMITTING data to the server
  • There's a reason it's called GET. It's used for getting data from the server. Don't submit data using GET.


  • PDO connections are more versatile than mysqli (procedural or object orientated) as can handle multiple types of databases
  • Use Prepare() and BindParam()/BindValue() to ensure protection against code insertion
  • If you use a good PHP framework you won't need to worry about your data layer. Especially if that framework makes use of an ORM.

PHP miscellaneous:

  • Use require_once() and include_once() to save unnecessary loading (unless using it to reconnect to a database);
  • The reason require_once() and include_once() exist is because sometimes including a script more than once can cause an error. Like when you have define()d variables.
  • Define substrings individually and then insert into a compiled variable to echo out, eg:
    foreach($users as $user) {
        $selected=($user['name']=$_POST['username'] ? 'SELECTED' : '');
        echo "<option id='$id' $selected >$value</option>";
  • This is also a matter of opinion.

To wrap it up:

Don't do preemptive performance fixes. You seem like a smart person so do what you think is logical. Write readable and documented code. Use a framework. Cannot stress this enough. Try Laravel, Symfony, Zend. Those are the major/most popular ones. Use a good IDE. My personal favorite is PHPStorm. And last but not least, code. Just write code, create applications. Skill will follow naturally and with time you'll be amazed how much your programming has improved. Good luck.

I truly hope this question doesn't get deleted since I really do need help from the programming pros out there...

I've been programming for quite a while (my main platform being .Net), and am about 85% self-taught - Usually from the school of hard-knocks. For example, I had to learn the hard way why it was better to put your configuration parameters in an .ini file (that was easier for my users to change) rather than hard-code them into my main app and now to use the app.config rather than even a config file sometimes. Or what a unit-test was and why it proved to be so important. Or why smaller routines / bits of code are better 90% of the time than one, long worker process...

Basically, because I was thrown into the programming arena without even being shown .Net, I taught myself the things I needed to know, but believe I missed MANY of the fundamentals that any beginner would probably be taught in an intro class.

I still have A LOT more to learn and was hoping to be pointed in the right direction towards a book / web-resource / course / set of videos to really teach the best programming practices / how to set things up in the best way possible (in my case, specifically, for .Net). I know this may seem subjective and every programmer will do things differently, but if there are any good books / resources out there that have helped you learn the important fundamentals / tricks (for example, self-documenting code / design patterns / ) that most good programmers should know, please share!!!

My main platform is .Net.


The basic idea for writing good code is that the code must be readable, well-commented and documented.

Other basic facts for writing good code regarding all the program languages are structuring the code in directories and files and indentation of course.

In the case of javascript the things could be more complicated, because the language allows you to use different style to accomplish similar task.

For example there are three different ways to define a JavaScript class.

Said that, which are the best resource (books/sites) or suggestion for writing good code (library) in javascript?

I'd highly recommend reading JavaScript: The Good Parts by Douglas Crockford to get you started on writing quality JavaScript code.

At the first place i would suggest you to get more familiar with JS object model I would suggest you to take Douglas Crockford's article on prototypal inheritance: and make comparison with classical inheritance model

More systematic approach of pros and cons of JavaScript can be found in his book JavaScript: The Good Parts

If you search for more broader architectural approach JQuery, ExtJs (a.k.a. Sencha), MooTools are great java script libraries/frameworks to start looking at their design principles.

Does anyone have a preference on getting feedback on their JavaScript code / apps? I am looking for general performance and architecture tips and wondering if there are best place for this?

Upload everything to GitHub? post snippets on Stack Overflow? Just keep re-writing my code every few months? ;-P

Would love to know opinions... feel like I am at that point where I can really absorb some advice from JS ninjas out there.

thanks, s

Just grab a few good books like JavaScript: The Good Parts and jQuery In Action. The former is particularly good for giving you an excellent, concise introduction to good JavaScript.

I am trying to get indepth knowledge on object literal and prototypes? how they relate and differ and when to use? Is there any good websites and book which dives into indepth on object literal and prototype with plenty of examples etc?


JavaScript: The Good Parts by Douglas Crockford is a book you're looking for.

Somehow, my code does not work. I can't figure out why, I'm completely new to javascript and thought this would work, in php it's similar. if(string != "string") works in PHP, but not in javascript, in javascript the code just continues. If I do it with =! it doesn't works...

var lastsite;

function checkSite (form){
if (document.getElementById('steam').checked  && lastsite != 'steam')
    $('#signaturestuff').append('<b>Style:</b> <input type="radio" name="style" value="1" id="steamstyle1" onclick="testButton();"> Style 1');
var lastsite = "steam";
  1. You can compare strings with "==" in PHP and Javascript (but not in C, C++, C# or Java)

  2. You probably should compare strings with Javascript compareLocale ()

  3. In either case, you need to look at the value of "lastsite" in order to figure out why your comparison isn't working. Who knows - maybe you just forgot to assign it ;)

  4. Firebug is a wonderful tool, if you're not already familiar with it.

  5. "Javascript: The Good Parts" is a wonderful book, if you've not already read it.

May be this question duplicate or redundant but i want to elaborate my question so:

i have tried looking to google and flipkar,amazon that ...but by just looking at the book you can't really judge how it will be...and it's always good ask someone who has experience...because i can't keep on buying to find good book

I want to buy books on jquery and javascript,and please consider that i am not a experienced in javascript and jquery neither a beginner i want buy a book that has a very high level that all goes above my head...

if some experienced one can reply to this it will be helpfull...and all others(less experienced) are also welcome.....

Hoping i will get good answer :)

First book to become JS developer is

JavaScript: The Good Parts

I love this book as well

Eloquent Javascript: has very basics of JS and best for that

if you want to test your perfection there is a way...

A Test-Driven JS Assessment: A set of failing tests that cover various JavaScript topics; can you write code to make the tests pass?

10 things I learned from the jQuery Source will help you understand how to dismantle others JS scripts perfectly