Skip to content

Instantly share code, notes, and snippets.

@Shemeikka
Last active September 5, 2016 18:16
Show Gist options
  • Save Shemeikka/fce0602f53d1169a3f5a7d1e8fa8b914 to your computer and use it in GitHub Desktop.
Save Shemeikka/fce0602f53d1169a3f5a7d1e8fa8b914 to your computer and use it in GitHub Desktop.
Javascript notes
// Some stuff requires ES6
// Watch this first
// Philip Roberts: What the heck is the event loop anyway? | JSConf EU 2014
// https://www.youtube.com/watch?v=8aGhZQkoFbQ
// Then read this
// https://rainsoft.io/gentle-explanation-of-this-in-javascript/
// https://strongloop.com/strongblog/higher-order-functions-in-es6easy-as-a-b-c/
// || returns the value from left side if it's true
true || false; // true
false || true; // true
// && returns the value from left side if it's false
true && false; // false
false && true; // false
// IIFE and closure
// IIFE is the (..)() part enclosing the function.
// !! This code will return function n, not the whole function !! Variable c is now a function that returns variable name.
// This name-variable cannot be accessed otherwise. It's private.
// Without using IIFE, c is a function that contains the whole function, including variable name. This means that
// the name-variable is public. To return the name, you need to call c()();
let c = (function() {
let name = "aha";
return function n() {
return name;
}
// It's also possible to return an object
/*
return {
n: function() { return name; },
s: function(val) { name = val; }
}
// Now c is an object with two functions, n and s.
// c.n(); // "aha";
// c.s("okey");
// c.n(); // "okey";
*/
})();
c(); // "aha"
// Object destructuring in function arguments
const d = { name: 'jack', age: 22, results: [1,2,3], works: true };
function printData({name, age, ...rest}) {
console.log(name, age, rest);
}
printData(d); // jack 22 [object Object] => jack 22 Object {results: Array[3], works: true}
// Filter, Map, Reduce
const orig = [1,2,3,4,5];
const isEven = val => val % 2 == 0;
const double = val => val * 2;
const sum = (a,b) => a+b; // reduce(prev, next)
let work = orig.filter(isEven).map(double).reduce(sum);
console.log(orig); // 1,2,3,4,5
console.log(work); // 12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment