Skip to content

Instantly share code, notes, and snippets.

@philmill
Last active February 16, 2016 18:35
Show Gist options
  • Save philmill/5b2b4a7aa3f20ee22cff to your computer and use it in GitHub Desktop.
Save philmill/5b2b4a7aa3f20ee22cff to your computer and use it in GitHub Desktop.
Subtle and Illuminating Notes about JavaScript
// Falsey
0, NaN, ""
// Automatic Type Conversion!!!
console.log(8 * null)
//> 0
console.log("5" - 1)
//> 4
console.log("5" + 1)
//> 51
console.log("five" * 2)
//> NaN
console.log(false == 0)
//> true
console.log(null == undefined)
//> true
console.log(null == 0)
//> false
console.log(null || 'user')
//> user
console.log('mom' || 'dad')
//> mom
console.log(null && 'user')
//> null
console.log('mom' && 'dad')
//> dad
// immediately exit loop
break;
// force continuation of next iteration
continue;
typeof // a unary opperation not a method!
// Ruby equivelents of Map/Reduce
Array.prototype.filter // #select
Array.prototype.find // #detect
Array.prototype.some // #any?
Array.prototype.every // #all?
Array.prototype.forEach // #each
Array.prototype.map // #map
//
// Non mutation Array manipulation
//
// instead of Array.prototype.push
Array.prototype.concat
let list = [];
list.concat([0]);
//=> [0]
// or ES6 version
[...list, 0]
// instead of Array.prototype.splice(index,1)
const index = 1;
let list = [1,2,3];
list.slice(0, index).concat(list.slice(index + 1));
//=> [1,3]
// or ES6 version
[...list.slice(0,index), ...list.slice(index + 1)]
// instead of directly mutating an item
const index = 1;
let list = [1,2,3]; // say we want to add 1 to the value at index
list.slice(0, index).concat([list[index] + 1]).concat(list.slice(index + 1));
//=> [1,3,3]
// or ES6 version
[...list.slice(0, index), list[index] + 1, ...list.slice(index + 1)]
// I was surprised to see that foo could be referenced from within the return of a funciton definition.
// Lovely explaination and myth busting by Angus Croll ...
// https://javascriptweblog.wordpress.com/2010/10/25/understanding-javascript-closures/
var foo = function(){
console.log("this is foo = ", foo);
return {
doThis: function() { foo.doThat(); },
doThat: function() { console.log('What Closure?'); }
};
}()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment