You are on page 1of 112

# Print the full path to the current working directory

pwd

# Clear the terminal output


clear

# List the contents of the working directory


ls

# Change directories to home


cd ~

# Navigate up a directory then into a nested directory


cd ../Downloads
# Run a JavaScript file though Node.js
node script.js

// Create a variable to store the city


let city = 'Philadelphia'

// Create a variable to store the state


let state = 'Pennsylvania'

// Create a variable to combine the city and state


let location = city + ', ' + state

// Print the combined location to the terminal


console.log(location)
// Create a number and assign to a variable
let age = 26

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

//

// A comment on its own line

console.log('Welcome!') // A comment at the end of a line


// === equal
'Andrew' === 'Andrew' // True
'Mike' === 'mike' // False

// !== not equal


'Andrew' !== 32 // True
12 !== 12 // False

// < less than


3 < 40 // True
3 < 3 // False

// <= less than or equal to


// 3 <= 3 // True
// 0 <= -23 // False

// > greater than


16 > -16 // True
-16 > 16 // False

// >= greater than or equal to


-23 >= -40 // True
100 => -100 // False

let ticketStatus = 'closed'

if (ticket === 'closed') {


console.log('This support ticket has been closed')
}
let age = 18

if (age >= 18) {


console.log('You are an adult')
} else {
console.log('You are not an adult')
}

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

// This condition will pass if isAccountActive is false


if (!isAccountActive) {
console.log('Account is locked')
}

$$

let temp = 170

if (temp >= 70 && temp <= 90) {


console.log('Get outside!')
} else {
console.log('Stay inside')
}

||
let isGuestOneVegan = true
let isGuestTwoVegan = true

if (isGuestOneVegan && isGuestTwoVegan) {


console.log('Only offer up vegan food.')
} else if (isGuestOneVegan || isGuestTwoVegan) {
console.log('Make sure to offer up some vegan food.')
} else {
console.log('Offer up anything on the menu.')
}
// Global scope (name, getName)
// Local scope (age)
// Local scope (location)
// Local scope (height)

let name = 'Andrew'


let getName = function () {
console.log(name)
let age = 26

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}`
}

let result = getNewScoreMessage()


console.log(result)
console.log(score)
// Example 1: Leaked global

let getNewScoreMessage = function () {


if (1 < 2) {
score = 3
}

console.log(score)
}
getNewScoreMessage()
console.log(score) // Prints 3

// Example 2: No leaked global

let getNewScoreMessage = function () {


let score

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
}

let temp70 = fahrenheitToCelsius(70)


console.log(temp70)
let temp32 = fahrenheitToCelsius(32)
console.log(temp32)

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

let name = 'Andrew'

name = null

if (name === null) {


console.log('No name is set!')
}
let add = function (x, y, z) {
return x + y + z
}

let result = add(1, 12, 3)


console.log(result)

let getScoreText = function (name = 'Anonymous', score = 0) {


return `${name} Score: ${score}`
}

let text = getScoreText(undefined, 11)


console.log(text)
// Global scope (add)
// Local scope (a, b, result)

let add = function (a, b) {


let result = a + b
return result
}

console.log(add(2, 4))
// Unable to access a, b, or result. They are not in scope in the global
scope.

bio
altBio

let petName = 'Hal'


let petAge = 3

let bio = petName + ' is ' + petAge + ' years old.'


console.log(bio)

let altBio = `${petName} is ${petAge} years old.`


console.log(altBio)
let myBook = {
title: '1984',
author: 'George Orwell',
pageCount: 326
}
let myBook = {
title: '1984',
author: 'George Orwell',
pageCount: 326
}

// Reading a property value with dot notation


console.log(`${myBook.title} by ${myBook.author}`)

// Chaing an object property value using dot notation


myBook.title = 'Animal Farm'
let myBook = {
title: '1984',
author: 'George Orwell',
pageCount: 326
}

let otherBook = {
title: 'A Peoples History',
author: 'Howard Zinn',
pageCount: 723
}

let getSummary = function (book) {


console.log(`${book.title} by ${book.author}`)
}

getSummary(myBook)

let convertFahrenheit = function (fahrenheit) {


return {
fahrenheit: fahrenheit,
kelvin: (fahrenheit + 459.67) * (5 / 9),
celsius: (fahrenheit - 32) * (5 / 9)
}
}

let temps = convertFahrenheit(74)


console.log(temps)
account addExpense myAccount
account myAccount

// Both logs print the same exact thing


let myAccount = {
name: 'Andrew Mead',
expenses: 0,
income: 0
}

let addExpense = function (account, amount) {


account.expenses = account.expenses + amount
console.log(account)
}

addExpense(myAccount, 2000)
console.log(myAccount)

myAccount
account
// Both logs print differen things
let myAccount = {
name: 'Andrew Mead',
expenses: 0,
income: 0
}

let addExpense = function (account, amount) {


account = {}
account.age = 1
console.log(account)
}

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)

// Convert to upper case


console.log(name.toUpperCase())

// Convert to lower case


console.log(name.toLowerCase())

let password = 'abc123asdf098'

// Includes method
console.log(password.includes('password'))

Math
let num = 103.941

// Specify decimal points


console.log(num.toFixed(2))

// Round numbers
console.log(Math.round(num))
console.log(Math.floor(num))
console.log(Math.ceil(num))

// Generate a random number


let min = 0
let max = 1
let randomNum = Math.floor(Math.random() * (max - min + 1)) + min

let

const

const
isRaining

const isRaining = true

isRaining = false

console.log(isRaining)

const
let
var const let
let var

var name = 'Andrew'


name = 'Vikram'
console.log(name)

var const let


var

var

var
const let

if (true) {
var name = 'Andrew'
let age = 26
}

console.log(name) // Will print: Andrew


console.log(age) // Will print: ReferenceError

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 name = 'Andrew'


var name = 'Mike'
console.log(name) // Will print: Mike

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]

// Array of mixed types


const data = [true, 12, 'Andrew']

0
0 2

const names = ['Andrew', 'Vikram', 'Zhu']

// Get the first item


console.log(names[0])

// Get the last item using bracket notation and the length property
console.log(names[names.length - 1])

push unshift push


unshift
const nums = [1]

nums.push(12)
nums.unshift(3)

console.log(nums) // Will print [3, 1, 12]

splice splice

const nums = [99, 199, 299]

// Add a new item at the second position without deleting any existing items
nums.splice(1, 0, 399)

console.log(nums) // Will print [99, 399, 199, 299]

pop shift pop


shift

const nums = [10, 20, 30, 40]

nums.pop()
nums.pop()
nums.shift()

console.log(nums) // Will print [20]

splice

1
const nums = [99, 199, 299]

// Remove the second item in the list


nums.splice(1, 1)

console.log(nums) // Will print [99, 299]

splice

const nums = [10, 20, 30, 40]

// Use bracket notation to replace the last item


nums[3] = 1000

// Use splice to replace the first item with 2000


nums.splice(0, 1, 2000)

console.log(nums) // Will print [2000, 20, 30, 1000]

forEach
forEach
forEach

const todos = ['Order cat food', 'Clean kitchen', 'Buy food', 'Do work',
'Exercise']

// This will print a numbered list for each todo item


todos.forEach(function (todo, index) {
const num = index + 1
console.log(`${num}. ${todo}`)
})

forEach

0 1
2

for (let count = 0; count <= 2; count++) {


console.log(count)
}
const players = ['Breanna', 'Kathi', 'Hunter', 'Andrew']

for (let count = 0; count < 3 && count < players.length; count++) {
const num = count + 1
const player = players[count]
console.log(`${num}. ${player}`)
}

indexOf
-1

const places = ['Philadelphia', 'Texas', 'Vermont']


const index = places.indexOf('Vermont')

console.log(index) // Will print 2

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'
}]

const index = notes.findIndex(function (note, index) {


return note.title === 'Habbits to work on'
})

console.log(index) // Will print 1

find findIndex true


false findIndex
find
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'
}]

const findNote = function (notes, noteTitle) {


return notes.find(function (note, index) {
return note.title.toLowerCase() === noteTitle.toLowerCase()
})
}

const note = findNote(notes, 'my next trip')


console.log(note) // Will print the first object from our array above

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
}]

const getThingsToDo = function (todos) {


return todos.filter(function (todo) {
return !todo.completed
})
}

// Will print an array of all todos that still need to be completed


console.log(getThingsToDo(todos))

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
}]

const sortTodos = function (todos) {


todos.sort(function (a, b) {
if (!a.completed && b.completed) {
return -1
} else if (!b.completed && a.completed) {
return 1
} else {
return 0
}
})
}

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

const element = document.querySelector('p')

querySelector

querySelectorAll

const elements = document.querySelectorAll('p')

remove
h1
const element = document.querySelector('h1')
element.remove()

const element = document.querySelector('p')


element.textContent = element.textContent + '!'

createElement appendChild

createElement

appendChild
const newParagraph = document.createElement('p')
newParagraph.textContent = 'This is a new element from JavaScript'
document.querySelector('body').appendChild(newParagraph)

addEventListener

document.querySelector('button').addEventListener('click', function (e) {


e.target.textContent = 'The button was clicked'
})
id id

id

<h1 id="my-id">My title</h1>

<h1 id="second-class">My title</h1>


<p class="class-one second-class">My title</p>

querySelector querySelectorAll

// Select an element with an id of "my-id"


document.querySelector('#my-id')

// Select all elements with an class of "special"


document.querySelectorAll('.special')

type
text type
placeholder

<input id="search-text" type="text" placeholder="Filter todos">

addEventListener
value

document.querySelector('#search-text').addEventListener('input', function (e)


{
console.log(e.target.value)
})
<form id="name">
<input type="text" placeholder="Enter your name" name="firstName">
<button>Submit</button>
</form>

name

submit

e.preventDefault()

document.querySelector('#new-todo').addEventListener('submit', function (e) {


e.preventDefault()
console.log(e.target.elements.firstName.value)
e.target.elements.text.value = ''
})
type checkbox

<label>
<input id="delivery" type="checkbox"> Check for delivery
</label>

change
checked checked true
false

document.querySelector('#delivery').addEventListener('change', function (e) {


console.log(e.target.checked)
})

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

document.querySelector('#filter-by').addEventListener('change', function (e)


{
console.log(e.target.value)
})
localStorage

setItem
"Andrew"
"username"

localStorage.setItem('username', 'Andrew)

getItem
getItem

const name = localStorage.get('username')


console.log(name)

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

const hotel = 'Radish Inn'


debugger
checkIn(hotel)

createElement appendChild
const root = document.createElement('div')
const text = document.createElement('span')
const button = document.createElement('button')

// Setup the text


text.textContent = 'Scranton, PA'
root.appendChild(text)

// Setup the button


button.textContent = 'x'
root.appendChild(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
})

const now = new Date()

Date

const dateOne = new Date('March 1 2017 12:00:00')

const dateOne = new Date('March 1 2017 12:00:00')


const month = dateOne.getMonth() + 1
const day = dateOne.getDate()
const year = dateOne.getFullYear()

console.log(`${month}/${day}/${year}`) // Wil print "3/1/2017"

getHours getMinutes
getSeconds
const date = new Date('March 1 2017 12:00:00')
const timestamp = date.getTime()
console.log(timestamp) // Will print 1488387600000

const timestamp = 1488387600000


const date = new Date(timestamp)

const date = moment()


const timestamp = 1488387600000
const date = moment(timestamp)

format

const timestamp = 1488387600000


const date = moment(timestamp)
console.log(date.format('MMMM Do, YYYY')) // Wil print "March 1st, 2017"
const squareLong = (num) => {
return num * num
}
console.log(squareLong(3)) // Will print 9

filter

squareLong

const squareLong = (num) => num * num


console.log(squareLong(3)) // Will print 9
this
this

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]
}

console.log(add(11, 22, 33, 44))

add

const add = function () {


return arguments[0] + arguments[1]
}

console.log(add(11, 22, 33, 44)) // Will print 33


const team = ['Tyler', 'Porter', 'Andrew', 'Ben', 'Mike']
const message = team.length <= 4 ? `Team size: ${team.length}` : 'Too many
people on your team'
console.log(message)

showPage
showErrorPage

const age = 21

const showPage = () => {


// Show some page
}

const showErrorPage = () => {


// Show an error page
}

age >= 21 ? showPage() : showErrorPage()

47 ''
true
false
const value = 'Andrew'

if (value) {
// This will run
} else {
// This won't run
}

const value = ''

if (value) {
// This won't run
} else {
// This will run
}
typeof

// Typeof examples

console.log(typeof 43) // Will print "number"

console.log(typeof 'Andrew') // Will print "string"

console.log(typeof undefined) // Will print "undefined"

false 12

const value = false + 12


const type = typeof value
console.log(type) // Will print "number"
console.log(value) // Will print 0

false 0 true
1 false + 12 12 true + 12 13
throw

getTip

const getTip = (amount) => {


if (typeof amount !== 'number') {
throw Error('Argument must be a number')
}

return amount * .25


}
const result = getTip('12')

getTip
const getTip = (amount) => {
if (typeof amount !== 'number') {
throw Error('Argument must be a number')
}

return amount * .25


}

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'

ReferenceError: assignment to undeclared variable data

'use strict'

const processData = () => {


data = '1230987234'
}
processData()
console.log(data)
const Person = function (firstName, lastName, age) {
this.firstName = firstName
this.lastName = lastName
this.age = age
}

Person new

const me = new Person('Andrew', 'Mead', 27)


console.log(me)

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
}

const me = new Person('Andrew', 'Mead', 27, ['Teaching', 'Biking'])


console.log(me.getBio())

const person2 = new Person('Clancey', 'Turner', 51)


console.log(person2.getBio())

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 = {}

console.log(myObject.hasOwnProperty('doesNotExist')) // Will print false

myObject

null
undefined
hasOwnProperty

new

const myObject = new Object({})

console.log(myObject.hasOwnProperty('doesNotExist')) // Will print false

toLowerCase
Object.prototype

// Array: myArray --> Array.prototype --> Object.prototype --> null


// Function: myFunc --> Function.prototype --> Object.prototype --> null
// String: myString --> String.prototype --> Object.prototype --> null
// Number: myNumber --> Number.prototype --> Object.prototype --> null
// Boolean: myBoolean --> Boolean.prototype --> Object.prototype --> null

const product = 'Computer'


console.log(product.toLowerCase()) // Primitive value gets converted into an
object to run method

const otherProduct = new String('Computer')


console.log(otherProduct.toLowerCase())
Person
getBio

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

const person2 = new Person('Clancey', 'Turner', 51)


console.log(person2.getBio())

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

human.name "Alexis Turner"


name
const human = {
firstName: 'Alexis',
lastName: 'Turner',
get name() {
return `${this.firstName} ${this.lastName}`
}
}

console.log(human.name) // Prints "Alexis Turner"

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]
}
}

human.name = ' Andrew Mead '


console.log(human.firstName) // Prints "Andrew"
console.log(human.lastName) // Prints "Mead"
XMLHttpRequest
XMLHttpRequest

XMLHttpRequest
GET

send
readyState 4
// Making an HTTP request
const request = new XMLHttpRequest()

request.addEventListener('readystatechange', (e) => {


if (e.target.readyState === 4) {
const data = JSON.parse(e.target.responseText)
console.log(data) // Will print a new random puzzle
}
})

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.addEventListener('readystatechange', (e) => {


if (e.target.readyState === 4 && e.target.status === 200) {
const data = JSON.parse(e.target.responseText)
console.log(data)
} else if (e.target.readyState === 4) {
console.log('An error has taken place')
}
})

request.open('GET', 'http://puzzle.mead.io/puzzle?wordCount=3')
request.send()

XMLHttpRequest

XMLHttpRequest

getPuzzle
getPuzzle
getPuzzle

const getPuzzle = (callback) => {


const request = new XMLHttpRequest()

request.addEventListener('readystatechange', (e) => {


if (e.target.readyState === 4 && e.target.status === 200) {
const data = JSON.parse(e.target.responseText)
callback(undefined, data.puzzle)
} else if (e.target.readyState === 4) {
callback('An error has taken place', undefined)
}
})

request.open('GET', 'http://puzzle.mead.io/puzzle?wordCount=3')
request.send()
}

getPuzzle((error, puzzle) => {


if (error) {
console.log(`Error: ${error}`)
} else {
console.log(puzzle)
}
})
getCountry

const createCounter = () => {


let count = 0

return () => {
return count
}
}

const counter = createCounter()


console.log(counter()) // Will print 0

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

const myPromise = new Promise((resolve, reject) => {


setTimeout(() => {
resolve('Example data')
}, 2000)
})

then

resolve
reject

// Using myPromise from above

myPromise.then((data) => {
console.log(data) // Will print "Example data"
}, (err) => {
console.log(err)
})
getDataPromise

const getDataPromise = (num) => new Promise((resolve, reject) => {


setTimeout(() => {
typeof num === 'number' ? resolve(num * 2) : reject('Number must be
provided')
}, 2000)
})

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 then catch


response
fetch('http://puzzle.mead.io/puzzle', {}).then((response) => {
if (response.status === 200) {
return response.json()
} else {
throw new Error('Unable to fetch the puzzle')
}
}).then((data) => {
console.log(data.puzzle)
}).catch((error) => {
console.log(error)
})

fetch responseText
json

async
const processData = async () => {
return 101
}

processData().then((data) => {
console.log(data) // Will print "101"
}).catch((error) => {
console.log(error)
})

const processData = async () => {


throw new Error('Something went wrong!')
return 101
}

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}`)

if (response.status === 200) {


const data = await response.json()
return data.puzzle
} else {
throw new Error('Unable to get puzzle')
}
}

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';

var name = 'Andrew';


var person = {
name: name,
getName: function getName() {
return this.name;
}
};

console.log(person.getName());
# Setup a boilerplate package.json file
npm init -y

# Install babel so we can run our command


npm install -g babel-cli@6.26.0

# Install a babel preset that tells babel what to change


npm install babel-preset-env@1.6.1

babel input.js --out-file output.js --presets env

// 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 run <name>


npm run build

npm install

// Other properties removed to keep things short


{
"scripts": {
"serve": "live-server public",
"build": "babel src/index.js --out-file public/scripts/bundle.js --
presets env --watch"
},
"dependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.6.1",
"live-server": "^1.2.0"
}
}
// Other properties removed to keep things short
{
"scripts": {
"serve": "live-server public",
"webpack": "webpack",
"build": "babel src/index.js --out-file public/scripts/bundle.js --
presets env --watch"
},
"dependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.6.1",
"live-server": "^1.2.0",
"webpack": "^4.5.0",
"webpack-cli": "^2.0.14"
}
}
const path = require('path')

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

export const subtract = (a, b) => a - b

import
// index.js
import { add, subtract } from './utilities'

console.log(add(32, 1)) // Will print: 33


console.log(subtractadd(32, 1)) // Will print: 31

add subtract
square

// utilities.js
const add = (a, b) => a + b
const subtract = (a, b) => a - b
const square = (x) => x * x

export { add, subtract, square as default }

square otherSquare
add
// index.js
import otherSquare, { add } from './utilities'

console.log(add(32, 1)) // Will print: 33


console.log(otherSquare(10)) // Will print: 100

test exclude
use
npm install babel-loader@7.1.4

const path = require('path')

// Other properties removed to keep things short


module.exports = {
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}]
}
}

// Other properties removed to keep things short


{

"scripts": {
"serve": "live-server public",
"build": "webpack"
}
}
npm install webpack-dev-server@3.1.3

// Other properties removed to keep things short


{
"scripts": {
"dev-server": "webpack-dev-server"
}
}

const path = require('path')

// Other properties removed to keep things short


module.exports = {
devServer: {
contentBase: path.resolve(__dirname, 'public'),
publicPath: '/scripts/'
}
}

npm run dev-server

--
mode development production
webpack webpack-dev-server

// Other properties have been hidden to keep things sort


{
"scripts": {
"dev-server": "webpack-dev-server --mode development",
"build": "webpack --mode production"
}
}

const path = require('path')

// Other properties have been hidden to keep things sort


module.exports = {
devtool: 'source-map'
}
includes

npm install babel-polyfill@6.26.0

entry

const path = require('path')

// Other properties removed to keep things short


module.exports = {
entry: ['babel-polyfill', './src/index.js']
}

npm install validator@9.4.1

isEmail
import validator from 'validator'

const isValidEmail = validator.isEmail('test@example.com')


console.log(isValidEmail) // Will print true
numbers

const calculateAverage = (...numbers) => {


let sum = 0
numbers.forEach((num) => sum += num)
return sum / numbers.length
}

console.log(calculateAverage(0, 100, 88, 64)) // Will print: 63

teamName

players
const printTeam = (teamName, coach, ...players) => {
console.log(`Team: ${teamName}`)
console.log(`Coach: ${coach}`)
console.log(`Players: ${players.join(', ')}`)
}

printTeam('Liberty', 'Casey Penn', 'Marge', 'Aiden', 'Herbert', 'Sherry')

printTeam

const printTeam = (teamName, coach, ...players) => {


console.log(`Team: ${teamName}`)
console.log(`Coach: ${coach}`)
console.log(`Players: ${players.join(', ')}`)
}

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

npm install babel-plugin-transform-object-rest-spread@6.26.0


const path = require('path')

// Other properties removed to keep things short


module.exports = {
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['env'],
plugins: ['transform-object-rest-spread']
}
}
}]
}
}

let house = {
bedrooms: 2,
bathrooms: 1.5,
yearBuilt: 2017
}
let clone = {
...house
}

console.log(house) // Will print the same as clone


console.log(clone) // Will print the same as house
const person = {
name: 'Andrew',
age: 27
}
const location = {
city: 'Philadelphia',
country: 'USA'
}
const overview = {
...person,
...location,
name: 'Mike'
}
console.log(overview)

// The above code will print the following


// {
// age: 27,
// city: "Philadelphia",
// country: "USA",
// name: "Mike"
// }

...other
const todo = {
id: 'asdfpoijwermasdf',
text: 'Pay the bills',
completed: false
}

const { text:todoText, completed, details = 'No details provided', ...others


} = todo

console.log(todoText) // Will print: "Pay the bills"


console.log(completed) // Will print: false
console.log(details) // Will print: "No details provided"
console.log(others) // Will print: { id: "asdfpoijwermasdf" }

printTodo
todo
text completed

const todo = {
id: 'asdfpoijwermasdf',
text: 'Pay the bills',
completed: false
}

const printTodo = ({ text, completed }) => {


console.log(`${text}: ${completed}`)
}
printTodo(todo)

firstAge
otherAges
const age = [65, 0, 13]
const [firstAge, ...otherAges] = age

console.log(firstAge) // Will print: 65


console.log(otherAges) // Will print: [0, 13]

You might also like