Professional Documents
Culture Documents
JavaScript PDF
JavaScript PDF
pwd
// Add
let addResult = age + 1 // 27
// Subtract
let subtractResult = age - 26.5 // -0.5
// Multiply
let multiplyResult = age * 10 // 260
// Divide
let divideResult = age / 2 // 13
// Parenthesis can be used to make sure one operation happens before another
let result = (age + 3) * 7 // 203
//
let age = 26
let isChild = age <= 7
let isSenior = age >= 65
if (isChild) {
console.log('Welcome! You are free.')
} else if (isSenior) {
console.log('Welcome! You get a discount.')
} else {
console.log('Welcome!')
}
let isAccountActive = false
$$
||
let isGuestOneVegan = true
let isGuestTwoVegan = true
if (2 > 0) {
console.log(name)
console.log(age)
let location = 'Philadelphia'
}
}
getName()
console.log(age)
if (1 < 2) {
console.log(name)
let height = 72
getName()
}
score
score score
`Score: ${score}` 2 5
let score = 5
let getNewScoreMessage = function () {
let score = 2
return `Score: ${score}`
}
console.log(score)
}
getNewScoreMessage()
console.log(score) // Prints 3
if (1 < 2) {
score = 3
}
console.log(score)
}
getNewScoreMessage()
console.log(score) // Will throw an error as score wasn't leaked to the
global scope
let fahrenheitToCelsius = function (fahrenheit) {
const celsius = (fahrenheit - 32) * (5 / 9)
return celsius
}
undefined
let name
console.log(name) // Will print undefined
undefined
let double = function (x) {
if (x === undefined) {
console.log('Please provide x') // This will print
} else {
console.log(x)
}
}
double()
name = null
console.log(add(2, 4))
// Unable to access a, b, or result. They are not in scope in the global
scope.
bio
altBio
let otherBook = {
title: 'A Peoples History',
author: 'Howard Zinn',
pageCount: 723
}
getSummary(myBook)
addExpense(myAccount, 2000)
console.log(myAccount)
myAccount
account
// Both logs print differen things
let myAccount = {
name: 'Andrew Mead',
expenses: 0,
income: 0
}
addExpense(myAccount, 2000)
console.log(myAccount)
checkAvailability
checkAvailability
let restaurant = {
name: 'ASB',
guestCapacity: 75,
guestCount: 0,
checkAvailability: function (partySize) {
let seatsLeft = this.guestCapacity - this.guestCount
return partySize <= seatsLeft
}
}
console.log(restaurant.checkAvailability(4))
this this
checkAvailability this.guestCapacity
this.guestCount
let name = ' Andrew Mead '
// Length property
console.log(name.length)
// Includes method
console.log(password.includes('password'))
Math
let num = 103.941
// Round numbers
console.log(Math.round(num))
console.log(Math.floor(num))
console.log(Math.ceil(num))
let
const
const
isRaining
isRaining = false
console.log(isRaining)
const
let
var const let
let var
var
var
const let
if (true) {
var name = 'Andrew'
let age = 26
}
var
const setupVariables = () => {
var name = 'Andrew'
let age = 26
}
setupVariables()
console.log(name) // Will print: ReferenceError
console.log(age) // Will print: ReferenceError
var
let
const
var
age = 6
console.log(age) // Will print: 6
var age
6
var age
age = 6
console.log(age) // Will print: 6
// Empty array
const emptyArray = []
// Array of numbers
const expenses = [100.10, 45, -20]
0
0 2
// Get the last item using bracket notation and the length property
console.log(names[names.length - 1])
nums.push(12)
nums.unshift(3)
splice splice
// Add a new item at the second position without deleting any existing items
nums.splice(1, 0, 399)
nums.pop()
nums.pop()
nums.shift()
splice
1
const nums = [99, 199, 299]
splice
forEach
forEach
forEach
const todos = ['Order cat food', 'Clean kitchen', 'Buy food', 'Do work',
'Exercise']
forEach
0 1
2
for (let count = 0; count < 3 && count < players.length; count++) {
const num = count + 1
const player = players[count]
console.log(`${num}. ${player}`)
}
indexOf
-1
indexOf ===
'Test' === 'Test' true {} === {} false
findIndex
findIndex
title text
title true
const notes = [{
title: 'My next trip',
body: 'I would like to go to Spain'
}, {
title: 'Habbits to work on',
body: 'Exercise. Eating a bit better.'
}, {
title: 'Office modification',
body: 'Get a new seat'
}]
filter
filter
true
false
filter
getThingsToDo
todos
const todos = [{
text: 'Order cat food',
completed: false
}, {
text: 'Clean kitchen',
completed: true
}, {
text: 'Do work',
completed: false
}]
sort
text
completed
sort sort
a b
a -1 b 1
0
const todos = [{
text: 'Buy food',
completed: true
}, {
text: 'Do work',
completed: false
}, {
text: 'Exercise',
completed: true
}]
sortTodos(todos)
console.log(todos)
npm install -g live-server
live-server folder-to-server
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>My App</h1>
<p>This application was created by Andrew Mead</p>
</body>
</html>
<script>
console.log('A message from JavaScript!')
</script>
<script src="my-script.js"></script>
document
querySelector
querySelector
querySelectorAll
remove
h1
const element = document.querySelector('h1')
element.remove()
createElement appendChild
createElement
appendChild
const newParagraph = document.createElement('p')
newParagraph.textContent = 'This is a new element from JavaScript'
document.querySelector('body').appendChild(newParagraph)
addEventListener
id
querySelector querySelectorAll
type
text type
placeholder
addEventListener
value
name
submit
e.preventDefault()
<label>
<input id="delivery" type="checkbox"> Check for delivery
</label>
change
checked checked true
false
option
value
<select id="filter-by">
<option value="byEdited">Sort by last edited</option>
<option value="byCreated">Sort by recently created</option>
<option value="alphabetical">Sort alphabetically</option>
</select>
value
setItem
"Andrew"
"username"
localStorage.setItem('username', 'Andrew)
getItem
getItem
removeItem
'username'
localStorage.removeItem('username')
clear
localStorage.clear()
<script src="notes-functions.js"></script>
<script src="notes-app.js"></script>
console.log
debugger console.log
debugger
createElement appendChild
const root = document.createElement('div')
const text = document.createElement('span')
const button = document.createElement('button')
document.body.appendChild(root)
<script src="http://wzrd.in/standalone/uuid%2Fv4@latest"></script>
<script src="notes-functions.js"></script>
<script src="notes-app.js"></script>
uuidv4
const id = uuidv4()
console.log(id) // Will print the new random id
<a href="/page.html">Go to my page</a>
location.assign
location.assign(`/page.html`)
location.hash
substring
const id = location.hash.substring(1)
addEventListener
window.addEventListener('storage', function (e) {
// Will fire for localStorage changes that come from a different page
})
Date
getHours getMinutes
getSeconds
const date = new Date('March 1 2017 12:00:00')
const timestamp = date.getTime()
console.log(timestamp) // Will print 1488387600000
format
filter
squareLong
this
const pet = {
name: 'Hal',
getGreeting: () => {
return `Hello ${this.name}!`
}
}
console.log(pet.getGreeting())
const pet = {
name: 'Hal',
getGreeting() {
return `Hello ${this.name}!`
}
}
console.log(pet.getGreeting())
arguments arguments
add
const add = () => {
return arguments[0] + arguments[1]
}
add
showPage
showErrorPage
const age = 21
47 ''
true
false
const value = 'Andrew'
if (value) {
// This will run
} else {
// This won't run
}
if (value) {
// This won't run
} else {
// This will run
}
typeof
// Typeof examples
false 12
false 0 true
1 false + 12 12 true + 12 13
throw
getTip
getTip
const getTip = (amount) => {
if (typeof amount !== 'number') {
throw Error('Argument must be a number')
}
try {
const result = getTip('12')
console.log(result) // This won't print
} catch (e) {
console.log('Error!') // This will print
}
JSON.parse
'use strict'
data
const processData = () => {
data = '1230987234'
}
processData()
console.log(data) // Will print '1230987234'
'use strict'
Person new
new
this
getBio Person.prototype Person.prototype
Person
getBio
this
const Person = function (firstName, lastName, age, likes = []) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.likes = likes
}
Person.prototype.getBio = function () {
let bio = `${this.firstName} is ${this.age}.`
this.likes.forEach((like) => {
bio += ` ${this.firstName} likes ${like}.`
})
return bio
}
prototype
prototype
new
firstName getBio
[[Prototype]]
me.[[Prototype]] = Person.prototype
[[Prototype]]
firstName getBio
Person firstName getBio
filter toLowerCase
hasOwnProperty
// myObject --> Object.prototype --> null
const myObject = {}
myObject
null
undefined
hasOwnProperty
new
toLowerCase
Object.prototype
constructor
prototype
,
class Person {
constructor(firstName, lastName, age, likes = []) {
this.firstName = firstName
this.lastName = lastName
this.age = age
this.likes = likes
}
getBio() {
let bio = `${this.firstName} is ${this.age}.`
this.likes.forEach((like) => {
bio += ` ${this.firstName} likes ${like}.`
})
return bio
}
}
Person Student
class Student extends Person {
constructor(firstName, lastName, age, grade, likes) {
super(firstName, lastName, age, likes)
this.grade = grade
}
updateGrade(change) {
this.grade += change
}
getBio() {
const status = this.grade >= 70 ? 'passing' : 'failing'
return `${this.firstName} is ${status} the class.`
}
}
extends extends
grade
super super
Person
updateGrade
getBio
name
firstName lastName
const human = {
firstName: 'Alexis',
lastName: 'Turner',
get name() {
return `${this.firstName} ${this.lastName}`
},
set name(name) {
const names = name.trim().split(' ')
this.firstName = names[0]
this.lastName = names[1]
}
}
XMLHttpRequest
GET
send
readyState 4
// Making an HTTP request
const request = new XMLHttpRequest()
request.open('GET', 'http://puzzle.mead.io/puzzle')
request.send()
200
400
status
status 200
200
200
// Making an HTTP request
const request = new XMLHttpRequest()
request.open('GET', 'http://puzzle.mead.io/puzzle?wordCount=3')
request.send()
XMLHttpRequest
XMLHttpRequest
getPuzzle
getPuzzle
getPuzzle
request.open('GET', 'http://puzzle.mead.io/puzzle?wordCount=3')
request.send()
}
return () => {
return count
}
}
0 createCounter
count count
createCounter count
createCounter
const createTipper = (baseTip) => {
return (amount) => {
return baseTip * amount
}
}
const tip20 = createTipper(.2)
const tip30 = createTipper(.3)
console.log(tip20(100))
console.log(tip20(80))
console.log(tip30(100))
createTipper createTipper
baseTip amount
createTipper
new Promise
resolve reject
resolve reject
resolve
reject
then
resolve
reject
myPromise.then((data) => {
console.log(data) // Will print "Example data"
}, (err) => {
console.log(err)
})
getDataPromise
getDataPromise(10).then((data) => {
getDataPromise(data).then((data) => {
console.log(data) // Will print "40"
}).catch((err) => {
console.log(err)
})
}).catch((err) => {
console.log(err)
})
then then
getDataPromise(10).then((data) => {
return getDataPromise(data)
}).then((data) => {
console.log(data) // Will print "40"
}).catch((err) => {
console.log(err)
})
then
catch
fetch fetch
resolve
reject
fetch responseText
json
async
const processData = async () => {
return 101
}
processData().then((data) => {
console.log(data) // Will print "101"
}).catch((error) => {
console.log(error)
})
processData().then((data) => {
console.log(data)
}).catch((error) => {
console.log(error) // Will print error object
})
await getPuzzle
await fetch
response.json getPuzzle
const getPuzzle = async (wordCount) => {
const response = await
fetch(`http://puzzle.mead.io/puzzle?wordCount=${wordCount}`)
getPuzzle('2').then((puzzle) => {
console.log(puzzle)
}).catch((err) => {
console.log(`Error: ${err}`)
})
// index.js file
const name = 'Andrew'
const person = {
name,
getName() {
return this.name
}
}
console.log(person.getName())
// bundle.js file
'use strict';
console.log(person.getName());
# Setup a boilerplate package.json file
npm init -y
// package.json
// Other properties removed to keep things short
{
"scripts": {
"build": "babel src/index.js --out-file public/scripts/bundle.js --
presets env --watch"
}
}
npm install
module.exports = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'public/scripts'),
filename: 'bundle.js'
}
}
export
// utilities.js
export const add = (a, b) => a + b
import
// index.js
import { add, subtract } from './utilities'
add subtract
square
// utilities.js
const add = (a, b) => a + b
const subtract = (a, b) => a - b
const square = (x) => x * x
square otherSquare
add
// index.js
import otherSquare, { add } from './utilities'
test exclude
use
npm install babel-loader@7.1.4
"scripts": {
"serve": "live-server public",
"build": "webpack"
}
}
npm install webpack-dev-server@3.1.3
--
mode development production
webpack webpack-dev-server
entry
isEmail
import validator from 'validator'
teamName
players
const printTeam = (teamName, coach, ...players) => {
console.log(`Team: ${teamName}`)
console.log(`Coach: ${coach}`)
console.log(`Players: ${players.join(', ')}`)
}
printTeam
const team = {
name: 'Libery',
coach: 'Casey Penn',
players: ['Marge', 'Aiden', 'Herbert', 'Sherry']
}
printTeam(team.name, team.coach, ...team.players)
let cities = ['Barcelona', 'Cape Town', 'Bordeaux']
let citiesClone = [...cities, 'Santiago']
console.log(cities) // Will print three citites
console.log(citiesClone) // Will print four citites
let house = {
bedrooms: 2,
bathrooms: 1.5,
yearBuilt: 2017
}
let clone = {
...house
}
...other
const todo = {
id: 'asdfpoijwermasdf',
text: 'Pay the bills',
completed: false
}
printTodo
todo
text completed
const todo = {
id: 'asdfpoijwermasdf',
text: 'Pay the bills',
completed: false
}
firstAge
otherAges
const age = [65, 0, 13]
const [firstAge, ...otherAges] = age