Skip to content

Instantly share code, notes, and snippets.

const countryCodes = {
US: 'United States',
CA: 'Canada',
NG: 'Nigeria',
GB: 'United Kingdom',
};
const sales = [
{ code: 'US', count: 233 },
//Explaning call in map
Using map generically
This example shows how to use map on a String to get an array of bytes in the ASCII encoding representing the character values:
var map = Array.prototype.map;
var a = map.call('Hello World', function(x) {
return x.charCodeAt(0);
});
With JSX
Ok, so this is not properly ES6, but you can use some ES6 features like property value shorthand very conveniently with JSX spread/rest syntax.
function WhySoManyProps(props) {
const user = extractUser(props);
const fudge = calculateFudge();
const bits = computeBits();
// This is soooooo redundant.
return <SomeComponent user={user} fudge={fudge} bits={bits} />;
// Nested ternary operator
var sexuallyActiveSelection = sexuallyActive === undefined ? '' : (sexuallyActive === 'Y') ? 'Sexually Active' : 'Not SexuallyActive';
//Example
console.info('@ %crecommendation condition: ID', "color: yellow; font-style: italic; background-color: blue;padding: 2px",
We can extract these values by index in ES5:
var
one = myArray[0],
two = myArray[1],
three = myArray[2];
// one = 'a', two = 'b', three = 'c'
ES6 destructuring permits a simpler and less error-prone alternative:
function reduce(index) {
var arr = [1,2,3,4,5];
return arr.slice(0, index).concat(arr.slice(index + 1));
}
//Passing your own array
function reduce(iarr, index) {
var arr = iarr;
return arr.slice(0, iarr.length - index).concat(arr.slice(index + 1));
setState is Asynchronous
I didn’t notice this when I started out with React. The setState function is asynchronous!
If you call setState and immediately inspect this.state, chances are it will not be updated yet.
If you need to set the state and immediately act on that change, you can pass in a callback function like this:
this.setState({name: 'Joe'}, function() {
// called after state has been updated
// Good practice to verify if a var exist or not or is the value is the one expected
var x = 0;
if ( typeof x !== 'undefined') {
console.log('Exist');
} else {
console.log('Not exist');
}
@jjsub
jjsub / js.curry.js
Last active April 29, 2016 18:43
Learning javascript curry
// Learning javascript curry
// see http://www.sitepoint.com/currying-in-functional-javascript/
/*Briefly, currying is a way of constructing functions that allows partial application of a function’s arguments.
What this means is that you can pass all of the arguments a function is expecting and get the result,
or pass a subset of those arguments and get a function back that’s waiting for the rest of the arguments.
It really is that simple. */
// Example