I keep on forgetting some cool declarative methods in JS, so this is a reminder compilation for me to refresh my memory as I encounter them doing coding challenges.
-
Array.prototype.sort(compareFn). Mutates array "in place" after converting values to string and comparing UTF-16 code unit values. Values are sorted ascending. If you don't want to mutate the array, usetoSorted.compareFnis called withaandband should return a negative number ifais smaller thanb, positive ifais bigger thanbor 0 if they are the same. IfcompareFnis not supplied the array is sorted after comparing the values to their string form. More here. -
Math.max(value1, value2, etc.)andMath.min(value1, value2, etc.). If the array has few elements, you can use it likeMath.max(...array). It is best to usereduce:
const arr = [1, 2, 3];
const max = arr.reduce((a, b) => Math.max(a, b), -Infinity);
-
String.prototype.repeat(count). Repeats a string acountnumber of times. i.e.'Hello'.repeat(3)returnHelloHelloHello. -
Array.prototype.some(cb)- returnstrueif one item in the array returns a truthy value when the callback is called upon orfalseotherwise. It stops iterating as soon as it find an element that returns a truthy value. -
0 + trueis1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unary_plus#usage_with_non-numbers -
new Set([1,1,3,2,2,3,4])will get rid of the duplicates and return[1,3,2,4]because asetcan't have duplicates. -
address.split('@').pop()will return the domain in an email even when there are 2@s.
Regex stuff
-
/^\d*/< match any series of digits at the start. You can then dostring.match(/^\d*/)to find a prefix made up of digits only. -
'string'.match(regex)will return the matches. If thegflag is used, it returns an array with the matches. If not, just the first match. i.e.'010010000110010101101100011011000110111100100001'.match(/.{1,8}/g)will return an array of bytes. -
String.fromCharCode(charCode)returns the ASCII string attached to the charCode.
Binary numbers
-
parseInt(binaryNumberString, 2)will return the integer of the number in whatever base we say. The example is base 2.
Top comments (0)