Published
Edited
Feb 17, 2020
Insert cell
md`# Learning React part 1 - ES6 Syntax`
Insert cell
Insert cell
md`# const
Like \`const\` in other languages.`
Insert cell
{
var pizza = true
pizza = false
return(pizza)
}
Insert cell
{
const pizza = true
pizza = false
}
Insert cell
Insert cell
{
var topic = "Javascript"

if (topic) {
var topic = "React"
console.log('block', topic)
}
console.log('global', topic)

}
Insert cell
{
var topic = "Javascript (ES6)"
if(topic) {
let topic = "React"
console.log("block", topic)
}
console.log("global", topic)
}
Insert cell
{
const container = d3.create("div")
.style("height","260px")
.style("width","100px")
var div;
// var creates a global variable i that is overwritten each time the loop is run
// then the console.log function looks in the higher scope for i and finds 5
for (var i=0; i<5; i++)
{
div = document.createElement("div")
div.onclick = function() {
console.log("This is box #" + i )
}
div.setAttribute("style","background: white; width:100px; height:50px; border:1px solid")
container.node().appendChild(div)
}
return container.node()
}
Insert cell
{
const container = d3.create("div")
.style("height","260px")
.style("width","100px")
var div;
// if instead we use lexical scoping, i does not get overwritten
// then the console.log function looks in the higher scope for i
// and finds the number that was there at the time of execution
for (let i=0; i<5; i++)
{
div = document.createElement("div")
div.onclick = function() {
console.log("This is box #" + i )
}
div.setAttribute("style","background: white; width:100px; height:50px; border:1px solid")
container.node().appendChild(div)
}
return container.node()
}
Insert cell
Insert cell
console.log(lastName + ", " + firstName + " " + middleName)
Insert cell
Insert cell
Insert cell
Insert cell
console.log(`${lastName}, ${firstName} ${middleName}`)
Insert cell
`
Hello ${firstName},

Thanks for ordering ${qty} tickets to ${event},

Order Details
${firstName} ${middleName} ${lastName}
${qty} x $${price} = $${qty*price} to ${event}

You can pick your tickes up at will call 30 minutes before the show,

Thanks,

${ticketAgent}
`
Insert cell
ticketAgent = "Jritch"

Insert cell
price = 4.20
Insert cell
qty = 69
Insert cell
event = "Glastonbury"
Insert cell
{
var iframe = d3.create("iframe").attr("sandbox", "allow-scripts")
return iframe.node()
// can't figure out how to append content to the iframe,
// but the takeaway from this example is that you can use format strings
// to embed formatted HTML text within javascript code blocks
}

Insert cell
Insert cell
function logActivity(name="Shane McGowan", activity="drinking") {
return `${name} loves ${activity}`
}
Insert cell
logActivity()
Insert cell
function personBuilder()
{
let defaultPerson = {
name : {
first: "Shane",
last: "McGowan"
},
'favActivity' : "drinking"
}
return defaultPerson
}
Insert cell
defaultPerson = personBuilder()
Insert cell
function logActivity2(p=defaultPerson) {
return(`${p.name.first} loves ${p.favActivity}`)
}
Insert cell
logActivity2()
Insert cell
md `# Arrow Functions
Arrow functions are new in ES6.`
Insert cell
// traditional syntax

Insert cell
lordify = function(firstname) {
return `${firstname} of Canterbury`
}
Insert cell
lordify("Dale")
Insert cell
lordify("Daryle")
Insert cell
lordify2 = firstname => `${firstname} of Canterbury`
Insert cell
lordify2("Jacob")
Insert cell
lordify3 = (firstname,land) => `${firstname} of ${land}`
Insert cell
lordify4 = (firstName, land) => {
if (!firstName) {
throw new Error("A firstName is required to lordify.")
}
if (!land) {
throw new Error("A lord must have a land.")
}
return `${firstName} of ${land}`
}
Insert cell
lordify3("igor","transylvania")
Insert cell
lordify4("kelly","sonoma")

Insert cell
// lordify4("kelly") // Error: A lord must have a land.
Insert cell
// lordify4(false,"Argentina") // Error: A firstName is required to lordify.
Insert cell
{
var tahoe = {
resorts: ["Kirkwood","Squaw","Alpine"],
print: function(delay=1000) {
setTimeout(() => {
console.log(this.resorts.join(", "))
}, delay)
}
}
tahoe.print()
}
Insert cell
Insert cell
sandwich = ({
bread: "dutch crunch",
meat: "tuna",
cheese: "swiss",
toppings: ["lettuce","tomato","mustard"]
})
Insert cell
{
var {bread, meat} = sandwich
return {bread: bread, meat: meat}
}
Insert cell
{
var lordify = regularPerson => {
return(`${regularPerson.firstname} of Canterbury`)
}
var regularPerson = {
firstname : "Bill",
lastname : "Watson"
}
return lordify(regularPerson)
}
Insert cell
{
var lordify = ({firstname}) =>{
return(`${regularPerson.firstname} of Canterbury`)
}
var regularPerson = {
firstname : "Bill",
lastname : "Watson"
}
return lordify(regularPerson)
}
Insert cell
// Destructuring is more declarative

// Code describes what we want to accomplish (we will only use the firstname variable)
Insert cell
{var [firstResort] = ["Kirkwood","Squaw","Alpine"]; return firstResort}
Insert cell
md `
# Object Literal Enhancement

The opposite of destructuring. The process of restructuring or putting back together.

We grab variables from the global scope and turn them into an object.

`
Insert cell
{
var name = "Tallac"
var elevation = 9738;

var funHike = {name, elevation};
return funHike
}
Insert cell
{
var name = "Tallac"
var elevation = 9738
var print = function() {
console.log(`Mt ${this.name} is ${this.elevation} feet tall`)
}
var funHike = {name,elevation,print}
funHike.print()
}
Insert cell
// OLD
{
var name = "John"
var sound = "Oy"
var skier = {
name: name,
sound: sound,
powderYell: function() {
var yell = this.sound.toUpperCase()
console.log(`${yell} ${yell} ${yell}!!!`)
},
speed: function(mph) {
this.speed = mph,
console.log('speed:',mph)
}
}
skier.speed(111)
skier.powderYell()
}
Insert cell
// NEW
{
let name = "John"
let sound = "Oy"
const skier = {
name,
sound,
powderYell() {
let yell = this.sound.toUpperCase()
console.log(`${yell} ${yell} ${yell}!!!`)
},
speed(mph) {
this.speed = mph,
console.log('speed:',mph)
}
}
skier.speed(111)
skier.powderYell()
}
Insert cell
// Object literal enhancement allows us to pull global variables into objects and reduces typing by making the `function` keyword unnecessary
Insert cell
Insert cell
{
let peaks = ["Tallac","Ralston","Rose"]
let canyons = ["Ward","Blackwood"]
let tahoe = [...peaks, ...canyons]
return(tahoe.join(", "))
}
Insert cell
{
let peaks = ["Tallac","Ralston","Rose"]
let canyons = ["Ward","Blackwood"]
let tahoe = [...peaks, ...canyons]
return(tahoe.join(", "))
}
Insert cell
{
let peaks = ["Tallac","Ralston","Rose"]

var [last] = peaks.reverse()
console.log(last)
return("\n" + peaks.join(", ")) // bad bc array reversed in-place
}
Insert cell
{
let peaks = ["Tallac","Ralston","Rose"]

var [last] = [...peaks].reverse()
console.log(last)
return(peaks.join(", ")) // all gucci
}
Insert cell
{
//just take the first
let lakes = ["A","B","C","D"]
let [first, ...rest] = lakes
return rest
}
Insert cell
{
function directions(...args) {
var [start, ...remaining] = args
var [finish, penultimate, ...stops] = remaining.reverse()

console.log(`drive through ${args.length} towns`)
console.log(`start in ${start}`)
console.log(`the penultimate town is ${penultimate}`)
console.log(`the destination is ${finish}`)
console.log(`stopping ${stops.length + 1} times in between`)
}

return directions(
"Ottawa",
"Kingston",
"Belleville",
"Ajax",
"Toronto"
)
}
Insert cell
// Using spread with objects
{
var morning = {
breakfast: "oatmeal",
lunch: "peanut butter and jelly"
}
var dinner = "mac and cheese"
var backpackingMeals = {
...morning,
dinner
}
return (backpackingMeals)
}
Insert cell
md` # Promises
Help make sense of asynchronous behavior.

Out of all the things that could happen in an async call, promises simplify to a pass/fail.
`

Insert cell
getFakeMembers = count => new Promise((resolves,rejects) => {
const api = `https://api.randomuser.me/?nat=US&results=${count}`
const request = new XMLHttpRequest()
request.open('GET',api)
request.onload = () =>
((request.status === 200) ? resolves(JSON.parse(request.response).results) : reject(Error(request.statusText)))
request.onerror = (err) => rejects(err)
request.send()
})
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more