- Shorten an array
- Short-circuits conditionals
- Assigning the remaining part of an array
- Object property assigning to a variable with a different name
- Select a subset of columns to display when doing console.table()
- Remove duplicate elements from the array
- Remove all falsy values from an array
- Convert a number to string
- Convert a numeric string to number
- Calculate the sum of all elements in array
- Use template literals to concatenate strings
- Get the maximum of an array
- Transform the array elements using the map function
- Calculate the running sum of an array with currying
You can set the length property to shorten an array.
const numbers = [1, 2, 3, 4, 5];
numbers.length = 3;
console.log(numbers); // Array(3) [1, 2, 3]
If you have to execute a function only if condition is true, you can use short-circuit.
// Instead of this
if (condition) {
doSomething();
}
// You can use short-circuit
condition && doSomething();
When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern:
const [a, ...b] = [1, 2, 3, 4, 5];
console.log(a); // 1
console.log(b); // [2, 3, 4, 5]
A property can be unpacked from an object and assigned to a variable with a different name than the object property:
const obj = {a: 42, b: true};
const {a: foo, b: bar} = obj;
console.log(foo); // 42
console.log(bar); // true
By default, console.table()
lists all elements in each row. You can use the optional "columns" parameter to select a subset of columns to display:
// an array of objects, logging only firstName
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const john = new Person("John", "Smith");
const jane = new Person("Jane", "Doe");
console.table([john, jane], ["firstName"]);
const myArray = [5, 4, 3, 'a', 5, 5, 'a'];
console.log([... new Set(myArray)]); // [5, 4, 3, "a"]
const myArray = [1, undefined, NaN, 2, null, '@denicmarko', true, 3, false];
console.log(myArray.filter(Boolean)); // [1, 2, '@denicmarko', true, 3]
const number = 403;
console.log(number + ''); // '403'
const numericString = '403';
console.log(+ numericString); // 403
You can use reduce
method to calculate the sum of all elements in array:
const myArray = [10, 20, 30, 40];
const reducer = (total, currentValue) => total + currentValue;
console.log(myArray.reduce(reducer)); // 100
let name = 'Horse';
console.log(`The ${name} is sleeping`); // the Horse is sleeping
let arr = [3, 5, 1];
console.log(Math.max(...arr)); // 5
const myArray = [1,2,3,4];
console.log(myArray.map(value => value * 2)); // [2, 4, 6, 8]
Here, a function is called with the initial sum
value of zero that returns a function which accumulates the values of myArray
.
const myArray = [1,1,1,1];
console.log(myArray.map((sum => value => sum += value)(0))); // [1, 2, 3, 4]