JavaScript Number toString()
method with radix param
You’re probably already familiar with thetoString()
method used on a Number object, it converts a number to a string. But do you know the toString()
method actually takes a parameter ‘radix’ (range between 2–36). This parameter specifies the base in which the integer is represented in the string. Here’s some example:
const num = 140;
num.toString(); // "140"
num.toString(2); // "10001100"
num.toString(8); // "214"
num.toString(16); // "8c"
num.toString(36); // "3w"
And one of the cool things you can do with this is to generate a random ID combined with numbers and letters withtoString()
Math.random().toString(36).slice(2) // "jzark7ew57"
Create an array with initial values
JavaScript Array has this fill(value, start, end)
method that will replace all elments between start
and end
index to value
. And this comes handy when we want to create an array and filled it with initial values.
Array(5).fill(0);
// [ 0, 0, 0, 0, 0 ]Array(5).fill("test");
// [ 'test', 'test', 'test', 'test', 'test' ]
One caveat is when using fill()
with reference type it will fill the slots with pointers to the…