Javascript / HTML5 best practices

Started by
8 comments, last by Alpha_ProgDes 11 years, 1 month ago

Hi guys!

Recently I had some free time, and decided to dive into javascript and html5 stuff. I'm looking for some book / series of articles that are talking about how to write efficient code, or what are the best practices, especially centered around html5 and game development.

I looked around the web, found a huge amount of resources, but it's really hard to decide where to begin. I have several years of experience with c++, so learning the syntax is simple, so I know how to organize my code or do anything I want. But I understand, that developing for browsers, or working with script languages like JS is different. I just don't want to follow some random tutorial that pops up in my google search and learn bad practices.

So, in short do you know any good javascript / html5 resources about game development?

Cheers,

Pal.

shaken, not stirred

Advertisement

Honestly, so few people know what they're actually talking about with JS, it's really hard to make any recommendations. There's a tendency these days to treat JS as a "low level" language (lol, I know) and everyone is scrambling to figure out what the best other language to get that "compiles" to JS (lloll, I double know).

As long as you're following very basic principles of OO and Functional Programming, not writing sloppy code, you're going to be fine. There are some cross-browser issues you will have to watch out for, but you'll find them with experience and figure out how to get around them. JS isn't hard, just spend a little time with it and you'll know what to do.

[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]

There are some cross-browser issues you will have to watch out for, but you'll find them with experience and figure out how to get around them.

Well isn't that what JQuery, Mootools, and other JS libraries are for?

Beginner in Game Development?  Read here. And read here.

 

First and foremost, since JavaScript is a programming language, the same general rules apply to writing efficient code:

  • Use the best algorithm for the task. Example, don't spend hours optimizing your bubble sort procedure when a quicksort will always be faster.
  • Use the features provided by the language's standard library, because they're probably written better than anything you'll create. Example, don't write your own quicksort. The standard library sort probably already does it.

Since javascript is a dynamic language, most of the same rules apply when optimizing:

  • Function calls to JavaScript are expensive. Calls to built-in functions may or may not be.
  • Dictionary references are expensive. Example: dictionary['thing']. If you need to access the same element more than once in a loop, assign it to a local variable before the loop then reference it with the variable.
  • Consider dictionary.thing to be equivalent to dictionary['thing'] as far as performance is concerned.
  • Functions are first class objects, and being first class objects they are no different than any other element in a dictionary on your objects: This line: "myobject.function()" can be considered the equivalent of "myobject['function']()" as far as efficiency goes. You can hoist this outside the loop too:
    
    var myobject = new MyObject(whatever);
    var hoisted = myobject.function;
    
    for (var i = 0; i < 1000; ++i) {
        for (var j = 0; j < 1000; ++j) {
            hoisted(i, j);
        }
    }

  • "for (var i = 0; i < arrayLength; ++i)" is more efficient than "for (var i in array)" or even "for (var i = 0; i < array.length; ++i)" when the dictionary can be indexed sequentially.
  • Use built-in functions whenever possible, because they're often implemented in a low level language and compiled to machine code.
  • jsPerf is a great resource.
  • Don't optimize until you've profiled.
  • What is fast in Chrome might be slow in Safari, Firefox or Internet Explorer.
In my experience with javascript performance wasn't an issue. I made a simple 2D tile based puzzle game. (link) When I implemented the collision detection for it I initially did an O(n^2) algorithm for checking collisions against all of the objects in the scene and would come up with a faster method if needed. I ended up not needing it. The bottleneck in the game for me was drawing the graphics. I even tried to optimize it by having all of the tiles draw once onto an off-screen context and simply copy over that large image once every frame to reduce the amount of drawing calls but it didn't really change the speed much. It seemed that copying over pixels is what took the most time, but in the end The game still ran fine. I also used a port of box2d for an editor in a physics based game I worked on and it worked surprisingly well. (link) Basically what I am trying to say is don't worry about your game running too slow. Just program your game in a way that makes sense and focus on making your code beautiful. That brings me to the next thing I want to take about. Classes.

Javascript does not have classes built into the language, but you have prototypes and that lets you create classes yourself. Read up on javascript prototypes. Make sure you understand what they do and how they work. I will write out the basics here.

To create a 'class' you actually define a function.
function Foo(bar)
{
  this.bar = bar;
}

Then to create an instance of a class you use the 'new' operator on the function
var foo = new Foo("string");

to add methods to the class you add functions to the prototype of a function

Foo.prototype.getBar() = function() {
  return this.bar;
}

Then you can call them on any instance of the class

alert(foo.getBar());

One thing that is great about javascript is it has closures. When I started using javascript I didn't use them much, the more familiar I get with javascript the more I love to use closures. Basically what you need to know is this. Functions can be used as objects in javascript and with closures, any local variables in the same scope where the function was declared can be used in the function. For example

var foo = "string";
var bar = function()
{
  // foo can be used in this function, 
  // even if var is stored and called 
  // later after foo is out of scope
  console.log(foo);
}

bar();

Any changes to variables in a closure are not reflected outside the closure (except for global variables) For example

{
  var foo = "original string";
  var bar = function() {
    // this only changes foo in this closure
    foo = "new value";
  }
  bar();
  // this will display "original string"
  console.log(foo);
}

My advice to you is to get familiar with closures. They are great and, if used well, can make your code beautiful. One thing to remember is that the local variable 'this' does not go into closures. If you need to pass 'this' in you need to create a temporary local variable. For example.

{
  this.message = "this is foo";

  bar = {};
  bar.message = "this is bar";

  var foo = this;
  bar.functionCall = function() {
    console.log(this.message); // this will print "this is bar"
    console.log(foo.message); // this will print "this is foo"
  }

  bar.functionCall();
}

What is happening here is 'this' is the object that the function is stored in when it is called.

Anyway, Those are a few things I think are good to know when starting javascript. I hope it is useful to you.
My current game project Platform RPG
There are some cross-browser issues you will have to watch out for, but you'll find them with experience and figure out how to get around them.

Well isn't that what JQuery, Mootools, and other JS libraries are for?

I haven't used Mootools that much, but I have used JQuery a fair bit. I like the design of the interface a lot. Unfortunately, I think it adds a lot of overhead, especially on mobile devices. I don't think there are *that* many cross-browser issues to warrant such a huge cost in download size and startup time. Yes, the issues are annoying, but they are really easy to get around, and then you've learned it and never have to deal with it again.

[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]

First and foremost, since JavaScript is a programming language, the same general rules apply to writing efficient code:

  • Use the best algorithm for the task. Example, don't spend hours optimizing your bubble sort procedure when a quicksort will always be faster.

  • Use the features provided by the language's standard library, because they're probably written better than anything you'll create. Example, don't write your own quicksort. The standard library sort probably already does it.

Since javascript is a dynamic language, most of the same rules apply when optimizing:

  • Function calls to JavaScript are expensive. Calls to built-in functions may or may not be.

  • Dictionary references are expensive. Example: dictionary['thing']. If you need to access the same element more than once in a loop, assign it to a local variable before the loop then reference it with the variable.

  • Consider dictionary.thing to be equivalent to dictionary['thing'] as far as performance is concerned.

  • Functions are first class objects, and being first class objects they are no different than any other element in a dictionary on your objects: This line: "myobject.function()" can be considered the equivalent of "myobject['function']()" as far as efficiency goes. You can hoist this outside the loop too:
    
    var myobject = new MyObject(whatever);
    var hoisted = myobject.function;
    
    for (var i = 0; i < 1000; ++i) {
        for (var j = 0; j < 1000; ++j) {
            hoisted(i, j);
        }
    }


  • "for (var i = 0; i < arrayLength; ++i)" is more efficient than "for (var i in array)" or even "for (var i = 0; i < array.length; ++i)" when the dictionary can be indexed sequentially.

  • Use built-in functions whenever possible, because they're often implemented in a low level language and compiled to machine code.

  • jsPerf is a great resource.

  • Don't optimize until you've profiled.

  • What is fast in Chrome might be slow in Safari, Firefox or Internet Explorer.

This is all very good advice, with the exception of "quicksort is always faster than bubblesort". That isn't necessarily true. Bubblesort is very fast on nearly sorted data and quicksort has a large constant value to its runtime that makes some algorithms like insertionsort faster than it for small sets of data. It really, really depends on the situation, which I think was your more general point, assume nothing.

Really, really, assume nothing. There is so much out there that can go wrong or can change at the last minute or looks one way but is really another. Whenever you find yourself in a situation of not understanding why something is broken, that is a big hint that you have a false assumption somewhere and need to start proving and disproving them.

[Formerly "capn_midnight". See some of my projects. Find me on twitter tumblr G+ Github.]

My general point was that the first and most important rule to writing efficient code is choosing the correct algorithm for the problem. I was generalizing in the case of quicksort vs bubble sort as you correctly assumed.

Hi everyone!

Thank you for the tips, and links they are really useful. It seems that I have to think a bit differently, than with c++ :) .

Cheers,

Pal.

shaken, not stirred

Out of curiosity, does anyone else have JS/HTML5 best practices?

Beginner in Game Development?  Read here. And read here.

 

This topic is closed to new replies.

Advertisement