-
let
- assigns a new variable that can be overwritten with any type -
const
- assigns a new variable that can not be overwritten; however, non-scalar values can be modified (immutable variables, not really traditional constants)
Functions can also be block-scoped
{
function foo () { return 1; }
foo() === 1;
{
function foo () { return 2; }
foo() === 2;
}
foo() === 1;
}
// With a block
(argument1, argument2) => {
return returnVal
}
// Without a block
// Returns what follows the arrow
(argument1, argument2) => returnVal
Remember:
- Always anonymous (No name in a stack trace)
- Do not create a new function scope (Can not use
this
) - Really helpful for nested callbacks where you need
this
from a parent function
function doSomething (name, value=42) {
// If value is not set from a function call,
// or is set to undefined, it is 42 within the function
}
function mapType (type, ...values) {
// values is an array of additional arguments
}
'Spreads' elements of a collection you can iterate (array, string, etc) into a literal object, or into individual function parameters
let params = [6, 7, 8, 9];
let filledArray = [1, 2, 3, 4, 5, ...params];
// filledArray is now equal to
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
Native mutli-line strings with interpolation
let name = 'John';
// Easy string interpolation
// Any valid javascript can be inside of the `${}` construct
// including other template literals
const greeting = `Hello, ${name}!`; // Hello, John!
// Old way
const objOldWay = {
foo: function (a, b) {
// ...
},
bar: function (x, y) {
// ...
}
}
// Shorthand
const objShorthand = {
foo (a, b) {
// ...
},
bar (x, y) {
// ...
}
}
// Traditional way
const obj = {x: x, y: y};
// Shorthand
const obj2 = {x, y}
Class gotchas
- class properties must be defined in methods, or manually, there is no literal syntax
class Shape {
constructor (id, x, y) {
this.id = id;
this.move(x, y);
} // No comma
move (x, y) {
this.x = x;
this.y = y;
}
}
// Instantiate
let shape = new Shape('foo', 0, 0);
class Rectangle extends Shape {
constructor (id, x, y, width, height) {
// You MUST call the parent constructor
// in any extending class, or you can
// only use static methods
super (id, x, y);
this.width = width;
this.height = height;
}
}
// Instantiate
let rectangle = new Rectangle('bar', 0, 0, 10, 10);
class StringUtil {
static parseNumbers (str) {
let matches = /\-?\d+\.?\d*/;
return Number(matches[0]);
}
}
// Direct call
let num = StringUtil.parseNumbers(' 56.7b');
class Bar {
get foo () {
return this._foo;
}
set foo (value) {
this._foo = value;
}
}
// Usage
let bar = new Bar();
bar.foo = 3; // Calls set foo
console.log(bar.foo); // Calls get foo
- String.prototype.repeat(valueToRepeat)
- String.prototype.includes(valueToSearchFor)
- Array.prototype.includes(valueToSearchFor)