Conquering JavaScript Types
Equals, Empty, Iterate, Filter, Sort Javascript data
Data Structures
Primitive data types (A singular type of data)— String, Number, Null, Undefined, Boolean, Symbol, BigInt
Mixed data types (Combines primitives)— Object, Array
Built-ins (contains built in methods)— Map, Date, String, Array, Set, NodeList, TypedArray, custom
For more on global types such as internationalization and Error objects see here.
How to check the type of each data
In most cases you can just use typeof. However, there are a few gotchas. For example, arrays are actually a type of object. In that case we must use Array.isArray(arrayFoo). For checking a date we must use Object.prototype.toString.call(date) === ‘[object Date]’.
How to convert types
When converting types keep in mind edge cases such as values array, objects, null, undefined. Since Javascript is not type sensitive you need to be more careful with this.
Convert to number — Number(foo) or +foo.
Convert to string — String(foo) or foo.toString() or foo + “”. foo.toString() will throw an error if foo is null.
Convert to Boolean — Boolean(foo) can work but is not nessisary in most cases. If a value is not null or undefined it is considered truthy. If you need to check for a specific value use a conditional.
Convert to Symbol — Symbol(foo)
Convert to object — Object.assign({}, arrayFoo), {…arrayFoo}, arrayFoo.reduce((acc, curr) => ({…acc, [curr]: curr})
Convert to array — Object.values(foo), Object.entries(foo), Array.from(stringFoo), Array.from(String(numberFoo))
How to check for empty
Empty Object
Boolean(!Object.keys(yourObject).length)
Empty array
if (!Array.isArray(array) || !array.length) {
// array does not exist, is not an array, or is empty
// ⇒ do not attempt to process array
}
How to check for equality
Equal arrays
We could use stringify but that would require more operations.
function arraysEqual(arr1, arr2) {
if (arr1 === arr2) return true;
if (arr1 == null || arr2 == null) return false;
if (arr1.length !== arr2.length) return false;
return arr1.every((val, i) => val === arr2[i])
}
Equal strings — string1 === string2
Equal objects
When checking for equal objects often they do not need to be deeply equal. Considering what actually needs to be equal can help you create a simple function for equality. The issue with using stringify is that is does not consider if the properties are out of order. If you need deep equality this could help you.
function deepEqual(x, y) {
return (x && y && typeof x === 'object' && typeof y === 'object') ?
(Object.keys(x).length === Object.keys(y).length) &&
Object.keys(x).reduce((isEqual, key) => {
return isEqual && deepEqual(x[key], y[key]);
}, true) : (x === y);
}
Alternatively, use object comparison from a package like Deep, Lodash, or Fast.
Sorting
Array
alphabetical order — array.sort()
reverse alphabetical order — array.sort().reverse()
chronological order -
array.sort((a,b) => {
const date1 = new Date(a);
const date2 = new Date(b);
return a - b;
}
numbers — array.sort((a,b) => a-b)
Object
To sort an object by value we need to know what property to sort it by. For example, we could sort by name.
Object.keys(name).sort(function(a, b) {return -(name[a] - name[b])});
Array of objects — array.sort((a,b) => a.speed > b.speed)
Javascript Design Patterns | Different Types of Design Patterns (educba.com)
Filtering
Filtering an array of objects for property values is simple. arrayFoo.filter(val => val?.price >= 200 && val.category === ‘appliances’) Filtering an object to only keep specific properties can be done via reduce. Filtering an array can be done using a.filter(a => a.startsWith(‘be’)).
Iterating
traditional for loops can be used but are not necessary and take longer to read than modern methods written below. While loops and do while loops are useful when you don't know ahead of time how many times the loop must run and don't want to loop through everything contained in the data.
for of allows you to iterate through built ins. Primitives are not iterable. If you need to iterate through a number convert it to the string build-in first and you can the also use this method.
for(const val of array) {
console.log(val);
}
for in allows you to iterate through objects.
for(const property in object) {
console.log(property);
}
forEach is used exclusively for arrays. It is syntactic sugar.
array.forEach(val => console.log(val));
Other ways to loop arrays are possible such as map, filter, but for readabilities sake consider the use case before you choose to use them. Map should return a new value. Filter should of course remove some of the values in the array. They should serve only that purpose.