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 to write JavaScript code faster and better.
Cut a String into Words
To divide a string into words, we can use the split
method.
For instance, we can write:
const text = "hello james smith";
const arr = text.split(" ");
Then text
would be split into an array of strings by their spaces.
So arr
would be [“hello”, “james”, “smith”]
.
Load an Image into the Canvas
We can load an image into the canvas by using the drawImage
method of the canvas context.
For instance, if we have the following canvas:
<canvas width="300" height="300"></canvas>
and image element:
<img id='cat' style='visibility: hidden' src='http://placekitten.com/200/200' />
We can write:
const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
const img = document.getElementById("cat");
context.drawImage(img, 90, 90, 50, 60, 10, 10, 50, 60);
The first argument of drawImage
is the image element.
The 2nd argument is the x coordinate of the top left corner of the image.
The 3rd is the y coordinate of the top left corner.
The 4th is the width of the sub-rectangle of the source image.
The 5th is the height of the sub-rectangle of the source image.
The 6th is the x-coordinate of the destination canvas to place the top-left corner of the source.
The 7th is the y coordinate of the top left corner.
The 8th is the width of the image to the destination canvas.
The last one is the height of the image in the destination.
Slowing Down a Loop
We can slow down a loop with promises.
First, we create our own sleep
function with the setTimeout
function:
const sleep = (ms) => {
return new Promise(resolve => setTimeout(resolve, ms))
}
We return a promise that runs setTimeout
and call resolve
. ms
is the delay in milliseconds.
Then we can run the sleep
function in a loop by running:
const list = [1, 2, 3];
(async () => {
for (const item of list) {
await sleep(1000);
console.log(item)
}
})();
We have an array list
, which we loop through in an async function.
In the loop body, we called sleep
with 1000 to delay the loop by 1 minute.
Then we log the item with the console.log
.
Get the First n Items in an Array
To get the first n
items in an array, we can use the slice
method.
For instance, we can write:
const arr = [1, 2, 3, 4, 5];
const newArray = arr.slice(0, 2);
to return the first 2 array entries from arr
in a new array.
So newArray
would be [0, 1]
.
Convert an Array to a String
We can call the toString
method to convert an array to a string.
For instance, we can write:
const list = [1, 2, 3];
const str = list.toString();
Then we get “1,2,3”
as the value of str
.
It’s not very flexible since it converts it the way it likes to.
To add more flexibility, we can use the join
method.
For instance, we can write:
const list = [1, 2, 3];
const str = list.join();
to concatenate the entries of the array into a string.
We can pass in a separator to separate the entries.
So we can write:
const list = [1, 2, 3];
const str = list.join(', ');
To use the comma as a separator.
Flattening Arrays
We can flatten arrays with flat
and flatMap
.
For instance, we can write:
const animals = ['dog', ['cat', 'wolf']];
const flattened = animals.flat();
We called flat
, which is a built-in array method.
Then we see that flattened
is [“dog”, “cat”, “wolf”]
.
flat
can flatten arrays at any level.
If we pass in 2, then it flattens 2 nesting levels.
If we pass in Infinity
, then flattening is done recursively.
So if we call:
const animals = ['dog', [['cat', 'wolf']]];
const flattened = animals.flat(2);
We get the same result.
If we write:
const animals = ['dog', [['cat', 'wolf']]];
const flattened = animals.flat(Infinity);
We get complete flattening, which also means the same result.
Conclusion
We can flatten arrays easily with flat
.
Also, we can load images from the img tag into a canvas with drawImage
.
To pause execution of JavaScript code, we can use setTimeout
with promises.