1. Print a string multiple times
In javascript you could print a string multiple times by using a loop, but you can also do it like this myString.repeat(3);
and that will print the string 3 times.
2. Check the length of an array
If you are checking the length of an array like myArray.length > 0
, you can actually only check for myArray.length
. There is no need to add the greater than 0 part.
3. Check if a string is null or undefined
You can do it like this if (myString !== undefined && myString !== null) {}
or like this if (myString) {}
4. Add items into array
Probably the best way to add items into array is like this myArray.push(1);
, but you could also do it like myArray[myArray.length] = 1;
or const newArray = myArray.concat([1]);
. Since the first 2 methods modify the existing array, they are a lot faster than the last method which is creating a new constant.
5. Sort strings with accented characters
Did you know that the .sort()
function does not work well with non ASCII characters like é
or ú
? If you run ['o', 'W', 'ö', 'ä'].sort();
you will get ["W", "o", "ä", "ö"]
which is not the right order. To compare strings with accented characters you can do it like this ['o', 'W', 'ö', 'ä'].sort(Intl.Collator().compare)
or like this ['o', 'W', 'ö', 'ä'].sort((a, b) => a.localeCompare(b));
which will print ["ä", "o", "ö", "W"]