Created by
Abram Hindle
(abram.hindle@ualberta.ca)
and Hazel Campbell (hazel.campbell@ualberta.ca).
Copyright 2014-2023.
Good resources for JavaScript:
Where did it come from?
JavaScript has problems...
If JavaScript has problems then why learn it? Why use it?
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!"; // js uses C-style comments
// 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);
});
// Function could be accidentally redefined
function one() {
return 1;
}
// Function cannot be accidentally redefined
const two = function() {
return 2;
}
// 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 = "something that should be encapsulated";
}
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 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.
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)
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"
);
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);
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);
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());
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());
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";
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();
static
methods & fields#
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() {
}
}
// 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 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;
}
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.
// 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>
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);
}
<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!
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!
Copyright 2014-2023 ⓒ Abram Hindle
Copyright 2019-2023 ⓒ Hazel Victoria Campbell and contributors
Other images used under fair use and copyright their copyright holders.
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