JavaScript Basics

From Code Self Study Wiki
Jump to: navigation, search

Here are some JavaScript notes.

Code Conventions[edit]

Identifiers[edit]

Identifiers are the names of variables, functions, properties, and function arguments.

  • must begin with a letter, $, or _
  • best practice: use camelCase

Strict Mode[edit]

"use strict";

You can put it at the top of the script or just in a function to limit it just to that function.

Variables[edit]

  • var is local.
  • Undeclared variables are global.
  • The five primitive data types (string, null, undefined, number, boolean) are by value. You can copy them and keep them separate.
  • All objects are by reference. You can add/delete properties and methods any time. If you copy it, you're still modifying the original object.
  • Function arguments are always passed by value, but variables inside the function are still accessing the object by reference. (?)

Garbage Collection[edit]

Local variables are dereferenced when their execution context ends. When you are finished with a global variable or object, you can dereference it by assigning null to it. It will then be cleaned up the next time garbage collection runs.

Data Types[edit]

There are six data types:

  • undefined
  • boolean
  • string
  • number
  • object
  • function

typeof[edit]

Find the type. Watch out for weird things like: null will return "object".

x = "Hello";
typeof x; // no parentheses needed because it's an operator, but you can use parentheses if you want

instanceof[edit]

object instanceof constructor

Example:[1]

function C(){} // defining a constructor
function D(){} // defining another constructor
 
var o = new C();
o instanceof C; // true, because: Object.getPrototypeOf(o) === C.prototype
o instanceof D; // false, because D.prototype is nowhere in o's prototype chain
o instanceof Object; // true, because:
C.prototype instanceof Object // true
 
C.prototype = {};
var o2 = new C();
o2 instanceof C; // true
o instanceof C; // false, because C.prototype is nowhere in o's prototype chain anymore
 
D.prototype = new C(); // use inheritance
var o3 = new D();
o3 instanceof D; // true
o3 instanceof C; // true

Arrays[edit]

See: JavaScript Arrays.

Objects[edit]

See: JavaScript Objects.

Operators[edit]

Logical NOT, AND, OR. Test them out in the console, because they aren't always intuitive.

Equality[edit]

  • = -- assignment
  • == -- converts and then compares, so "10" == 10 is true.
  • === -- compares exact types, so "10" === 10 is false.

Statements[edit]

if Statement[edit]

if (i > 100) {
    // do something
} elseif (i < 0) {
    // do something else
} else {
    // do another thing
}

do-while Statement[edit]

  • executes at least once
var i = 0;
do {
    i += 1;
} while (i < 25);

while Statement[edit]

  • doesn't execute the loop if condition is not met
var i = 0;
while (i < 100) {
    // do something
}

for Statement[edit]

var counter = 50;
for (var i = 0; i < counter; i++) {
    // do something
}

for-in Statement[edit]

Enumerate properties of objects.

Labeled Statements[edit]

break and continue Statements[edit]

break breaks out of a loop immediately. continue runs the loop one more time.

with Statement[edit]

Loop over an object. Forbidden in strict mode.

with(student) {
    var name = name; // student.name
    var bday = birthday; // student.birthday
    var major = major; // student.major
}

switch Statement[edit]

switch(x) {
    case 100:
        // do something
        break; // break is optional -- you can have it continue
    case 50:
        // do something else
        break;
    default:
        // otherwise do this
}

Functions[edit]

  • Functions don't need to return a value. You can use return; to return undefined.
  • The execution of the function stops when it reaches a return statement.
  • You can pass any number of arguments to a function.
  • Arguments are passed into the function as an array.
  • Access arguments with arguments[1], arguments[2], arguments.length, etc.

Regular Expressions[edit]

var text = "This is some text"
 
text.match(/[aeiou]/g); // ["i", "i", "o", "e", "e"]
 
text.search(/s/); // index of the item: 3
 
text.replace(/is/, 'was'); // "Thwas is some text"
 
text.replace(/is/g, 'was'); // "Thwas was some text"
 
text.split(/\s/g); // ["This", "is", "some", "text"]

Match an HTML element:

content.match(/<img[^<>]*>/g);

Timers[edit]

setTimeout()[edit]

// wait 5 seconds, then run myFunction once
setTimer(myFunction, 5000);

See also clearTimeout().

setInterval()[edit]

// run myFunction every 5 seconds
setInterval(myFunction, 5000);

XHR / AJAX[edit]

Basic steps:

  1. Create a new XHLHttpRequest() object
  2. xhr.open("GET", "URL", async); // async = true
  3. xhr.onload = function () {};
  4. xhr.send();
var parseJSON = function (someJSON) {
    parsedJSON = JSON.parse(someJSON);
 
    return parsedJSON["a"]["b"]["c"];
};
 
var setup = function () {
    var xhr = new XMLHttpRequest();
 
    xhr.open("GET", "/something/some.json", true); // async = true
 
    xhr.onload = function () {
        var res = JSON.parse(this.responseText);
        return res;
    };
 
    xhr.send();
};

Binary Data[edit]

For binary data like audio files, set the responseType to "arraybuffer":

xhr.responseType = "arraybuffer";

Example Functions[edit]

function xhrGet(reqUri, callback, type) {
    var xhr = new XMLHttpRequest();
 
    if (type) {
        xhr.responseType = type; // E.g., "arraybuffer" for binary data
    }
    xhr.open("GET", reqUri, true); // async = true
    xhr.onload = callback();
}
 
parseJSON = function (xhr) {
    var parsedJSON = JSON.parse(xhr.responseText);
    var targetItem = parsedJSON["a"]["b"]["c"];
 
    return targetItem;
}
 
playSound = function (xhr) {
    try {
        var context = new webkitAudioContext();
 
        var mainNode = context.createGainNode(0);
        mainNode.connect(context.destination);
 
        var clip = context.createBufferSource();
 
        context.decodeAudioData(xhr.response, function (buffer) {
            clip.buffer = buffer;
            clip.gain.value = 1.0;
            clip.connect(mainNode);
            clip.loop = true;
            clip.noteOn(0);
        }, function (data) {});
    }
    catch(e) {
        console.warn("Web Audio API isn't supported in this browser.");
    }
};
 
// Usage
xhrGet("/api/some.json", parseJSON); // Doesn't include type
xhrGet("/media/sound.ogg", playSound, "arraybuffer"); // Includes type

Promises[edit]

/* jshint esversion: 6 */
document.addEventListener('DOMContentLoaded', () => {
    function get(url) {
        return new Promise((resolve, reject) => {
            let req = new XMLHttpRequest();
            req.open('GET', url);
 
            req.onload = () => {
                if (req.status == 200) {
                    resolve(req.response);
                }
                else {
                    reject(Error(req.statusText));
                }
            };
 
            req.onerror = () => {
                reject(Error("Network Error"));
            };
 
            req.send();
        });
    }
 
    function renderView(data) {
        let hobbitArea = document.getElementById('hobbits');
        hobbitArea.innerHTML = data;
    }
 
    const hobbits = get('/api/hobbits').then((response) => {
        renderView(response);
    }, (error) => {
        console.error("Failed!", error);
    });
 
});

History[edit]

  • history.back()
  • history.forward()
  • history.go(-2) -- this example goes back two pages in the history

Watch out for iframes.

There are libraries to manage history in pre-HTML5 browsers like Really Simple History.

HTML5 has a different way to manage history (later chapter).

Closures[edit]

DOM Scripting[edit]

See also DOM Enlightenment.

  • getElementById
  • getElementsByName
  • getElementsByTagName
  • getElementsByClassName

and:

  • parentNode
  • childNodes
  • firstChild, lastChild
  • nextSibling, previousSibling
  • nodeType
  • nodeValue
  • nodeName

and:

  • firstElementChild, lastElementChild
  • nextElementSibling, previousElementSibling
  • childElementCount

Data[edit]

HTML5 can have data-x attributes. "X" can be anything, but should be lowercase. You can then access the data with something like data.x. If you use multiple words like data-some-example, then access it with camelCase: data.someExample.

References[edit]

  1. https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/instanceof