# Tricks in JavaScript
# Array Distinct
var nums = [1, 1, 2, 2, 3, 3, 4, 5];
var unique = [...new Set(nums)];
console.log(unique);
// [1, 2, 3, 4, 5]
1
2
3
4
5
2
3
4
5
# &&
& ||
&&
returns a first false
value, if all of them were true
, then returns the last expression.
1 && 2 && 3 // 3
0 && null // 0
1
2
2
||
returns a first true
value, if all of them were false
, then returns the last expression.
1 || 2 || 3 // 1
0 && null // null
1
2
2
# Get last item in an array
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(array.slice(-1)); // Result: [9]
console.log(array.slice(-2)); // Result: [8, 9]
console.log(array.slice(-3)); // Result: [7, 8, 9]
1
2
3
4
2
3
4