Intro to JavaScript

Data Types, Variables, Functions, Comparisons, Conditionals, DOM, Browser Support & jQuery

Reading Recap

Jeffrey Zeldman JavaScript: The World's Most Misunderstood Programming Language - Douglas Crockford

Main points:
Misconceptions about the name and it's origin. Idiosyncrasies. Bad history. Misunderstandings about how to use it.

http://javascript.crockford.com/javascript.html

Reading Recap

Jeffrey Zeldman Douglas Crockford: The JavaScript Programming Language - Douglas Crockford

Main points:
Mostly syntax and a little history.

http://www.youtube.com/watch?v=v2ifWcnQs6M&feature=related

Responses Q&A

Common questions:

  • What are some recommended books?
  • What is the origin of JavaScript?
  • Anything else?

What are some recommended books?

What is the origin of JavaScript?

  • Developed by Brendan Eich at Netscape
  • First shipped in Netscape Navigator 2.0 in 1995
  • Microsoft reverse-engineers it and calls it JScript in 1996 to avoid trademark issues
  • Later in 1996, Netscape tried to find a standards body to solidify it as an industry standard, and finds ECMA (European Computer Manufacturers Association)
  • Unfortunately, Microsoft was on the board and forces the standard to be called ECMAStript
  • Source: http://en.wikipedia.org/wiki/JavaScript

Data Types

  • String - "Hello World"
  • Number - 100
  • Boolean (true/false)
  • Object - { name: "Dennis" }
  • Array - ['apples', 'oranges', 'bananas']
  • Null
  • Undefined

Data Types - Strings

  • A "string" of characters
  • Surrounded by single or double quotes
  • Internal quotes of the same type need to be escaped
  • var myString = 'Pretty cool string isn\'t it?';
    
    // versus...
    
    var myString = "Pretty cool string isn't it?";
    
  • Further reading: PPK on Strings

Data Types - Objects

  • Associative arrays (names + values)
  • Uses curly braces
  • var myShinyNewObject = {
      color: 'red',
      price: 199.99,
      availability: ['US', 'Japan', 'Australia']
    }
    
  • Values accessed by "[]" or "." notation
  • myShinyNewObject.color; // 'red'
    myShinyNewObject[price]; // 199.99
    
  • Further reading: PPK on Objects

Data Types - Arrays

  • Indexed array (no names, just values)
  • Uses square brackets
  • var myArray = ['omg', 'this', 'array', 'is', 'sweet'];
    
  • Values can be anything
  • var one = 1;
    var myArray = [
      one,
      function () {alert('hey');},
      ['another', 'array'],
      'or maybe an object',
      {awesome: true}
    ];
    

Variables

  • Variables store values
  • var name = "Dennis";
    
  • The default value of a variable with no value is "undefined"
  • var name;
    

Functions

  • Stores sets of instructions
  • function sayHello() {
      var name = "Dennis";
      alert('hello ' + name);
    }
  • Can be assigned to variables
  • var sayHi = sayHello;
    sayHi(); // 'hello Dennis'
    

Conditionals

  • if / elseif / else
  • if (thisThing === someValue) {
      doSomething();
    } elseif (thisThing === someOtherValue) {
      soSomethingElse();
    } else {
      doDefaultThing();
    }
    

Conditionals

  • Switches - Used for handling conditionals with many possible values
  • switch (checkOutThisValue) {
      case '1': 
        doTheFirstThing();
       break;
      case '2':
        doTheSecondThing();
        break;
      case '4':
        doTheSecondThing();
        break;
      case '...':
        doThe...Thing();
        break;
      default: 
        doDefaultThing();
        break;
    }
    

Comparison & Logic

  • ==, ===, !=, >, <, >=, <=
  • example:
  • if (age < 18) document.write("Too young");
    
  • == vs. ===
  • == is a value check (equality)
  • === is a value AND type check (strict equal)
  • ALWAYS use ===
  • Also: ||, && (or, and comparisons)

Loops

  • for
  • for (var i = 0; i < 100; i++) {
      doSomethingWith(i);
    }
    
  • for in
  • var person = {name: 'Dennis'};
    for (x in person) {
      alert('person\'s name: ' + person[x]);
    	// same as calling person[name] or person.name
    }
    
  • while - may not ever run once if condition is initially false
  • while (i <= 5) {
      doSomethingWith(i);
    }
    
  • each

Document Object Model (DOM)

  • "An application programming interface (API) for HTML" - W3C
  • It's basically the object version you get after the browser has parsed your HTML file.
  • It can be accessed by JavaScript in a bunch of ways
  • <h1 id="myHeader">Hello Class</h1>
    document.getElementById('myHeader');
    
  • Source: http://www.w3.org/TR/DOM-Level-2-Core/introduction.html
document object model

Browser Support

  • Browsers do not all implement the same methods the same way (i.e., it's crappy)
  • and it's unfortunately complicated...
  • Examples include: Ajax (XHR) implementation, the event model (bubbling & capture), a myriad of various events (e.g., mouseenter, mouseleave)
  • PPK: Event compatibility tables
  • Fortunately we have a little help from our friends at Mozilla...

jQuery

Selectors

  • Wrapped Sets
  • $('div'); // Gets all div elements
    
  • CSS3 Selector Engine (a.k.a. Sizzle)
  • $('div:nth-child(n)'); // Gets every nth div element
    
  • More on CSS3 selectors: http://www.w3.org/TR/selectors/

Convenience Methods

  • $.hide() / $.show()
  • $.fadeIn() / $.fadeOut()
  • window.onload = function () {
      alert('page is loaded');
    }
    
    // boils down to this...
    
    $(function () {
      alert('DOM is loaded');
    });
    

Chaining

    $('#h1')
      .animate({'top': '10px'])
      .fadeOut()
      .remove();
    

Download it

  • http://jquery.com/
  • or
  • include it on your site from a CDN
  • <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script<
    

Questions

?

Assignment

Prepare for next week's presentation