Skip to content

Instantly share code, notes, and snippets.

@bambielli
Last active August 15, 2017 01:59
Show Gist options
  • Save bambielli/25dd9778f286fe04338092c87b145fc2 to your computer and use it in GitHub Desktop.
Save bambielli/25dd9778f286fe04338092c87b145fc2 to your computer and use it in GitHub Desktop.
A primer for es6. Meant to be run in a node environment. Make sure you're on node 8.3.0 if you want to test out the spread operator.
/****************
ES6 FEATURE
let && const: new ways to define variables more expresively
let --> defines a mutable variable
const --> defines an immutable variable
- NOTE: if a `const` is assigned to a reference type (an object), properties of that reference can still change.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
****************/
// In ES5, only var was available for variable declaration
var fruit = 'apple';
var cost = 5.50;
var basket = {
fruit: fruit,
drink: 'beer',
cost: cost,
};
// mutations are allowed
fruit = 'grapefruit';
cost = 6.50
basket.fruit = 'grapes';
basket = {};
// ES6 introduced `let` and `const`, which are more expressive (they indicate which variables change). var is still ok to use in ES6.
// You should prefer declaring variables as `const`, since immutability reduces the frequency of bugs due to unexpected mutations!
let food = 'sandwiches';
const price = 5.50
const shoppingCart = {
food: food,
drink: 'soda',
price: price
}
food = 'grapefruit'; // this is allowed, since variable declared as `let`.
// price = 6.50 // this NOT allowed, since we are attempting to assign a new value to a const.
shoppingCart.food = 'pasta' // this is allowed, since properties of reference type are still mutable.
// shoppingCart = {} // this is NOT allowed, since we are attempting to assign a new reference to a const.
/****************
ES6 FEATURE
Template Literals: A new syntax for building strings, which allow for embedded expressions
String Interpolation: the interpretation of expressions inserted in the middle of a template literal.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
****************/
// ES5 way of inserting expressions in the middle of strings
const name = 'Brian'
const stringWithExpression = 'This is ' + name + ', 1 + 2 = ' + (1 + 2) + ' and I love Javascript!';
// ES6 introduced template literals and string interpolation, allowing for easier string building with expressions
const templateLiteralWithInterpolatedExpressions = `This is ${name}, 1 + 2 = ${1 + 2} and I love Javascript!`;
/****************
ES6 FEATURE
Arrow Functions: A new way for creating functions in ES6.
- Arrow functions do NOT bind a new `this` to their scope.
- Functions declared with `function` keyword do bind a new `this`.
- Arrow functions can NOT be used as constructors (since they don't bind a new `this`)
- Arrow functions can drop parenthesis for single parameter functions.
- Arrow functions can drop curly braces around function body for single expression functions.
For more details and examples on how arrow functions bind `this`, see blog post:
http://www.bambielli.com/til/2017-04-16-javascript-arrow-functions/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
***************/
// The binding of `this`
// Example of how the binding of 'this' differs between function keyword and arrow function declarations
this.name = 'Brian';
function es5Function() {
console.log('My name is ' + this.name);
};
const es6ArrowFunction = () => {
console.log('My name is ' + this.name);
};
es5Function(); // logs 'My name is undefined', since a function defined with `function` keyword binds a new `this`
es6ArrowFunction(); // logs 'My name is Brian', since arrow functions do not bind a new `this`.
// Constructors
function Animal(name) {
this.name = name
};
const dog = new Animal('Fido');
console.log(dog.name);
const Pie = (filling) => { // arrow functions can't be used as constructors (they don't bind a new `this`)
this.filling = filling;
};
// const pie = new Pie('cherry'); // Throws error
// Anonymous es6 arrow function
// if function is a single expression,
// implicitly returns the expression result. Can drop curlys around function body.
(name, age) => `name is ${name} age is ${age}`;
// single parameter arrow functions can also drop the parenthesis.
name => `name is ${name}`;
/****************
ES6 FEATURE
Class Keyword: Classes are syntactic sugar around creating object templates in javascript.
- `class` does NOT introduce new object-oriented inheritance model to Javascript - still prototype-based
- `extends` implements a proper prototypal inheritance relationship between two javascript classes, without the mess.
To learn more about implementing prototypal inheritance relationships without using the class keyword, see the following blog post:
http://www.bambielli.com/til/2017-04-09-javascript-inheritance/
****************/
class Base {
static goodBye() {
return 'See ya later!';
}
constructor(name) {
this.name = name;
}
greet() {
return `hello ${this.name}`
}
}
class ChildBase extends Base {
constructor(name, age) {
super(name); // must be called first
this.age = age;
}
greet() {
// partial overriding
return `${super.greet()} you are ${this.age}`;
}
}
const base = new Base('Brian');
const childBase = new ChildBase('Devin', 'old');
console.log(base.greet());
console.log(childBase.greet());
// console.log(base.goodBye()) // won't work, since method is static
// can call static methods from either Superclass or Sub-Class
console.log(Base.goodBye());
console.log(ChildBase.goodBye());
/****************
ES6 FEATURE
Destructuring Assignment: Taking the values of an array or properties of an object, and extracting them in to distinct variables.
- This is often referred to as "unpacking" values in to variables.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
*****************/
const obj1 = {
firstName: 'Devin',
color: 'green',
}
// extracts firstName and shirt in to variables
const {firstName, color} = obj1;
// the following two lines are behaviorially equivalent
console.log(firstName, color);
console.log(obj1.firstName, obj1.color)
// works with arrays too
const [a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(a, b, rest); // note ...rest takes the rest of the values!
/********
ES6 Feature
Object Spread: Allows object or array to be expanded in places where key value pairs are expected.
- Useful for merging keys of multiple objects, concatenating arrays, passing all props to React Components.
- Only available in node >= 8.3.0
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator
*********/
// WARNING: As of August 13, 2017, the object.spread operator ONLY works with node 8.3.0 and later.
// if you'd like to see the spread operator in action, upgrade to 8.3.0 and uncomment the following lines.
// const obj2 = {
// ...obj1,
// favoriteFruit: 'apples',
// };
// // works with arrays too
// const arr1 = [1, 2]
// const arr2 = [3, 4]
// const arr3 = [...arr1, ...arr2];
// console.log(obj2); // logs { firstName: 'Devin', color: 'green', favoriteFruit: 'apples' }
/*****
Functional Programming Feature
Array.map(fn): Accepts a function as a parameter, applies the function to each item in the array on which it was called, returning a new array.
- fn(currentItem, index) --> accepts the current item in the array being transformed, and the index of that item in the array.
Should return a value, representing the transformation applied to the item in the array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
*****/
const nums = [1,2,3];
const timesTwo = nums.map((currentItem, index) => {
return currentItem * 2;
}); // resulting array is [2, 4, 6]
/*****
Functional Programming Feature
Array.filter(fn): Accepts a function as a parameter, function defines a test to be run against each item in the array.
If the test returns true, that item is added to the return array. If the test returns falsey, that item is not added.
Returns an array where all items passed the test provided in the function.
fn(currentItem, index) --> accepts the current item in the array being tested, and the index of that item in the array.
Should return a boolean indicating whether the item has passed the test.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
*****/
const nums2 = [1,2,3];
const greaterThanOne = nums2.filter((currentItem, index) => {
return currentItem > 1;
}); // resulting array is [2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment