Like any kind of apps, JavaScript apps also have to be written well.
Otherwise, we run into all kinds of issues later on.
In this article, we’ll look at some tips we should follow when writing JavaScript code.
Get a Random Number in a Specific Range
We can get a random number from a specify range with the Math.random()
method.
For example, we can write:
const min = 2;
condt max = 10;
const x = Math.floor(Math.random() * (max - min + 1)) + min;
Since Math.random()
only returns a number between 0 and 1, we’ve to multiply what it returns with max — min + 1
.
Then we add that to min
to make it within range.
Generate an Array of Numbers with Numbers from 0 to Max
We can create an array of numbers by using a for loop.
For example, we can write:
let numbersArray = [] , max = 100;
for (let i = 1; numbersArray.push(i++) < max);
We use the for
loop to increment i
by 1 with each iteration.
And then we end with we reach max — 1
.
i++
increments and returns the number we return.
Generate a Random Set of Alphanumeric Characters
We can create a random set of alphanumeric characters by using the toString
and substr
methods.
For instance, we can write:
function generateRandomAlphaNum(len) {
let randomString = "";
while (randomString.length < len) {
randomString += Math.random()
.toString(36)
.substr(2);
}
return randomString.substr(0, len);
}
We have the generateRandomAlphaNum
function.
And we use the while
loop to generate the string up to the given len
value.
To generate the character we use the Math.random()
with the toString
and substr
calls to create the character.
Shuffle an Array of Numbers
We can shuffle an array of number with the sort
method.
For example, we can write:
const numbers = [5, 2, 4, 3, 6, 2];
numbers = numbers.sort(() => { return Math.random() - 0.5});
We return a random number that’s positive or negative so that the order is switched only when it’s positive.
That’s random so we shuffle them.
A String Trim Function
We can trim all whitespace with the replace
method and some regex.
For example, we can write:
str.replace(/^s+|s+$/g, "")
We trim all whitespace with the regex.
JavaScript strings also have the trim
method to do the trimming.
Append an Array to Another Array
To append an array to another array, we can use the spread operator with push
.
For example, we can write:
array1.push(...array2);
We can also use the spread operator without push
:
const arr = [...arr1, ...arr2];
Transform Arguments into an Array
We can get arguments as an array with the rest operator.
For example, if we have:
const foo = (...args) => {}
Then whatever we have in args
will be an array.
We can pass in anything into foo
and it’ll end up in args
.
Conclusion
We can generate random entities with the Math.random
method.
Also, we can append items to arrays and get arguments.