Created by
Abram Hindle (abram.hindle@ualberta.ca)
and Hazel Campbell (hazel.campbell@ualberta.ca).
Copyright 2014-2019.
Good resources for JavaScript:
Where did it come from?
JavaScript has problems...
If JavaScript has problems then why learn it? Why use it>
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>
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!"; // -------------------------------------------------
// 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);
};
// 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);
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
function f() {
a = "top secret data";
}
f();
console.log(a); // oops we leaked the data
Solution: use 'use strict';, let, const, and var.
"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
In Python the following code throws a type error:
"1" + 1
But in JavaScript you get:
"11"
Like self in Python, except:
function f() {
console.log(this);
}
f();
class Quiz:
def write(self):
print(self)
quiz = Quiz()
w = quiz.write
w()
In Python the w method is bound to the quiz object
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)
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);
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
var aString = "Strings";
var break = "not allowed!";
var BREAK = "This is allowed!";
var BrEAK = "Try not to abuse case sensitivity";
var aNumber = 10;
var aNumber = 11.11;
var aNumber = 1e-100;
var aNumber = 1E+100;
var nan = NaN;
var inf = Infinity;
var negativeInfinity = -Infinity;
Math.floor(0.7)
Math.ceil(0.7)
Math.round(0.7)
Math.trunc(0.7)
parseFloat("127")
Number("0x7F")
+"0x7F" // Unary plus is the same as Number
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);
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;
"" + 1;
1 + "";
String(1);
(1).toString();
String(null); // "null"
null.toString(); // Error
(127).toString(16); // "7F"
false
null
undefined
''
0
NaN
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
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)
let a = [1, 2, 3, 4, 5];
for (let i of a) {
console.log(i);
}
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";
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
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();
}
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]);
}
JavaScript has several ways of creating "classes"
class Pokemon {
constructor(name, level) {
this.name = name;
this.level = level;
}
levelUp() {
this.level += 1;
}
}
pikachu = new Pokemon("Pikachu", 1);
pikachu.levelUp();
// 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();
// 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();
// 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();
<p>A paragraph</p>
<div>
Hi!
<a href="https://google.ca">Click me!</a>
</div>
A paragraph
Hi! Click me!
function domRecurseExample() {
var start = document.querySelector("#domexample");
alert(domRecurse(start, 0));
}
<blockquote id="domexample">
...
</blockquote>
<button type="button" onclick="domRecurseExample()">Try it!</button>
// 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's functionality is now available from APIs built-in to browsers.
Changing the DOM
<div id="fillme"></div>
<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!
I'm text in a div!I'm text in another div!
Copyright 2014 ⓒ Abram Hindle
Copyright 2019 ⓒ Hazel Victoria Campbell and contributors
Other images used under fair use and copyright their copyright holders.
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