A Simple, Comprehensive Overview of Javascript

Get the Math, Better Explained eBook and turn Huh? to Aha!

This isn’t a reference guide, programming tutorial or detailed overview. It’s a Javascript refresher, assuming you know another programming language and puts all the information in one place (just ctrl+f to find!). Javascript has nothing to do with Java, is dynamically typed and has C-like syntax.

Enabling Javascript

Include javascript inside HTML:

<script>
  x = 3;
</script>

Reference external file:

<script src="http://example.com/script.js"></script>

Redirect if javascript disabled:

<noscript><meta http-equiv="refresh" content="0; URL=http://example.com/noscript.html"/></noscript>

Using Variables, Objects and Arrays

Deep dive into objects.

var str = "Hello";                // local variable, when inside a function
str2 = "Hello World";             // global variable in default context (window.str2)
str3 = 'My quote char: " ';       // single or double quote
str4 = "My really really really \
really long string broken into \
multiple lines";

str = 19;                         // change to int
str = 0xfe + 2.343 + 2.5e3;       // hex, floats, exp

var newObject = new Object();     // constructor
newObject = {};           // shorthand for same
newObject.name = "bob"            // dynamic attributes
newObject.name = null         // it's there (null item)
delete newObject.name         // it's gone (undefined)
newObject["real age"] = 33;       // array notation/hash table

var obj = {           // create object using JSON
    name: "Bob",          //   aka Javascript Object Notation
    details: {
        age: 33,
        "favorite color": "green"
    }
}
obj.name
obj.details["favorite color"]

var newArray = [];                // no size
newArray[3] = "hi";               // grows dynamically
newArray[2] = 13;                 // any type
newArray.push(newObject);         // add new item
newArray.pop();               // remove it

Comparisons and Manipulations

Javascript has some funky types and comparisons.

/* javascript types */
typeof("string") == "string"
typeof(3) == typeof(3.4) == typeof(0x34) == "number"
typeof(myObject) == typeof(myArray) == "object" // arrays are objects
typeof(true) == typeof(1 == 2) == "boolean"
typeof(Math.sin) == "function"
typeof(notthere) == "undefined"

/* comparisons */
123 == "123"                     // true => converts type
123 === "123"                    // false => checks type
typeof(x) == "undefined"     // x isn't there
x == null            // x is defined, but null

/* Numbers */
parseInt("123")          // base 10 => 123
parseInt("123", 16);         // base 16 => 291
parseFloat("123.43");        // 123.43

isNaN(0/0) == true       // illegal number
3/0 == Infinity          // legal...
-3/0 == -Infinity        //
isFinite(3/0) == false       // ... but not finite

/* regular expression (regex) string comparisons */
matches = "hello".match(/h../)   // returns array ["hel"] or null

re = new RegExp("h..", "ig");    // construct regexp -- no slashes
matches = "hello".match(re);     // use it

"hello".replace(/h/,"b")     // => "bello"

Conditionals and Loops

if (str == "Hello"){    // if-else
  alert("Hi");      // popup dialog
}
else{
  alert("something is wrong!");
}

a = 3, b = 4;       // multi-assigment
c = a > b ? a : b;  // c gets bigger item (b)

switch (name){      // switch statement
  case "Bob":
    alert("Hi Bob!")
    break
  case "Joe":
    alert("Hey Joe.")
    break
  default: alert("Do I know you?")
}

while (i < n){          // the basics
 // do something
 i++;
}

for (var i=0; i<n; i++){
  // do something else
}

for (var key in obj){
  // do something with obj[key]
}

Defining Functions

function foo(a,b){          // global function
  return a + b;
}

var fn = function(a,b){     // save function as variable...
  return foo(a,b);
}

obj.fn = function(a,b){     // ...or as part of object
  return a + b;
}

function bar(a,b){
    var n = 1;                  // local var

    function helper(x) {            // inner function...
        return 1/Math.sqrt(x + n);  // .. can use local vars
    }
    return helper(input);           // avoid need for global function
}

foo(1,2) == fn(1,2) == 3;   // true

Javascript Classes

Javascript doesn’t have formal class notation, but you can create a “constructor” and add methods to it. Examples from here.

function Person(first, last) { // create "constructor"
    this.first = first;        // public variables -- reference current object
    this.last = last;

    var privateFn = function(first, last){  // private function
    // ...
    }

    this.setName = function(first, last){ // public function
        this.first = first;
    this.last = last;
    }

}

Person.prototype.fullName = function() { // extend prototype
    return this.first + ' ' + this.last; //   even at runtime!
}

var bob = new Person("Bob", "Smith"); // "new" creates an object
bob.fullName();               // => "Bob Smith"

Advanced Javascript

function foo(a,b){        // will raise exception
  var c = a + b;
  throw "Error Message"; // your message here
}

try{                     // try dangerous code
   foo(1,2);
}
catch(e){           // catch exception
   alert(e.name + e.message);   // show details
}

eval("x = 3");       // execute arbitrary code

timer = setTimeout("myfunction()", 1000)  // execute in 1 second (1000ms)
clearTimeout(timer);              // cancel event

Browser Document Object Model (DOM), and GUI

Find and change HTML elements.

alert("message");  // messagebox with "OK"
var choice = confirm("message");  // OK/CANCEL true or false
var input = prompt("message", "default value"); // enter a value; null if cancelled

x = document.getElementById("foo");    // finds <div id="foo"></div>

x.style.background = "#333";           // set CSS style
x.style.borderLeft = "1px solid #ccc"; // border-left => borderLeft (camelCase)

x.className = "myclass";           // set CSS class
x.innerHTML = "Hello";             // set html inside div

y = document.getElementById("myinput"); // input area/textarea
y.value = "Hi";                 // get or set text

Keep learning

I made this page as a list of important examples; read the advanced guides if any section is confusing. A later post will cover the helper functions I use in my applications. Good luck.

Other Posts In This Series

  1. Starting Ruby on Rails: What I Wish I Knew
  2. Intermediate Rails: Understanding Models, Views and Controllers
  3. A Simple, Comprehensive Overview of Javascript
  4. Using JSON to Exchange Data
  5. How To Make a Bookmarklet For Your Web Application
Better Explained is dedicated to helping you grasp concepts, and serves over 250k readers each month.

Enjoy this article? Try the site guide or join the newsletter:

15 Comments

  1. var obj = { // create object using JSON
    name: “Bob”, // aka Javascript Object Notation
    details: {
    age: 33,
    “favorite color”: “green”
    }
    }
    obj.name
    obj.details[“favorite color”]

    i’ve a question… how can I print all obj property without know them
    exist something like reflection???
    I’m looking for a function like (php) print_r(obj)

  2. In line 4 of your sample for the section “Comparisons and Manipulations,” it seems to me that you’re missing a ‘=’.

  3. These lines are not quite correct:

    var str = “Hello”; // local variable
    str2 = “Hello World”; /* global */

    While “var” is the correct way to define a variable in the local scope, in this case both “str” and “str2″ will become properties of the “window” object, which is essentially JavaScript’s global scope. A function is the only way to create a new local scope in JS, so “var” is only useful inside functions (and all JS code should be inside a function to prevent polluting the global scope).

  4. the redirect when JavaScript is disabled sounds like a pretty good idea, however I’ve heard before that meta redirects are viewed negatively by Google and other search engines. If you’re using PHP maybe you could do a redirect with that inside the noscript tag. (or whichever server side programming language you prefer.)
    Nice to see such an article recently posted somewhere and up voted 6 years after it was originally published…

  5. When describing constructor functions you use self without defining it. Its probably better to just use this.

  6. In you “Javascript Classes” section, “self.setName” should be “this.setName”. Otherwise, a nice summary!

  7. @devurls: Interesting point, not sure about the SEO impact. Yep, I like that this is still handy for people!

    @Michael, Adam: Thanks, great feedback. Just changed.

Your feedback is welcome -- leave a reply!

Your email address will not be published.

LaTeX: $$e=mc^2$$