CMPUT 404

Web Applications and Architecture

JavaScript

Created by
Abram Hindle (abram.hindle@ualberta.ca)
and Hazel Campbell (hazel.campbell@ualberta.ca).
Copyright 2014-2023.

Resources

Good resources for JavaScript:

History

Where did it come from?

  • Created in one day by Brendan Eich for Netscape in 1995
  • Inspired by Java, C, Self, Perl...
  • Multi-paradigm
    • Imperative
    • Functional
    • Object-oriented
    • Prototype-driven
    • Event-driven
    • Embeddable

Problems

JavaScript has problems...

Why?

If JavaScript has problems then why learn it? Why use it?

  • It runs everywhere
    • Browsers (Firefox, Chrome, Edge, Safari...)
    • Servers (nodejs)
    • PDFs
  • Fast: modern browsers compile JavaScript to machine code

Why?

If JavaScript has problems then why learn it? Why use it?

JS on Webpages

Put the JavaScript within <script> tags.

<script>
    var someJS = "JS in a <script> tag!";
</script>
<!-- you can embed oneliners within HTML! -->
<button onClick="alert('Stuck in JS factory, send help!');">
    Test me!
</button>

JS on Webpages

Or put the JavaScript at a seperate URL with <script> tags.

<script src="myscript.js"></script>
<!--You have to put the closing </script> tag because script isn't a void tag!-->

Then in the content (file) at the URL specified:

'use strict';
var someJS = "JS in a script tag!"; // js uses C-style comments

Functions

  • Functions can return values
  • Functions can have parameters
  • Functions can access all available scope (closures)
// Function one with no parameters
function one() {
    return 1;
}
// A function with 1 param
function f(x) { 
    return 2*x; 
}
// How to call the function
f(2) == 4.0;
// Show on the console each click event
// Unnamed (anonymous) function
button.addEventListener("click", function(e) {
    console.log(e);
});

Anonymous Functions

  • Often preferred...
// Function could be accidentally redefined
function one() {
    return 1;
}
// Function cannot be accidentally redefined
const two = function() { 
    return 2; 
}

Closure

  • Functions in functions can see the outer function's variables from when the function was defined
// I'm some javascript
/* also a comment */
function outer(text) {
    function inner(x) {
        alert(text);
    }
    return inner;
}
f = outer("Hi mom I'm on the projector");
f(1);
  • Functions in functions can see the outer function's variables from when the function was defined
function p(a) {
    function q() {
        console.log("a: " + a);
        console.log("arguments: " + arguments[0]);
    }
    return q;
}
r = p(1);
s = p(2); // now p is finished running, what happens to a?
r(3); // print 1
s(4); // print 2

Scope

  • By default creating a variable makes globals
function f() {
    a = "something that should be encapsulated";
}
f();
console.log(a); // oops we leaked the data<

Solution: use 'use strict';, let, const, and var.

  • let and const scopes variables/constants to the enclosing block
  • var scopes variables to the enclosing function
"use strict";
function f() {
    let a = 1;
    for (let i = 1; i < 10; i++) {
        var c = i; // var defines it inside the function
        let b = i; // let only defines it inside the for loop
    }
    console.log(c); // 9
    console.log(b); // Reference Error
}
f();
console.log(a); // Reference Error

Type Coercion

In Python the following code throws a type error:

"1" + 1

But in JavaScript you get:

"11"

this

Like self in Python, except:

  • You don't have to list in the arguments
  • It's not automatically bound to an object
function f() {
    console.log(this);
}
f();

Python

class MyClass:
    def write(self):
        print(self)
i = MyClass()
x = i.write
x()
y = MyClass.write
y()

In Python the x method is bound to the i object, and y is not.

JavaScript

class MyClass {
    write() {
        console.log(this);
    }
}
i = new MyClass();
x = i.write;
x();
// i.write doesnt work in JS

In JavaScript the x function isn't bound to anything unless we call it explicitly like i.write, x.call(i) or bind it with x.bind(i)

More Anonymous Functions

var outer = function(text) {
    console.log("in outer: " + this);
    return function(x) {
        console.log("in inner: " + this);
        alert(text);
    }
}
var f = outer.call(
    "this string is outer's this",
    "Hi mom I'm on the projector"
);
f.call(
    "this string is the this now",
    "this string does nothing"
);

Arrow Functions: Why?

This does not work!

class MyClass {
    constructor() {
        this.state = 1;
    }
    getIncrementer() {
        return function() { // this does NOT work
            this.state += 1;
        }
    }
}
var i = new MyClass();
var f = i.getIncrementer();
f();
console.log(i.state);

Arrow Functions: Why?

This does work!

class MyClass {
    constructor() {
        this.state = 1;
    }
    getIncrementer() {
        return () => { // fixed
            this.state += 1;
        }
    }
}
var i = new MyClass();
var f = i.getIncrementer();
f();
console.log(i.state);

This Example 2

What happens?

this.name = "Closured C!";
var a = {
    name: "Awesome A!",
    getName: function() {
        return this.name;
    }
};
var b = {
    name: "Beautiful B!"
};
b.getName = a.getName;
console.log(b.getName());
console.log(a.getName());

This Example 2

What happens?

this.name = "Closured C!";
var a = {
    name: "Awesome A!",
    getName: () => {
        return this.name;
    }
};
var b = {
    name: "Beautiful B!"
};
b.getName = a.getName;
console.log(b.getName());
console.log(a.getName());

Names

  • Start with a letter followed by underscores, letters or numbers.
  • Can't be a reserved word like break or case or for or function or if or in etc.
  • Convention is to use camelCase like Java not snake_case like Python.
var aString = "Strings";
var break = "not allowed!";
var BREAK = "This is allowed!";
var BrEAK = "Try not to abuse case sensitivity";

Numbers

  • Everything is a double :(
  • Write integers, decimals, or decimals with an exponent
var aNumber = 10;
var aNumber = 11.11;
var aNumber = 1e-100;
var aNumber = 1E+100;
var nan = NaN;
var inf = Infinity;
var negativeInfinity = -Infinity;

Casting Numbers

  • Getting an "integer"
Math.floor(0.7)
Math.ceil(0.7)
Math.round(0.7)
Math.trunc(0.7)
  • Getting a float
parseFloat("127")
Number("0x7F")
+"0x7F" // Unary plus is the same as Number

Rounding Errors

Since everything's a double, you get rounding errors...

function horse(b) {
    var c = b;
    return function() {
        return 1/c;
    };
}
f = horse(101);
g = horse(102);
h = horse(103);
console.log(1/f()==101);
console.log(1/g()==102);
console.log(1/h()==103);

Strings

  • Unicode by default
  • Use ' ' or " "
  • Any characters except control characters and \, " or '
var aNumber = 10;
var aString = "";
var anotherString ="Hi how are you";
var escapesString = "\r\n\t\f\b\/\\\\'\"";
var snowMan = "\u2603";
snowMan.length === 1;
aString.length === 0;

Casting Strings

  • Convert to string
"" + 1;
1 + "";
String(1); 
(1).toString();
String(null); // "null"
null.toString(); // Error
(127).toString(16); // "7F"

Booleans

  • true, false
  • Unfortunately conditional expressions have lot of truthy and falsey values
  • False values:
false
null
undefined
''
0
NaN
  • True values are true and everything else.

Equality

  • == the abstract equality operator
  • === the strict equality operator
3=="3" // true
3==="3" // false
1==true // true
1===true // false
undefined == null // true
undefined === null // false
NaN==NaN // false
NaN===NaN // false
isNaN(NaN) // true
  • In general you should always use ===

Arrays

  • Object-oriented and full of methods
  • 0-indexed
var empty = [];
var arrayInitialized = [1,2,3,4,'5'];//mixed!
var arr = new Array(10);
arr[0] === undefined;
arr[0] = 'Assigned';
'Assigned' === arr[0];
arrayInitialized[4] === '5';
arrayInitialized.length === 5;
arrayInitialized.splice(3,1); // delete 4 from the array (slow)
  • loop over arrays with for ... of
let a = [1, 2, 3, 4, 5];
for (let i of a) {
    console.log(i);
}

Objects

  • Everything is an object except booleans, numbers and strings
  • Booleans, numbers and strings still have methods
  • Objects have properties
  • Properties are named by a string
  • Property values can be anything including undefined
  • Objects don't have a class
  • Pass by reference

Objects

var empty = {};
var abram = {
    "name":"Abram Hindle",
    "job":"Throwing Down JS",
    "favorite tea":"puerh"
};
var dog = {
    paws: 4 // note I didn't quote paws
};
dog.paws === 4;
abram["favorite tea"] === "puerh";
abram.name === "Abram Hindle";

Objects

undefined.property; // Throws a type error
undefined && undefined.property // returns undefined
var empty = {};
empty.property === undefined;
var abram = {
    "name":"Abram Hindle",
    "job":"Throwing Down JS",
    "favorite tea":"puerh"
};
keys(abram); // produces ["name","job","favorite tea"]
//prototype!
var abramChild = Object.create(abram)
keys(abramChild); // produces []
abramChild.name === "Abram Hindle"; // inherits keys from abram

Prototypes

var abram = {
    "name":"Abram Hindle",
    "job":"Throwing Down JS",
    "favorite tea":"puerh",
    "sayName": function() {
        alert(this.name);
    }
};
abramChild = Object.create(abram);
abramChild.name = "Child";
function doit() {
    abram.sayName();
    abramChild.sayName();
}

Looping over Properties

  • Use the for ... in syntax
let author = {
    "name":"Unknown Slide Author",
    "job":"Making Slides",
    "sayName": function() {
        alert(this.name);
    }
};
let hazel = Object.create(author);
hazel.name = "Hazel Campbell";
for (let property in hazel) {
    alert(property + ": " + hazel[property]);
}
  • for ... in includes properties from the prototype!

Remember!

Classes

JavaScript has several ways of creating "classes"

  • ECMAScript 2015 classes
  • Constructor functions

ECMAScript 2015 Classes

  • Recommended
class Pokemon {
    constructor(name, level) {
        this.name = name;
        this.level = level;
    }
    levelUp() {
        this.level += 1;
    }
}
pikachu = new Pokemon("Pikachu", 1);
pikachu.levelUp();

ECMAScript 2022 Classes

  • Supports static methods & fields
  • Private methods & fields start with a #
class Something extends Superthing {
    static count = 0;
    constructor(param) {
        super(param); // must call before we can use this
        this.#private = Math.random();
    }
    static someMethod() {
    }
    #privateMethod() {
    }
}

Constructor Function

  • You might see this in old code
// classes start with a capital letter by convention
function Pokemon(name,level) {
    this.name = name;
    this.level = level;
    this.levelUp = function() {
        this.level += 1;
    }
}
pikachu = new Pokemon("Pikachu", 1);
pikachu.levelUp();

Constructor Function

  • You might also see the methods added to the prototype later
// classes start with a capital letter by convention
function Pokemon(name,level) {
    this.name = name;
    this.level = level;
}
// have to include "prototype" here so "this" works in the method
Pokemon.prototype.levelUp = function() {
    this.level += 1;
}
pikachu = new Pokemon("Pikachu", 1);
pikachu.levelUp();

Object.create(prototype)

  • Awkward and rarely used
// classes start with a capital letter by convention
var Pokemon = {
    name: null,
    level: null,
    levelUp: function() {
        this.level += 1;
    }
}
pikachu = Object.create(Pokemon);
pikachu.name = "Pikachu";
pikachu.level = 1;
pikachu.levelUp();

Manipulating the DOM

  • You can use JavaScript to manipulate what's on the page
  • Browser turns HTML into the DOM
  • Document Object Model
    • Document: the stuff on your page, the content
    • Object: gets turned into objects accessible by JS
    • Model: it's a tree with children nodes
  • Take the JS HTML DOM Tutorial

DOM Elements from HTML


    <p>A paragraph</p>
    <div>
      Hi!
      <a href="https://google.ca">Click me!</a>
    </div>
  

A paragraph

Hi! Click me!

Top of the DOM

  • Document (it's a tree with children nodes!)
    • Root Element: HTML ( document.children[0] )
      • Element: Head ( document.children[0].children[0] )
      • Element: Body ( document.children[0].children[1] )
        • Element: p ( document.children[0].children[1].children[0] )
          • Text: A paragrah
        • Element: div
          • Text: Hi!
          • Element: a ; attribute href
            • Text: Click me!

Recursive

function domRecurse(start, depth) {
    var out = "";
    for (child of start.childNodes) {
        indent = "    ".repeat(depth);
        out += indent + "* " + child.nodeName;
        if (child.nodeName === "#text") {
            out += " " + JSON.stringify(child.wholeText);
        }
        out += "\n";
        out += domRecurse(child, depth + 1);
    }
    return out;
}

querySelector

  • Jump straight to an element
  • Use CSS-style selectors
  • You don't need jQuery
function domRecurseExample2() {
    var start = document.querySelector("#domexample2");
    alert(domRecurse(start, 0));
}
<p id="domexample2">The paragraph we're looking for.</p>
<button type="button" onclick="domRecurseExample2()">Try it!</button>

The paragraph we're looking for.

Finding DOM Elements

  • Other than querySelector
// Get all DIVs
var divs = document.getElementsByTagName("div"); 
// gets all elements with class divider
var dividers = document.getElementsByClassName("divider"); 
// get the element with the ID main
var main = document.getElementById('main');
// get the element by name
var ups = document.getElementsByName('up');

jQuery?

jQuery's functionality is now available from APIs built-in to browsers.

  • Old projects that need backwards-compatibility or already use jQuery:
    • Using jQuery is totally cool!
  • New projects using ECMA 2016 and later:
    • Better to just use the tools the browser gives you.

Changing Document Content

Changing the DOM

<div id="fillme"></div>
function fillExample() {
    fillme = document.getElementById("fillme");
    fillme.textContent = "Here's some text in that div! ";
    a = document.createElement("a"); // create an a element
    a.textContent = "Let's make a link too!";
    a.href = "https://google.ca/";
    fillme.appendChild(a);
}

Changing Document Style

<div class="styleme">I'm text in a div!</div>
<div class="styleme">I'm text in another div!</div>
function styleExample() {
    var divs = document.getElementsByClassName("styleme");
    divs = Array.prototype.slice.call(divs); // convert HTMLCollection to Array
    divs.map((div) => {
        console.log(div);
        div.style.border = "5px solid";
        div.style.borderColor = "rgb(" + (256 * Math.random())
            + ", " + (256 * Math.random())
            + ", " + (256 * Math.random()) + ")";
    });
}
I'm text in a div!
I'm text in another div!

Changing Document Style

function styleExample2() {
    old = document.getElementById("styleme2sheet");
    if (old) {
        old.parentNode.removeChild(old);
    }
    var css = "div.styleme2 { border: 5px solid "
        + "rgb(" + (256 * Math.random())
        + ", " + (256 * Math.random())
        + ", " + (256 * Math.random()) + "); }";
    style = document.createElement('style');
    style.type = "text/css";
    style.id = "styleme2sheet";
    style.textContent = css;
    document.head.appendChild(style);
}
I'm text in a div!
I'm text in another div!

Explore The DOM

  • Right-click -> Inspect Element
  • Change DOM elements and Style!
  • Copy parts of the HTML out to the clipboard!
  • Remove annoying elements!
  • Of course, websites that use lots of divs, custom tags, or FE frameworks that create lots of divs like React make this annoying...

More Resources

License

Copyright 2014-2023 ⓒ Abram Hindle

Copyright 2019-2023 ⓒ Hazel Victoria Campbell and contributors

Creative Commons Licence
The textual components and original images of this slide deck are placed under the Creative Commons is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

Other images used under fair use and copyright their copyright holders.

License


Copyright (C) 2019-2023 Hazel Victoria Campbell
Copyright (C) 2014-2023 Abram Hindle and contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN.

01234567890123456789012345678901234567890123456789012345678901234567890123456789