JavaScript as a First Language

At Khan Academy we’ve been investigating teaching Computer Science to students in some new and interesting ways. The most interesting aspect of which is that we’re likely going to be teaching them JavaScript as their first language.

We’re in a very unique position as we’re primarily aiming to teach students who’ve been through our previous math and science-centric curriculum. Because of this we can create some rather compelling exercises and projects that never would’ve been feasible otherwise.

The prospect of teaching the JavaScript language as a first language is actually really exciting. Teaching prototypal inheritance to experienced classical-inheritance-using developers is normally rather frustrating (and results in many libraries springing up attempting to replicate the classical style of inheritance in JavaScript, which is a whole realm of weirdness in-and-of itself). Teaching prototypal inheritance to someone who has never seen any form of inheritance before will decidedly be an easier task. The same goes for learning functional programming. JavaScript is a great language for experiencing functional programming and can be a major focus of our curriculum as a result.

As we’ve begun to look at the prospect of JavaScript-as-a-first-language a number of obvious warts stick out (as is obvious to anyone who has worked with JavaScript for any duration). To make sure that general warts don’t crop up we will be using some form of linting (either JSLint or JSHint or similar) in the code editor to give the users contextual information on what’s happening with their code and why they should be writing their code in a certain way.

We want to go beyond basic syntax tweaks though and find ways of using the language that’ll result in an easier learning experience. In particular there are two changes which will likely result in a much simpler on-ramp to learning.

Note: These particular recommendations really only make sense if you’re teaching JavaScript to someone who has never seen the language before and is really only programming with a set of specific, well-coded, libraries. Obviously more will have to be taught in order bring the students up to the level of “see any random piece of cross-browser JavaScript code and understand what it does.”

Type Coercion

Type coercion is just a complete mess, as many many others have pointed out and as what Douglas Crockford typically teaches, as in JavaScript: The Good Parts.

It might make sense to discuss it far later in the education cycle… like after learning about prototypes, functional programming, and closures. Basically after everything that’s actually important.

name === "John"

The first change that I’m recommending is that the students will only ever see, and use, === (and !==). While using ‘==‘ does have the advantage of being syntactically shorter there is so much type coercion baggage attached to it as to make it an exercise in futility to try and teach early on in the learning of programming.

The one exception that might be worthwhile to teach later on is the case in which you wish to see if a variable contains a null or undefined value. This can be done easily with a simple someVar == null check and is likely the one useful case of ==. (Another noted exception is the browser bug in IE where === checks against Window objects will always return false, but it’s unlikely that we’ll cover such specific browser issues in our curriculum.)

Falsy Values

For the same reasons that == can be messy, so can falsy values. Enforcing strict boolean checks would result in less edge cases but would certainly result in longer code. Perhaps education of falsy values can be limited to booleans, null, and undefined with number and string falsy values left for a later exercise.

Function Declarations

Perhaps the most interesting change that we can make is a rather subtle one, but it’s eschewing normal function declarations for creating anonymous functions and assigning them to a variable.

// Don't do this:

function getData() { }

// Do this instead:

var getData = function() { };

There are a number of good habits that are instilled when you use this particular technique.

Makes it easier to understand “functions as an object”. I’ve found that when you show new developers a function being assigned to a variable it suddenly becomes much more obvious that a function is actually an object and can be manipulated as such (and that a function can be passed as an argument to another function). Thus students are advanced along the path towards a better understanding of functional programming.

It enforces good semicolon habits. Traditional function declaration is the only situation in which semicolons aren’t needed (save for conditional statements and loops, naturally) and it makes it much more obvious when they’re required all the time.

Block Scope

This is the remaining area that’ll certainly be a challenge for any introductory student to understand and yet I don’t see a particularly good solution here. The issue of variables declared within for loops hoisting up is more than enough to make most developers heads spin. I’ll have to see if we can’t come up with some intuitive ways of explaining how variable declaration works (and combining it with vigilant lint enforcement) rather than having a purely technical solution.

(While (function(){ ... })(); is a solution I’m skeptical that we’ll be able to teach that early-enough on as to make it worthwhile.)

JavaScript as a First Language

It should be noted that while we’re starting with JavaScript as a first language – largely due to its ubiquity, desirability in the larger workforce, lack of prior installation requirements, and ability to create something that’s easy to share with friends – we’re not going to be myopic and only focus on JavaScript. There are so many things that can be learned from other languages, not to mention entire skillsets that aren’t terribly relevant to in-browser JavaScript, that it behooves us to try and bring as much of them into our curriculum as possible.

I talk a little bit more about our choice to use JavaScript and some of the browsers that we’ll want to support in our development in the following video:

By all accounts I want to try and avoid any features that would cause cross-browser weirdness to spring up. As a result we’ll be making extensive use of libraries (for drawing to a canvas or manipulating the DOM) and using only JavaScript language features that work consistently in the browsers that we end up supporting.

Just to further support this, we actually teach JavaScript as the first language in our Mobile degree program at Full Sail University. It serves as an introduction to programming (without any DOM until later classes), before they eventually move on to Objective C and Java.

I completely agree about === and never relying on “” and 0 being falsy.

Not sure about function expressions. Without the hoisting behavior of function declarations, you have to worry use-before-defined problems, which still bite me sometimes. How do you plan to deal with that? Just teach good code structuring discipline?

Have you thought about how you’re going to integrate let into the curriculum once it starts being available in browsers? And what about const?

I think it is not necessarily easy to justify JS as a first language from the point of view of linguistic structures. However, its safe to say that

(a) Javascript is not going away in the forseeable future — you will be using it for the rest of your professional life

(b) It is the one language that you are most likely to use no matter what you do with your career (unless you get truly exotic and work on embedded systems, or for NASA or something. And even then…)

(c) Javascript has not gone through versions and evolution, so no matter how far back you go, you will be able to read the code easily. As a student, you aren’t likely to get confused with changing APIs, deprecated commands, etc. (Unless you start using Node… :) )

(d) The core libraries are finite; it is conceivable to expect that you will learn every method, object etc. of the core library without your brain exploding.

I’ve been ranting about the futility of shoe-horning classical inheritance paradigms into JavaScript for some time now. Sometimes it seems like we can all agree that “composition over inheritance” sounds good in theory, but as soon as we get the chance to use a language that really embraces that notion we immediately resort to various “extends” and “Class” hacks.

One short note about == vs. ===: while I agree that it’s probably a good idea when teaching beginners to always use ===, there is one more exception that I make for using == besides checking for null/undefined values. It is when you are absolutely sure of the type of the operands. For example, I can safely assume that the length property of an array is always a Number, and that the result of using typeof will always be a String. Thus, I can safely use something like if (array.length == 0). But then again, that may be a bit too much for a beginner to think about. Not sure.

As far as teaching scope goes, it’s going to be tricky. Whenever I teach it to programmers, I usually start out with some basic rules about vars and functions, but the whole thing falls apart as soon as you start talking about assigning functions to vars (as in var foo = function). I’d love to be a sounding board for ideas that you have in this area, if you need something like that.

@Dave: Yeah, plan on tackling that through good coding conventions. I find that it tends to make sense to a new developer: You want to call a function, that function must be defined before you can call it. If you’re use to defining functions in that way you wouldn’t expect it to happen in any other way.

Haven’t really thought about let/const – although let would certainly be way more attractive. What’s browser support for it, these days? It seems like it’d be a hard pill to swallow to complete reduce browser support to the latest browsers (including only IE 9+). I’d like to try and avoid discussing cross-browser issues for as long as humanly possible.

@Dmitry: In my video, I talk about not supporting IE 6 and 7, but that doesn’t change many of the larger language issues.

@Michael: I guess in those cases (array.length == 0) it simply feels cleaner to me to be absolutely consistent with your operators. It’s only one extra character, and I remember doing some performance testing on it way back in the day seeing that it’s minutely faster, so might as well give it a try.

A big issue in using javascript as a first language is the “all numbers are floating-point” problem. The behavior of floating-point numbers is extremely non-intuitive unless you know how they work. All beginning classes I’ve seen have resorted to hand-wavy “don’t trust numbers to do what you think” comments from the teacher.

I’m very happy to hear that JavaScript is being taught to new programmers. Especially because of the short development cycle of save file/reload page in browser gives quicker feedback about what is or isn’t working. This is essential for those learning how to program. I also think you’re sending a good message that JavaScript isn’t something you just “pick up”, but is actually a legitimate programming language for learning CS concepts.

First, I think that it is great to teach JavaScript as a first language. It is important to remember that while OOP is very popular, there are also some other paradigms that can sometimes be more useful. I believe teaching JavaScript as a first language is going to raise the popularity of prototype-based and functional programming, which I think is great.

I also think that it is important that you make it clear for students that JavaScript is very different than other popular programming languages, so they won’t get confused when they suddenly see something in Java or C#.

Also, about block-scope, I don’t understand why are you making this a problem. Why won’t you just explain that in JavaScript variables have function-scope and explain how the function-scope works?

Javascript cannot just put a variable anywhere. It must belong to a variable container. If you are not in a variable container, javascript will look for the first pair of curly braces that represents a container. This is usually the function itself. So if you declare a variable inside a for loop, since the for loop is not a container, the function which contains the for loop will become the owner of this variable.

Then go on to list all the different kinds of ways to become a “container” for a variable. And I think that should make sense.

If you declare all your variables in a single var statement at the top of the function, you don’t have to worry about explaining complex function scope and hoisting issues to newbie programmers. Just tell them that’s how it’s done from the start, and it won’t be a problem for them.

Interesting post. I’ve been pondering trying to teach my wife a programming language lately (since i have a theory she might enjoy it, but unfortunately has never been exposed to it before.) As someone raised on BASIC, Assembly, C, C++, Java, etc … I thought “JavaScript will be a hard language to pick up, scoping and inheritance is abnormal” — but in fact maybe it would make far more sense to a total blank slate than the C++/Java way of thinking of the world. Well anyway I look forward to any tutorials that might come up if I go down this road with her!

I couldn’t agree more with you John. I tried to do this also a few years ago, but abandoned the idea due to lack of support from others at the institution.

Noone can deny the fact that JavaScript is an extremely useful language that prepares very well for other more traditional programming languages. Students can do very interesting things very quickly. The aim for the first programming module or course should be to get students interested in programming, and for that JavaScript is the best language in my opinion.

I think it’s a fascinating idea for an introductory course trying to provide an ankle deep coverage of as many areas in programming as possible. Particularly in the point that JS is very well suited for learning both basic OOP and basic Functional (as well as iterative clearly) without the potential of losing basic concepts in syntax.

Would love to see how it plays out in comparison to the current trend of Python-first education.

As someone who spent time teaching high school seniors programming at the end of most summers during the 1990s, I’d just like to chime in and say generally that JavaScript fared pretty well compared to the other languages we tried (Pascal, Prolog, and Java). I have a soft spot for Prolog because of the power and conceptual depth of the logic paradigm, but I think JavaScript was the clear winner at balancing accessibility, the speed at which students could learn to do something practical, and available depth. And nearly all of them did quite well — despite the fact that most of us who were teaching them were only beginning to discover and come to grips with issues of how scope and coercion worked.

On a specific note, my observation is that consternation about the `var` not invoking block scope is probably similar to classical OO — it’s largely an issue for developers who’ve already learned to do things that way — and that new programmers seem content to accept `var` as invoking scope internally across a function.

I would consider JS to be my first language. As a front-end guy it’s a necessity and I’ve found that learning JS has made it easier for me to learn the more complex languages that are required to develop more data driven app and mobile-centric websites. Immediate feedback and understanding the relationship between JS and UI Design gave me confidence to tackle more abstract concepts.

@Eric: Good point about the call stack – although I’m skeptical that we’ll get to that level at the very introductory levels. By the time they get to the level in which a call stack makes sense we can explain alternative solutions to this particular issue.

Regarding the single declaration just being “the way it’s done” – that’s actually not a half-bad idea, something I will definitely consider.

@Weston: That’s a good point regarding block scope expectations – maybe it just won’t be as much of an issue with new students. We’ll see!

One major problem I have met with students that start with high languages ( java C# etc.. ) that they never acquire full understanding of memory proper usage. I even noticed that the common programmer ( not the top notch ) which start with C++ tend to over think memory allocation and a like. As a programmer and as an employer I still find people which start with C to have better grasp as how to avoid programming traps, they tend to develop more basic view as to “how things works”

Whatever else you do, I would make it clear to them that the language is flawed, that they will encounter things that don’t make sense and they should just accept it and move on. Just knowing this can save a lot of confusion and frustration if they are coming in with an idealized image of programming.

Took an intro to programming class about a year ago and they taugh C++… it was a pain because they gave a live CD of a custom build of OpenSolaris with the libraries need for the project we had to complete… but this forced us to use an awfully old version of eMacs and it would forget or settings everytime… I had to explain to so many people how to boot from the CD in that class it was a bit ridiculous… Javascript is from my point of view the easiest language to learn currently since its available with basically all of its feature on every computer with a modern browser. Its great to hear that this is the course Kahn Academy is taking…

I think teaching JS as a first language is a great idea. Its ubiquity, C-based syntax, and feature set make it a great intro language.

I think you should make sure there’s at least one lesson pointing out the gotchas / bad parts. Maybe later on in the course after students have picked up the basics and understand JS. It’s important for people to understand that it’s not all rainbows and unicorns.

I’ve never found block scope to be a hard concept. I think a single lesson dedicated to it should make it pretty clear. I think the reason it’s a problem for many people is that they come from other languages and never learn about block scope and hoisting. Then when they encounter it they get very confused due to ignorance.

Last year I taught some kids 9-11 an introduction to JavaScript. I was extremely interesting to see what worked and what didn’t. I have a bunch of ideas to try for next year and I suspect there will be an entirely new set of things that work better or worse than expected.

I’m not sure if what I learned is of value to you but there may be some useful info here, so I’ll relate my experience.

I chose JavaScript pretty much for the exact reasons listed in the Video. I focused upon canvas only output. In a way I was influenced by the BASICs that I experienced as a youth, simple code doing a graphic output seemed most immediate to me. The first ever program I can remember writing(copied from a book) was a screen filler

10 set (rnd(128),rnd(48))
20 goto 10

I wanted that immediacy, so I have a small set of functions available for simple canvas rendering.

I based the first lesson around showning a web page with some inline JavaScript then splitting it into a page.html and a program.js
From there students focused on the .js files only.

Originally I had page1.html running program1.js and all files in the one directory. It proved much more expedient to switch to a page.html & program.js each in their own directory. This allowed students to quickly make copies of programs without having to do any renaming of links.

From the start I aimed for a extremely quick path towards animation then interactivity.

Once students understood that page there were things they wanted to do, implementing their ideas allowed introduction of more aspects of JavaScript as they were needed.

A common path was for http://fingswotidun.com/javascript/Program3/page.html students would complain that the circle was too slow, making it faster was a good way for them to understand how the position(and variables in general) can be changed. Once it goes faster It quickly leaves the screen. So far, every student who has done this has wanted it to bounce off the edge. That’s when they learn their first if statement. They also get a dx and dy for the direction of the circle. Once that is done, adding a dy=dy+0.01 makes gravity work. The Circle is now clearly a ball and suddenly it feels like they are manipulating something more real.

Because of the age of the kids there were a few surprises. X being horizontal and Y being vertical are so ingrained to me I didn’t anticipate the kids having trouble with remembering which was which, but they are arbitrary definitions which simply have to be remembered rather than learned. Next year I will write a helper program that demonstrates screen coordinates so the kids can refer back to it.

Objects came very naturally to the kids.
var ball = {x:10, y:20};
was taken as simply more convenient rather than more complex.

I used both forms of function declarations. For one student, the ball object became an array of balls with a howToDraw field which was set to one of two values
var drawSoccerBall=function(x,y) {…};
var drawChelseaLogo=function(x,y) {…};

I did find some students were confused by function declarations initially. At first, they expected the code to run as the declaration was encountered in the source. the var declaration form may not have this problem so much.

Based on my experience with learners in similar contexts (students learning such languages as Scheme and Standard ML), I believe that defining functions as values and binding them to vars is a very good idea. It is remarkable how many people start out with limited notions of what a function is (and how hard it is to unlearn those misconceptions) just because the “usual” syntax looks so different.

I have been teaching an introduction to programming course at The Creative Circus in JavaScript since last Summer and have found it to be a great experience.

You are spot on with the need for jslint in the editor (I use jsfiddle in the early parts). They need to move in to a real editor soon though, so that they learn how to add script tags and how to apply their knowledge to real web development. They also need to know how to look at the error log for things that cause their program to stop working but jslint can’t catch.

Another note on in browser editors. The code shouldn’t run on load like jsfiddle. This makes it difficult to teach looping, because they will invariable create infinite loops.

I found students really enjoy doing development with canvas. One of their assignments is to create a business card using canvas. This is good early on because they don’t have to understand the DOM.

In the early stages I also made extensive use of a printLine() abstraction and prompt() statements before they learn about the dom. They can get basic data type understanding, conditionals, looping constructs, and functions without being bogged down with the dom. That being said they get bored with it quickly. They really want to create applications that are real world. They want to know why I am learning all of this stuff.

That is a great note about doing explicit boolean comparisons. My approach was to simply have them memorize what the falsey values are and know that everything else is truthy. It turns out that they don’t have an appreciation for terse coding this early in their career, so it is hard to bring home. It is important to know though so you can understand other peoples code.

As far as DOM development goes I just straight up taught jQuery. I am sure this is controversial. My thought is that it does not seem productive to teach a way of interacting with the web page that is highly error prone and not production ready. Direct DOM development in my opinion has become a higher level skill because of JavaScript frameworks, and most programmers will never need to know it beyond a few basic things.

Another thing I like to emphasize in my intro class is high level concepts like abstraction, configurability, and the DRY principle. They have a tendency to hard code functionality without understanding these principles.

Glad to see Khan Academy teaching this as a first language. Stanford also has a Computer Science 101 class that uses JavaScript.

It looks like you’re wasting a lot of your time by teaching how to avoid JavaScript traps instead of focusing on core programming concepts (such as managing state, isolating functions loosely coupled, abstraction patterns, composition patterns, etc.).
BTW, I think you can not teach programming without introducing static typing and discussing a type checker can do and can not do.
But maybe you want your students to make beginners mistakes so they will understand more easily the benefits of static typing, immutability, refactoring using IDE, etc.
(I’ve nothing against you a respect your work, John Resig, I just don’t understand why some brilliant people are promoting a so badly designed and painful to use language as JavaScript instead of investing their energy and time to make browsers a platform really suitable to large scale and agile development)

I do not think this would be optimum for new comers even thought i’m a die hard fan of JavaScript. You can teach ‘Io’ language instead of JavaScript which has all kind advantages you have mentioned and which has few set of parser rules that would be easier for new comers.

Out of curiosity, why not avoid block scope problems by teaching using a modern JavaScript VM, and using “let” rather than “var”? If the goal is to learn a programming language, rather than a web development language, then surely the web browser itself shouldn’t be included. I would assume that things like DOM manipulation, libraries, etc. would only be covered at the very end of the course — well after “==” and so on.

Teaching around a more modern JS implementation also has the advantage of the various library-like functions (foreach, map, filter, etc.) coming for free — most of which very clearly reinforce JavaScript’s functional roots.

The thing with first programming languages is that if you teach someone in a language they will hate everything that is too different from it. All the Lisp folk I met (the two or three of them) hate every single part of most of the traditional languages. That is why you should teach the basics in a crappy language, so they will be more open to the different languages. Pascal comes to mind because it’s more simple and bare bones than C, it takes longer to do stuff if you know what you are doing, but at the same time doesn’t incentive bad programming habits.

If you teach in pascal you would be glad to use a any other language. If you teach in Javascript they will HATE C++, Java and pretty much any statically typed language. I know it’s boring to teach pascal and classic programming, but it’s better for the student.

Javascript would be a great language to introduce the more advanced concepts like dynamic languages and object orientation.

Using javascript as a teaching language is a terrible idea. OOP is a mess in javascript. Also common CS 101 things like polymorphism, etc are much better suited to something like python rather than javascript.

Additionally there are a number of higher level concepts that are fundamental to javascript (like anonymous functions) that will need to be explained during a first semester course.
Also the structure of javascript to foreign to most other programming languages in use.

Please, whatever you do, let them learn the basics. Wayyyyy too many graduates of CS programs come out without knowing the basics like how to sort, what goes on underneath common data structures like lists and hashmaps, or a dozen other things that they really just need to know. The biggest issue I have with most programmers who start with Javascript is that they never learn the basics, and thus their skills are not portable.

Please consider using CoffeeScript as it solves several of the issues you mentioned. `==` automatically becomes `===` and the function creation syntax only allows the kind that is preferred.

As for the block scope if you use iterators (such as each) rather than ‘old school’ for loops it is not an issue because the anonymous function passed to the iterator has its own block scope. This will also be a useful stepping stone for teaching things like `map` later
["a", "b", "c"].each (letter) ->
message = "#{letter} is a pretty cool letter"

It’s cool that you’re expanding KA to new subjects, but if I had to choose, I’d much rather see KA develop the authoring infrastructure. Currently, the exercises can only check answers. The most advanced educational software programs give feedback on each step of a student’s solution process (like the CTAT suite: http://ctat.pact.cs.cmu.edu/ ). I’m learning how to author in your current environment, but it will be very complicated to write exercises that can check and provide feedback on students steps in the solution process.

Instead of teaching coding styles `===` vs `==` and `function fn(){}` vs `var fn=function(){}` why not teach students the ups and downs of both. I use the right equality operator for the job and reject blanket `===` use (same goes for function declarations and function expressions).

As someone who has tried and failed a wide variety of programming tutorials, courses and videos, I would only suggest that the lessons be framed as ‘problems to solve’… We’re going to sort this list. We’re going to get a user’s name and login. etc. I also think Yahoo Pipes would be a great place to teach programming principles. You could make cool things and then work backwards to take them apart.
Please don’t assume your students have done the math and science section of KhanAcademy before coming into the programming section. Excited to get started!

@Eric Hamilton: your example is bad because a function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in.

The scope in Javascript is so important and different from most other languages (especially PHP) that I would use “function getData(){}” as an example because it shows that not only variables but functions too are scoped and hoisted to the function they are defined in.

Also I wouldn’t call “var getData = function() { };” an anonymous function since the function can be called using “getData()”, the same as if it was defined using “function getData() {}”, whereas “”astring”.replace(/a/, function() {});” uses an anonymous function.

I used to define local function using “var getData = function() {}” until I discovered that functions ALSO are scoped, now I don’t see the point it that anymore.

I think JavaScript makes a really good first language – just don’t try and make it look like a class based hierarchical strongly typed language i.e. don’t invent ways of implementing inheritance.
Go with object construction – (literals to general object factories to constructors), composition and explain prototype (much later) as something you use for efficiency reasons.
And I agree with others about playing down the problems with JavaScript and concentrate on the “big” ideas.

I can see a couple of the advantages and disadvantages of choosing JavaScript as the first language. All else being equal I think I would choose a language that has warts only if you dive a bit deeper. As far as I know, and you explain, JavaScript has some places in the start of the learning path where you don’t want to be treading unless you know what you’re doing, which by definition of starting out with JavaScript you’re not.

Python comes to mind.

However all else is not equal and having pretty much everything in the browser and doing stuff with HTML/DOM really fast is a big plus for getting people motivated to learn JavaScript.

While, teaching JavaScript as a first language a progressive idea, I feel like it’s a bit too much to get your head around for a first language. You said yourself, you will also be introducing them to HTML5 and CSS. I think that if someone is new to programming it’s too much to take in. Fundamentally, you need to learn programming structures like loops, arrays, and branching statements. These are elements common to all programming languages.

I have yet to see a book “Java – the good parts”. My point is that even Douglas Crockford who thinks Javascript has some great features (closures for example) would agree that there are so many ugly parts to the language!

So, my suggestion would be to teach Ruby as the first language and then ease in to Coffescript! Why take them back 20 years when you are starting with a clean slate?!

As a long-term full-time Javascript developer I DO NOT THINK that Javascript is the best programming language as a first language.

I would not be happy that my child learns javascript as a first programming language. There are so many unusual and weired thing in Javascript…

Take this as just a hint of somebody familiar with both Java and Javascript (and many more) and who is using it every single day for a long period of time.

It’s definetly NOT BAD to teach Javascript, it’s actually quite good idea and the student can develop quite nice applications in weeks. But for the real good knowledge of the programming, it’s IMHO essential to teach real languages (no offence please, I do javascript every single day and I would say I love it!)

I would choose Java, even though it takes longer to get into it (OOP), it’s more complicated (threads, JVM), it needs some effort to set up the environment etc. etc.
Java has very strong standards, it can be used to many things (web pages as well as native apps or even quite complicated games) and mainly – switching FROM Java to another language (Python, Ruby, even PHP or Javascript) is usually like using light-weighted Java – so it’s very easy.
Java enables the student to use this knoledge later on, – use libraries (that copy standards), multithreaded apps if needed etc. Compared to use of javascript, there are much more possibilities to realy apply what has student learnt.

It’s obviously about audiences, and their future paths. If Kahn Academy is primarily interested in providing an exposure to “what programmers do,” I’d think a RCL (reduced complexity language?) would be a better bet.

Do people still teach Logo? Maybe if the student passes something like that, and liked the experience, a second language would let them get serious.

I actually wrote up a Learn Computer Programming road map, based on the old-school, ground up, technique. It climbs the LAMP architecture. I wouldn’t expect it to be for everyone. Maybe for throw-backs ;-)

This will end in tears for everyone involved. Sal, John and above all, the students.

While it is true that no language is universally elegant in all problem domains, using language as fundamentally flawed as JavaScript needlessly complicates pedagogy. Expanding upon John’s description of the == and === problem, JavaScript lacks structural equality by default. [1, 2, 3] == [1, 2, 3] and [1, 2, 3] === [1, 2, 3] both evaluate to false. The same holds true for objects:
var a = {};
var b = [];
a != b && a !== b;

(and for some bizarre reason, “{} == {}” is a syntactically invalid)

Libraries like jQuery and Underscore offer functions for structure equality, but they only work with builtins like Array and Object. The second you use them with customized Objects all bets are off.

Then there’s the fact that
new String(‘that’) == ‘that';
new String(‘that’) !== ‘that';
new String(‘that’) !== ‘that’.toString();

This makes sense if one understands that === is actually the identity comparison operator (analogous to comparing memory addresses), but it’s still very confusing for students.

And don’t get me started on the unintuitiveness of using certain functions (conventionally titlecased) as object constructors. Omit the token ‘new’ and you’ve just polluted the global namespace, potentially clobbering important state-encoding variables in the process.

Reading the comments, now I kind of want a “JavaScript for JavaScript coders” lesson. There are a lot of coding conventions and so forth I didn’t know about.

I think IE8-era JS is fine for this. Part of the fun is teaching kids a language that they can use for deployable programs, and that means working in at least IE8 for as long as Windows XP is around.

Mark’s right that, say, Python is probably easier to learn, but there could be far worse first languages than JS, and JavaScript’s adoption gives it advantages–lots of other material out there to learn from, and it’s not unrealistic that kids might actually use it.

Since you’re still in Boston, you should definitely talk to some of the members of the PLT group at Northeastern University, particularly Matthias Felleisen. Though they’ll probably have lots of issues with teaching JavaScript as a first language (like, say, all this weird stuff you just went over), they’ve been thinking about teaching programming for quite a while and have some good thoughts. Some of them are also responsible for the Program by Design project – http://www.programbydesign.org/who

Javascript definitely has some weirdness, but so does every language. I learned C as my first language, and that language has some really bizarre edge cases. C arrays are a lot weirder than most people realize.

Javascript’s hoisting is a bit strange, but I think that in practice most newbies are hardly going to notice. If you are teaching someone who has never programmed at all before, they are going to be more confused by basic things like for loops, how to do logic, and how to decompose their code into functions. All the basic stuff that programmers internalize so much that they forget it was hard won knowledge way back when.

“Processing is an open source programming language and integrated development environment (IDE) built for the electronic arts and visual design communities with the purpose of teaching the basics of computer programming in a visual context, and to serve as the foundation for electronic sketchbooks.”

I mentioned “reduced complexity languages” above, it might work as that.

The book Minimal Perl http://goo.gl/pQgdP took a subsetting approach. Perl has a lot of Bad Parts so faced some of the same problems you do.

This would suggest defining a safe subset of JS to start with, avoiding lots of subtleties initially. Yes, there are different ways to define functions, and variable hoisting is a problem and hundreds of ways to fake classes. Choose simple solutions and press on with just one. Don’t worry about DOM etc, just plain writing simple JS code which is pretty C like. And even tell it like it is, maybe calling it Minimal JS.

JS is not alone being difficult to teach. I’d never start with Python, for example, even tho it is starting to gain a lot of traction in schools as a first language. It is just too weird, depends on __foo__ in too many places and as soon as someone cuts and pastes code, the white space problem with hit. Java ditto, indeed I’d use Processing as the subset to teach first. Let them learn later that they’ve been using Inner Classes.

I’ve long held that Marijn Haverbeke’s “Eloquent JavaScript” would make a great early CS program text, so I’m certainly in support of the Kahn Academy taking steps to introduce the language early in its curriculum. I agree with John Dalton’s “right tool for the job” approach – all techniques should be taught, so they are all understood.

A common problem with intro programming courses is that output from programs is purely numbers or strings, which have low motivational value. You propose to get students into doing things on the web page, including the canvas, as early as possible, which is good. Of particularly high motivational value is doing 3D animations, and there’s a new JavaScript environment in which this is easy, glowscript.org. For an overview see the Help available there or see this article:

Bravo! With node.js and MongoDB, JavaScript can be the only language one needs. Professionals need to learn more, but the 20 million others can get by with just this one language. Nothing else compares. And with jsLint use, it can be very pleasant.

@Petr Urban is probably right about dynamic languages making learning static languages feel awful. But it depends on the target audience. Non-professionals should not need to learn static languages. My daughter will be learning JavaScript as her first programming language.

At programmingmath.com, we had the idea to teach both math and JavaScript together, not assuming much background in either. The JavaScript intro was done (feel free to use): http://www.programmingmath.com/introduction/ but alas the only math post so far is on Newton’s Method though I do think it is quite well done. jsFiddle rocks for this stuff.

Excellent endeavour! I look forward to being able to build specialization-scoped “courses” on top of this, for teaching the awesomeness of the web medium: user scripts, $browser add-on writing, D3 data visualization, jQuery cross-browser comforts, et cetera.

I believe that you are presently creating the way into javascript for upcoming generations of web programmers, and judging by your last good book (for hackers, at least) Secrets of the JavaScript Ninja it will come out really well, too. I can’t overstate how happy I am that you’re building Khan these days – happy holidays!

Oh, I almost forgot my initial reason to post: when teaching data structures, I would suggest you stick 100% to JSON syntax, and make it the way students think of data literals.

Yes, it’s comfy for graduated programmers to use the short-hand syntax for objects, but with all the language keywords being verboten as unquoted keys, it is a really leaky abstraction to confuse students with early on.

Side benefit: thinking of data in terms of JSON also paves the ground for good REST API practices right out of the box, rather than pursuing other distracting offers on the web, but that’s another “down the line” kind of topic.

After some intro let students dive in to simple 3D graphics. That will keep them motivated. There’s a great cross-platform library which by virtue of the fact that it doesn’t use advanced, difficult WebGL, also works on all mobile browsers: http://kevs3d.co.uk/dev/canvask3d/k3d_test.html

John, teaching JS as a first language is a great idea! However, don’t assume that students live in a vacuum and if you don’t teach them something they’ll never see it. They will see it, because they will google something themselves. And since you haven’t talked to them about it, they’ll just pick up whatever they read in whatever random source.

I learned this the hard way. I thought if I don’t tell my students about inline event handlers and only teach them event listeners and traditional event registration, I would help them keep their structure and behavior decoupled. It was funny (in a sad way) when, at the end of the semester, EVERYONE (not a single exception!) turned up with ALL events done inline in their projects. Turned out they’ve been googling and because we never told them about this, they didn’t know it’s bad (for most cases) so they went with it because it’s easier. Of course we had advocated separation of concerns, but that was too abstract for them to actually realize it’s against what they were doing.

Hey, you can probably introduce node.js later on (last 2 lectures or so), just to show JS is not strictly tied to browsers, and can be used as a general purpose programming language.

Maybe even top it off with an introduction to CouchDB views. Not very sure about this one though. Having worked with MySQL and DataMapper (Ruby) first, I found CouchDB views a little unconventional and difficult to understand.

Comments are closed.
Comments are automatically turned off two weeks after the original post. If you have a question
concerning the content of this post, please feel free to contact me.