Shorthand Flashcards
concise property initializers
function xyzzy(foo, bar, qux) {
return {
foo,
bar,
qux,
};
}
In each case, we merely use the name of the property we want to initialize, and JavaScript looks for a variable with the same name to use as the initial value.
concise methods
let obj = {
foo() {
// do something
},
bar(arg1, arg2) {
// do something else with arg1 and arg2
},
}
//The new concise method syntax lets you eliminate the : and the word function:
object destructuring
let obj = {
foo: “foo”,
bar: “bar”,
qux: 42,
};
let foo = obj.foo;
let bar = obj.bar;
let qux = obj.qux;
//or
let { foo, bar, qux } = obj;
renaming the variables in object destructuring
let { qux: myQux, foo, bar } = obj;
//This example creates a myQux variable that receives the value of obj.qux
destructuring with function parameters
function xyzzy({ foo, bar, qux }) {
console.log(qux); // 3
console.log(bar); // 2
console.log(foo); // 1
}
let obj = {
foo: 1,
bar: 2,
qux: 3,
};
xyzzy(obj);
object destructuring as an assignment to existing variables
{ foo, bar, qux } = obj;
//will produce an error, { marks the beginning of a block rather than destructuring.
Instead:
({ foo, bar, qux } = obj);
array destructuring
let foo = [1, 2, 3];
let [ first, second, third ] = foo;
skipping elements in an array destructuring
let bar = [1, 2, 3, 4, 5, 6, 7];
let [ first, , , fourth, fifth, , seventh ] = bar;
using array destructuring to perform multiple assignments in a single expression
let one = 1;
let two = 2;
let three = 3;
let [ num1, num2, num3 ] = [one, two, three];
console.log(num1); // 1
console.log(num2); // 2
console.log(num3); // 3
how can we use spread syntax with the argument to a function
function add3(item1, item2, item3) {
return item1 + item2 + item3;
}
let foo = [3, 7, 11];
add3(…foo); // => 21
using spread to clone or concat arrays
// Create a clone of an array
let foo = [1, 2, 3];
let bar = […foo];
console.log(bar); // [1, 2, 3]
console.log(foo === bar); // false – bar is a new array
// Concatenate arrays
let foo = [1, 2, 3];
let bar = [4, 5, 6];
let qux = […foo, …bar];
qux; // => [1, 2, 3, 4, 5, 6]
What does spread return with objects
Spread syntax with objects only returns the properties thatObject.keyswould return. That is, it only returns enumerable “own” properties. That means, in part, that it’s not the right choice when you need to duplicate objects that inherit from some other object. It also means that you lose the object prototype.
using spread to clone an object
// Create a clone of an object
let foo = { qux: 1, baz: 2 };
let bar = { …foo };
console.log(bar); // { qux: 1, baz: 2 }
console.log(foo === bar); // false – bar is a new object
What does rest syntax do?
Rest syntax collects multiple items into an array or object
how do we use rest syntax with arrays?
//With Arrays
let foo = [1, 2, 3, 4];
let [ bar, …otherStuff ] = foo;
console.log(bar); // 1
console.log(otherStuff); // [2, 3, 4]