+
ClojureScript, ElixerScript, Elm, Scala.js, TypeScript, CoffeeScript, ASM, Dart
Almost Java
var arr = ["a","b","c"];
for(var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
while(true) {
if(!false || true) {
// do something
break;
}
}
switch (thing) {
case "a":
break;
case "b": // fall through
default:
return "whatever";
}
try {
throw new Error("an error");
} catch(err) {
console.log(err.message);
}
// number
var num1 = 5
var num2 = .1
var num3 = num1 + num2 // 5.1
num3++ // 6.1
// string
var str1 = "string"
str1[0] // "s"
str1.substring(0, 4) // "stri"
var str2 = str1 + num3 // "string6.1"
// boolean
var thisIsTrue = true
var thisIsFalse = !thisIsTrue
// other
undefined
null
NaN
Infinity
var obj = { a: 'hello' }
if(obj) {
// this works
}
if('string') {
// this works
}
obj && obj.a // 'hello'
obj && obj.a && obj.a.b // undefined
var obj2
obj2 || obj // { a: 'hello' }
var arr = [57, 'bananas']
arr[0] = 'oranges'
arr.pop() // 'bananas'
arr.push('grapes')
arr // ['oranges', 'grapes']
Arrays are untyped, mutable, and have stack/queue methods
Try it yourself
var obj = {
name: 'John',
'last name': 'Doe'
}
obj.name // 'John'
obj['last name'] // 'Doe'
obj.age = 30
Object.keys(obj) // ['name', 'last name', 'age']
Object.values(obj) // ['John', 'Doe', 34]
delete obj.name
Objects are mutable hashmaps
// simple function
var addTwoNumbers = function(num1, num2) {
return num1 + num2
}
addTwoNumbers(1, 2) // 3
// methods
var obj = {
counter: 1,
addToCounter: function(num) {
this.counter += num
}
}
obj.addToCounter(5)
obj.counter // 6
let blockScoped = 'value'
const nonReassignable = 'value'
blockScoped = 'value2' // fine
nonReassignable = 'value2' // error
declarations
const obj = { greeting: 'hello', name: 'John', age: 30 }
const { greeting, name, ...rest } = obj
rest // { age: 30 }
const arr = [1, 2, 3]
const arr2 = [...arr, 4, 5, 6] // [1,2,3,4,5,6]
function sum() {
var total = 0
for(var i of arguments) {
total += i
}
return total
}
sum(...arr2)
spread
// file1
var importantThing = 42
export default importantThing
// file 2
export var thing1 = 4
var thing2 = 6
export thing2
// file 3
import importantThing from './file1'
import { thing1, thing2 } from './file2'
modules
// original recipe
const func1 = function() {}
function func2() {}
// extra spicy
const noArgs = () => {}
const oneArg = arg => {}
const twoArgs = (a,b) => { return a + b }
const implReturn = arg => arg + 1
// inline functions
const arr = [1,2,3]
arr.map(n => n + 1) // [2,3,4]
arr.filter(n => n % 2 === 0) // [2]
arr.reduce((acc, n) => acc + n, 0) // 6
arrow functions
Try it yourself
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
area() {
return this.height * this.width
}
}
console.log(new Rectangle(5,8).area())
"classes"
Why React?
Workshop continued...