Fellow Stackers,

In the first Computer Science class I took, the professor used C++ as a teaching language. He emphasized that the important things to understand are the concepts of programming, not just the language itself.

In the past few years, I've fallen in to a career in database driven web development. At first, I was busy learning to use the server-side programming tools, namely ASP.net. Most of my fellow co-workers from my early days didn't use much client-side scripting code, but I've been making a big effort to learn to write good client side scripting.

I've begun using jQuery in earnest.

The first thing that most any C++ or .net developer will notice about JavaScript upon first encountering it is that the syntax is remarkably similar to C-style languages.

There are important differences. JavaScript uses variant data types, allows for arrays to be declared in-line, and uses it's own object syntax with curly braces. Above all, JavaScript is an interpreted language that allows for a user to interact with a "document-object-model" using a web browser which C++ is typically compiled into native code (or sometimes managed code). It would be silly to make more than a superficial comparison of the two languages.

What I would like to ask is, "As I learn to write JavaScript code, part of my mind can't help but think of it as being like C code because it looks like C code. What mistakes am I likely making on account of this? What useful features of the language am I likely not using?"

Update: I edited my question title because it's clear that my old title was ambiguous :-/

  • +1 but I have a strong feeling this question is going to be [closed] soon. – pixelbobby May 11 '11 at 19:32
  • 1
    It is a good question, just not sure how to answer it – Neal May 11 '11 at 19:32
  • C != C++. Which one are you familiar with? The least difference that makes is whether answers have to state "OO is very different, there are no classes but prototypes" or "There are objects [...]". – user395760 May 11 '11 at 19:34
  • 1
    Uhm, C++ is not a superset of C++. ;-) But I think you meant C. Anyway, no, C++ is not converted to C before it is compiled. – Marcel Korpel May 11 '11 at 19:44
  • 1
    @CharlieKilian run your js code through jshint in your build process. – Raynos May 11 '11 at 19:53

It's mainly an issue with writing procedural code in JavaScript. You'll miss out on two big features if you write JavaScript like C :

Prototypical OOP and First class functions

Prototypical OOP allows you to create new objects and apply many of the OOP patterns of other languages. It's rather different from classical OOP.

A good article on that would be JavaScript Garden Objects section

First class functions allow you to pass functions as arguments and this allows you to write functional code. With just this alone you can get close to the power of LISP, ML or Haskell. Again a good article is JavaScript Garden Functions section.

The reason why these two things are big is because they allow you to use the OOP paradigm and the Functional paradigm.

Otherwise you will be stuck writing Procedural JavaScript forever.

  • Yes, good example! I learnt about this when I started using the jQuery-UI autocomplete widget. You can specify your own function to look up autocomplete matches and then call a function that autocomplete passes to your function. It took me a while to understand, but it is enormously useful and malleable. – Daniel Allen Langdon May 13 '11 at 14:05

There is not nearly enough room here, besides, since there is at least one great source I just post a link:

To learn the REAL (deep conceptional) basics of Javascript watch the videos from Douglas Crockford at http://developer.yahoo.com/yui/theater/

He's one of the most important people in bringing to light the (until then) hidden great power of the language. Besides, he's a very good presenter even for such a relatively dry topic as a programming language.

However, those videos are not very suitable for beginners in programming, but then the question you raise is not a useful one for them either since any answer requires a deeper understanding and quite a bit of practice as well.

Core Javascript is very RAW. You do things that in other languages happens at compile time, for example, when your JS program is loaded you already execute code which assembles objects, "classes" etc. dynamically - and after that initial loading and execution it can be a COMPLETELY different piece of software. You don't have these two stages in any other (old) language (you can do it in Ruby, similar story, those modern languages share certain features). It is therefore NOT helpful to compare JS and C/C++, especially not when you only look at syntax leven stuff, in which case you'll learn nothing at all. It can provide the illusion of learning, though. WATCH CROCKFORD.

A block scope example for the discussion in another answer here, since I've no other place to put it now (for convenience wrapped in function "foo"). There is a claim you cannot have block scope in Javascript. Granted, in other languages you use a much more familiar syntax, often just enclosing {} or sometimes BEGIN... END. Anyway, the below delivers EXACTLY block scope. Yes, it uses the "function" keyword, but just because you're not used to it does not change the facts.

function foo () {
    var a = 1;

    (function () {
        var a = 2;
    })();  //IMPORTANT: the "()" executes it immediately, INLINE


Calling foo():


If somebody still says "block scope is impossible (in JS)" they should point out what "block scope" is supposed to have that the above example does not provide, apart from needing some getting used to and being less esthetically pleasing than wrapping code in {} or BEGIN...END.

  • 3
    +1 for good reference. – pixelbobby May 11 '11 at 19:40
  • 2
    @Morre Generically you can refer to it as block scope but your renaming function scope to block scope. (function () { and })(); are not keywords that start a new block and end a new block. Yes you've created new scope, but you've created local scope inside a new function. This new function you created exists but since it's not named you don't have a handle or pointer on it. There is a subtle difference. – Raynos May 11 '11 at 20:43
  • @Morre as a seperate matter. The let statement that's coming in the next version of JavaScript creates real block scope. – Raynos May 11 '11 at 20:46
  • I see there are quite a few Crockford videos in the link. Which ones would you say are most relevant to my question? – Daniel Allen Langdon May 12 '11 at 16:49
  • Nice, my office has the linked videos blocked :-/ – Daniel Allen Langdon May 12 '11 at 16:50

I'd say

  1. Closures
  2. Nameless inline objects
  3. Dynamic typing
  4. Garbage collection
  5. Dynamic arrays and objects

but however someone coming from C may not actually "miss" these features... one could happily use javascript as C (of course losing a lot doing so and also creating a true nightmare for fellows programmer that actually know javascript if they have to work on the same project).

  • 1
    Arrays are not like arrays in any other language, instead they are implemented using objects, and those are hash-based. So you don't gain the usual speedy lookup of array elements through the index. I don't have a good feeling with the above list, pls. DO try Douglas Crockfords videos. Before I found them a few years ago I had thought I knew Javascript pretty well (since the very first release in Netscape) only to find I knew NOTHING at all. Yes, you CAN program it "like C" - in which case you are not using it at all, actually. – Mörre May 11 '11 at 19:47
  • 1
    More importantly then "losing a lot" is making it difficult for future developers. Writing procedural JavaScript will actually hinder future developers on your project, it's not a personal choice you can make, it's a team choice. – Raynos May 11 '11 at 19:47
  • Explicit garbage collectors exists for C/C++. Take a look at this or this. Finally you can write GC yourself in C/C++, albeit this is not an easy task ... – Agnius Vasiliauskas May 11 '11 at 20:12
  • @Raynos: I agree (see edit). It's exactly like working on a C++ program when someone that only really knows C just keeps memcpy-ing objects around and uses fixed-length char arrays and strdup instead of std::string. This is the nightmare in which I'm currently forced living at least part of my life... :-( – 6502 May 11 '11 at 20:28
  • @6502 time to use C++ as a better C then C. Sure you could lever the power of C++ but why fight it on your project. C isn't that bad. – Raynos May 11 '11 at 20:30

(Removed previous example)

I think the #1 cause of confusion is lack of block scope in JavaScript:

Here's an example:

if (true) {
    var foo = 7;

"7" is alerted. Not an expected result to a C++ programmer.

  • Lack of block scope is a big thing. The actual problem here is creating anonymous functions in a loop. Rather then using a closure refactor your code so you don't create functions in a loop. – Raynos May 11 '11 at 19:51
  • There is no lack of block scope! I can use an immediately executed anonymous function INLINE in my code and have exactly block scope. Q is, is it useful - but you CAN. Example: outside-code...; (function(){ ...my-code-block...})(); ...again-outside-block; – Mörre May 11 '11 at 19:53
  • 2
    @Morre that's not block scope, that's local function scope. There semantically different. { foo() } is a block and is a valid statement in javascript. It's just generally not used without a for or if statement – Raynos May 11 '11 at 19:54
  • 1
    @Morre: a "block" is a set of statements wrapped in curly braces (as defined by "JavaScript: the good parts." That's where the confusion is here. – Andrew Whitaker May 11 '11 at 20:13
  • 1
    @Morre But your overloading the definition of block. A block in javascript is { console.log(1+1) } { console.log(2+2) }. That is valid code. I merely disapprove with the term "block scope" because it's too tightly coupled with the non-mutable definition of what a block is in javascript. Your overloading names. Block scope is not possible, your example is creating new scope. new scope is possible, and it's a good thing to do. – Raynos May 11 '11 at 20:31

How JS differs from C++:

  1. Dynamic Typing
  2. Functional Programming (leading to nested functions,scope chains and closures)
  3. Classless OOP and prototypical inheritance
  4. Absence of block scope
  5. Interpreted language
  6. Scripting language (therefore dependent on the environment)

In fact, I wrote a couple of tutorials on JavaScript that highlights these same points. You can read it on my blog

  • I enjoyed your write-up about Javascript you link to. I wonder if there is a .net array equivalent for the Javascript Array.join function... – Daniel Allen Langdon May 13 '11 at 16:54

What I always miss:


or something very similar (= formatted input/output).

What C developers will probably not use that much (at first): functions (lambdas), unless they were using function pointers heavily in C.

  • I/O is not part of the core Javascript specification, but esp. the commonjs project has taken care of that, the most famous project implementing that is node.js. I/O is something very specific (hardware, environment), core Javascript is really just "language core". – Mörre May 11 '11 at 19:43
  • printf === console.log – Raynos May 11 '11 at 19:48
  • console is NOT part of "Javascript" but added by some actual piece of software on top. You may or may not have a console object. – Mörre May 11 '11 at 19:59
  • printf is not just printf but the whole spectrum of formatted input/output (sprintf, sscanf, etc.), which is really missing. – SztupY May 11 '11 at 20:16
  • 1
    @SztupY if your missing sprintf then that's a different matter, I agree we don't have that in JavaScript. – Raynos May 11 '11 at 20:44

Here's an example that I learnt about recently: the arguments variable. This variable can be used within any function to access the arguments passed to the function as an array.

When I first learnt that you could declare a function with x parameters and invoke it with y parameters
(x!=y), I thought that it was awful. I thought that doing something like that should generate an error; the result of thinking about the Javascript code as if it were C code.

The arguments variable allows you to work with a function that may receive any number of variables. Consider the following example:

function returnCount() {
    var count = 0;
    return count;

var number = returnCount('alpha','bravo','charlie');

When returnCount is invoked with 'alpha', 'bravo', and 'charlie', it will alert with all three values and then return the number three. Learn something new every day!


I found Douglas Crockford to be quite informative. In addition to the videos mentioned in the previous answer, Crockford has a web site with very good information as well: http://javascript.crockford.com/.

I'd like to add something new I've learnt that C developers are likely to miss: the small number of primitive data types and the strict equality operator (===).

Javascript has only boolean, string, and number for it's primitive data types.

Of course, C has boolean and string (C-strings, yada yada yada...), but C has many different types of number primitives: 16-bit integer, 32-bit integer, 32-bit byte float, 48-bit float and so on. Javascript has only a 64-bit float, the IEEE 754 Double Precision floating point.

Unfortunately, this does weird things with arithmetic so that for example, 0.1 + 0.2 == 0.3 evaluates to false because of the way floating point arithmetic works.

As for the strict equality operator (===), it works like the normal equality operator, but without type coercion. That means that 3=="3" evaluates to true, but 3==="3" evaluates to false.


Here's another snippet (excepted from the following link) of code that gives my C-head a migraine. It allows you to define custom events for your Javascript code.


var CustomEvent = function() {
    //name of the event
    this.eventName = arguments[0];
    var mEventName = this.eventName;

    //function to call on event fire
    var eventAction = null;

    //subscribe a function to the event
    this.subscribe = function(fn) {
        eventAction = fn;

    //fire the event
    this.fire = function(sender, eventArgs) {
        this.eventName = eventName2;
        if(eventAction != null) {
            eventAction(sender, eventArgs);
        else {
            alert('There was no function subscribed to the ' + mEventName + ' event!');
