// Objects are collections that map strings
// to values of any type
var myObject = {
foo: 1
bar: 'fizz'
}
// String dereference
myObject.foo // 1
// Expression dereference
myObject['b' + 'ar'] // fizz
// Attribute assignment
myObject.bar = 'gorp'
// Function statement
function add(a, b) {
return a + b;
}
// Function expression (anonymous function AKA lambda)
function(a, b) {
return a + b;
}
// Functions are "first class"
// (you can create them and pass them around dynamically)
// and close over their parent function's scope
function makePrinter(message) {
return function() {
console.log(message)
}
}
var printUpbeatMessage = makePrinter("Isn't JS dandy?")
printUpbeatMessage() // "Isn't JS dandy?"
Over-eager type coercion
2 == '2' // true!?!?
2 === '2' // false
// Lesson: you almost always want to use the === operator for equality checks
// == coerces, === does not
undefined and null
var myObject = {
foo: null
}
var a = myObject.foo // null
var b = myObject.bar // undefined
Boolean(a) // false
Boolean(b) // false
fs.readdir(source, function (err, files) {
if (err) {
console.log('Error finding files: ' + err)
} else {
files.forEach(function (filename, fileIndex) {
console.log(filename)
gm(source + filename).size(function (err, values) {
if (err) {
console.log('Error identifying file size: ' + err)
} else {
console.log(filename + ' : ' + values)
aspect = (values.width / values.height)
widths.forEach(function (width, widthIndex) {
height = Math.round(width / aspect)
console.log('resizing ' + filename + 'to ' + height + 'x' + height)
this.resize(width, height).write(dest + 'w' + width + '_' + filename, function(err) {
if (err) console.log('Error writing file: ' + err)
})
}.bind(this))
}
})
})
}
})
Taken from callbackhell.com
// Getting into callback hell
$.ajax('https://my.api.com/will').done(function(userResponse) {
let link = response.body.friends;
$.ajax(link).done(function(friendsResponse) {
for (let friend of friendsResponse) {
let imgLink = friend.profilePicture;
$.ajax(imglink).done(function(imageBlob) {
imageBoard.push(imageBlob);
})
}
})
});
// Breaking out into functions
let addImageToBoard = (imageBlob) => imageBoard.push(imageBlob);
function fetchFriendImages(userResponse) {
for (let friend of friendsResponse) {
let imgLink = friend.profilePicture;
$.ajax(imglink).done(addImageToBoard);
}
}
$.ajax('https://my.api.com/will').done(function(userResponse) {
let link = userResponse.friends;
$.ajax(link).done(fetchFriendImages);
});
// Writing sequential-looking code with promises
fetch('https://my.api.com/will')
.then(userResponse => fetch(userResponse.friends))
.then(friendResponse => {
let imgPromises = friendResponses.map(f => fetch(f.profilePicture));
return Promise.all(imgPromises);
})
.then(images => {
for (let img of images) {
imageBoard.push(img);
}
});