CMPUT 404

Web Applications and Architecture

Part 07: JavaScript

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

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

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!"; // -------------------------------------------------

Functions

  • Functions can return values
  • Functions can have parameters
  • Functions can access all available scope
// 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 function
button.onclick = function(e) {
    console.log(e);
};

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 = "top secret data";
}
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 Quiz:
  def write(self):
    print(self)
    
    
quiz = Quiz()
w = quiz.write
w()

In Python the w method is bound to the quiz object

JavaScript

class Quiz {
  write() {
    console.log(this);
  }
}
quiz = new Quiz();
w = quiz.write
w()

In JavaScript the w method isn't bound to the quiz object unless we call it explicitly like quiz.write, w.call(quiz) or bind it with w.bind(quiz)

Anonymous Functions

var outer = function(text) {
    return function(x) {
        console.log(this);
        alert(text);
    }
}
var f = outer("Hi mom I'm on the projector");
f.call({}, 1);

Arrow Functions

Like anonymous functions but they always keep the this from when they were created.

var outer = function(text) {
    return (x) => {
        console.log(this);
        alert(text);
    }
}
var f = outer("Hi mom I'm on the projector");
f.call({}, 1); // {} is ignored because it's an arrow function

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
  • Boolens, 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";
abram["favorite tea"] = "oolong";

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!

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();
        

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
  • 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


          
        

querySelector

  • Jump straight to an element
  • Use CSS-style selectors
  • You don't need jQuery

          function domRecurseExample() {
            var start = document.querySelector("#domexample");
            alert(domRecurse(start, 0));
          }
        

          <blockquote id="domexample">
            ...
          </blockquote>
          <button type="button" onclick="domRecurseExample()">Try it!</button>
        

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>
        

          
        

Changing Document Style


          <div class="styleme">I'm text in a div!</div>
          <div class="styleme">I'm text in another div!</div>
        

          
        
I'm text in a div!
I'm text in another div!

Changing Document Style


          
        
I'm text in a div!
I'm text in another div!

Explore The DOM

  • Right-click -> Inspect Element
  • Experiment with a page like https://metafilter.com/
  • Change DOM elements and Style!
  • Copy parts of the HTML out to the clipboard!
  • Remove annoying elements!

More Resources

License

Copyright 2014 ⓒ Abram Hindle

Copyright 2019 ⓒ 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

The source code to this slide deck is:

          Copyright (C) 2018 Hakim El Hattab, http://hakim.se, and reveal.js contributors
          Copyright (C) 2019 Hazel Victoria Campbell, 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