ECMA6 is changing our coding style
‘in’ Operator
The in
operator returns true
if the specified property is in the specified object or its prototype chain.
var car = {make: ‘Honda’, model: ‘Accord’, year: 1998};
console.log(‘make’ in car);
//expected output: true
Don’t forget, arrays are objects too — which means we can also use the for...in
loop on Arrays:
const arr = ['cat', 'dog', 'fish'];
for (let i in arr) {
console.log(arr[i])
}// cat
// dog
// fish
Counting instances of values in an object
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
var countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
}
else {
allNames[name] = 1;
}
return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
Unary + and — operator
+Tries to convert the operand into a number
- Tries to convert the operand into a number and negates after
Array.isArray
Arrays do not form a separate language type. They are based on objects.So typeof
does not help to distinguish a plain object from an array:
alert(typeof {}); // object
alert(typeof []); // same
But arrays are used so often that there’s a special method for that: Array.isArray(value). It returns true
if the value
is an array, and false
otherwise.
alert(Array.isArray({})); // false
alert(Array.isArray([])); // true