IAP 2021 Day 2 - JavaScript
JavaScript is…
- … a programming language that
manipulates
the content of a web page - … how we take HTML + CSS and make it
interactive
- … used by a vast majority of websites and web apps
- … not related to Java
Where does it go?
- The browser console
- Tied to HTML files
How to JavaScript
Types
5 primitive data types:
- Boolean(true,false)
- Number(1,3.14,5e4)
- String("hello","227")
- Null
- Undefined
Operators
Like what we expected
arithmatic operators:
comporsion operators:
Defining variables
let myBoolean = true;
let myNumber = 3.14;
let myString = "yoda";
myBoolean = false;
myNumber = 227;
myString = "yuki";
When you first define a variable, you use the let
JavaScript convention is to name variables using camelCase
.
Every statement in JavaScript ends with a semicolon;
Defining constants
To define a variable which cannot be reassigned, use const
instead of let
.
const myBoolean = true;
// won't work
myBoolean = false;
let vs. const
Why bother using const
when let
exists?
Safe code practice. If something should never be changed, use const.
null vs. undefined
undefined
means "declared but not yet assigned a value"
null
means "no value"
let firstName;
// currnetly undefined
firstName = "Yuki";
// firstName has now been assigned "Yuki"
firstName = null;
// empty the variable
let vs. var
Don't use var
technical details: var
is function scoped, let
is block scoped
let
exists because people kept getting bugs when trying to use var
Output
console.log()
writes to the JavaScript console
It's handy for quick debugging
Alerts
alert()
generate a pop-up notification with the given content
alert("Nogizaka!")
Arrays
For when you want to store a sequence of (ideally similar) items:
//initialize
let pets = ["dog", "cat", "fish"];
//access
console.log(pets[0]); // "dog"
pets[0] = "bird"; // ["bird", "cat", "fish"]
Like other languages, arrays are zero-indexed.
let pets = ["dog", "cat", "fish"];
// remove from the end
pets.pop(); // ["dog", "cat"]
// add to the end
pets.push("fish"); // ["dog", "cat", "fish"]
Conditionals
if (hour < 12){
console.log("Good morning!");
}
else if (hour < 16){
console.log("Good afternoon!");
}
else if (hour < 20){
console.log("Good evening!");
}
else{
console.log("Good night!");
}
While loops
let z = 1;
while (z < 10){
z=z*2
console.log(z);
}
For loops
Useful when we want to iterate through indices
const pets = ["dog", "cat", "fish"];
for (let i =0; i < pets.length; i++){
const phrase = "I have a " + pets[i];
console.log(phrase);
}
Functions
JavaScript functions can be defined using =>
Syntax: (parameters) => {function body};
const celciusToFahrenheit = celcius => {//parentheses are optional for single parameters
return celcius * 1.8 + 32;
};
console.log(celciusToFahrenheit(0)); // 32
Callback functions
In JavaScript, functions can be passed around like any other variable.
This means we can give a "callback" function as an argument to another function.
const addTwo = x =>{
return x+2;
};
const modifyArray = (array, callback) =>{
for (let i = 0; i < array.length; i++){
array[i] = callback(array[i]);
}
};
let myArray = [5, 10, 15, 20]
modifyArray(myArray, addTwo);
// myArray is now [7, 12, 17, 22]
A common mistake
addTwo
is a function.
addTwo(x)
is the value that gets returned when you run addTwo
on x.
modifyArray
needs to be given the actual function in order to use it.
modifyArray(myArray, addTwo(x));
Anonymous functions
const modifyArray = (array, callback) =>{
for (let i = 0; i < array.length; i++){
array[i] = callback(array[i]);
}
};
modifyArray(myArray, x => {
return x+2;
});
Other built-in array functions
For arrays, we've seen push
and pop
, which edit the target array in-place.
We also have map
and filter
, which create a new array based on some instruction.(This instruction is going to be a callback function)
map(...)
Creates a new array by applying a function to each element of the original array.
let myArray = [1,2,3,4,5];
let modifiedArray = myArray.map(x => x+2); // [3,4,5,6,7]
filter(...)
Creates a new array by selecting the elements in the starting array which pass the given test.
let values = [3, -6, 2, 0, -9, 4]
let positiveValues = values.filter(x => x > 0); // [3, 2, 4]
A practical example:
let nogiNames = ["Yoda", "Yamashita", "", "Kubo"];
let validNames = nogiNames.filter(name => name !== ""); // ["Yoda", "Yamashita", "Kubo"]
Objects
A JavaScript object is a collection of name:value
pairs.
const myCar ={
make: "Tesla",
model: "Model 3",
year: 2020,
color: "red"
};
Accessing properties
There are two ways to access properties of an object:
const myCar ={
make: "Tesla",
model: "Model 3",
year: 2020,
color: "red"
};
console.log(myCar.make); // "Tesla"
console.log(myCar["make"]); // "Tesla"
Object destructing
Object destructing is a shorthand to obtain multiple properties at once.
without object destructing:
const myCar ={
make: "Tesla",
model: "Model 3",
year: 2020,
color: "red"
};
const make = myCar.make;
const model = myCar.model;
with object destructing:
const myCar ={
make: "Tesla",
model: "Model 3",
year: 2020,
color: "red"
};
const {make, model} = myCar;
Using objects
We can treat objects like any other variable.
const myCar1 ={
make: "Tesla",
model: "Model 3",
year: 2020,
color: "red"
};
const myCar2 ={
make: "Nissan",
model: "GTR"
year: 2019,
color: "blue"
};
etc.
let myCars = [myCar1, myCar2, myCar3];
let redCars = myCars.filter(car => car.color === "red");
Equality...?
We use === to check if two primitive variables are equal.
2 === 2; // true
2 === 3; // false
"2" === "2"; // true
"2" === 2; // false
But what about arrays and objects?
let arr1 = [1,2,3];
let arr2 = [1,2,3];
arr1 === arr2; // false
let obj1 = {a:1, b:2};
let obj2 = {a:1, b:2};
obj1 === obj2; // false
Object references
Object variables are actually references - they point to where the data is actually stored.
=== checks if the references are equal.
Two objects created seperately are stored seperately, so their references are not equal.
Same goes for arrays - two arrays created seperately have different references.
How to copy arrays and objects
It's not as simple as let arr2 = arr1
.
If you do so, you let the two variables point to the same array.
One way to copy arrays and objects is to use the spread(...) operator.
let arr1 = [1,2,3];
let arr2 = [...arr1]; // [1,2,3]
let obj1 = {a:1, b:2};
let obj2 = {...obj1}; // {a:1, b:2}
Why we don't use ==
==
is a loose equality operator.
It performs type coercion.
2 == 2; // true
2 == "2"; // true
So, don't use ==
unless you know what you're doing.
Classes
If you want multiple entities that are guaranteed to have shared a behavior, you can use classes.
class Rectangle{
constructor(height, width){
this.height = height;
this.width = width;
}
getarea = () => {
return this.height * this.width;
};
}
const smallRect = new Rectangle(3,4);
const bigRect = new Rectangle(15,11);
console.log(smallRect.width); // 4
console.log(bigRect.height); // 15
console.log(smallRect.getArea()); // 12
JavaScript and the DOM
DOM means Document Object Model: how your browser represents the HTML of a webpage.
What you need to add to your HTML
IDs
<div id="header">stuff</div>
script tag
<script src="script.js"></script>
Finding elements
HTML
<div id="header">stuff</div>
const headerDiv = document.getElementById("header");
Modify elements
old HTML
<p id="content">
Nogizaka46 forever!
</p>
JavaScript
const content = document.getElementById("content");
content.innerHTML = "22/7 forever and ever!";
new HTML
<p id="content">
22/7 forever and ever!
</p>
Modifying styles
JavaScript
const content = document.getElementById("content");
content.style.color = "red";
Adding elements
old HTML
<ul id="songlist">
<li>rikaisha</li>
<li>overtrue</li>
</ul>
JavaScript
const songList = document.getElementById("songlist");
const newSong = document.createElement("li");
newSong.innerHTML = "kimi wa moon";
songList.appendChild(newSong);
new HTML
<ul id="songlist">
<li>rikaisha</li>
<li>overtrue</li>
<li>kimi wa moon</li>
</ul>
Making elements interactive
Attach an event listener to an element.
Listen for click, dblclick, drag, focus, keydown...
<button id="button"> Click me! </button>
const button = document.getElementById("button");
button.addEventListener("click", () => {
alert("button clicked!");
});
Alternatively, you can use onclick
const button = document.getElementById("button");
button.onclick = () => {
alert("button clicked!");
};
Bonus: attach an event listener to window
window
represents the browser window and all of its properties,
We can listen everywhere for, say, a key being pressed down.
window.addEventListener("keydown", event => {
console.log(event.key);
});
window
exists automatically, you don't need to declare itSummary
JavaScript is how we make things happen!
- Create and add elements on the fly
- Change the content of elements
- Change the style of elements
- Give elements actions by addinfg event listeners
Comments NOTHING