Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.
In this article, we’ll look at some solutions to common JavaScript problems.
Turn JavaScript Array into a Comma-Separated List
We can use the array instance’s join
method to join the strings together with a comma.
For instance, we can write:
const arr = ["foo", "bar", "baz"];
console.log(arr.join(", "));
Constructors in JavaScript Objects
JavaScript objects can be created from constructors.
To create it. we write:
function Box(color) {
this.color = color;
}
Box.prototype.getColor = function(){
return this.color;
};
We created the Box
constructor with the color
instance variable.
Also, we attach the getColor
method with the prototype
property to return the color
.
Then we can use the new
operator to create a Box
instance:
const box = new Box("brown");
console.log(box.getColor());
Equivalent, we can use the class syntax:
class Box {
constructor(color) {
this.color = color;
}
getColor(){
return this.color;
}
}
We put everything in the Box
class instead of using prototypes.
However, they’re the same.
Disable ESLint Rule for a Specific File
We can disable ESLint rules for a specific file with comments.
For instance, we can write:
/* eslint no-use-before-define: 0 */
to turn off the a no-use-before-define
rule.
Or we can write:
/* eslint-disable no-use-before-define */
to do the same thing.
And we can write:
/* eslint no-use-before-define: 2 */
to turn it on.
We can also tell ESLint to ignore specific files by putting the file paths in .eslintignore
:
build/*.js
node_modules/**/*.js
Add a JavaScript / jQuery DOM Change Listener
To listen for DOM changes, we can listen to the DOMSubtreeModified
event.
For instance, we can write:
$("#div").bind("DOMSubtreeModified", () => {
console.log("tree changed");
});
We use jQuery’s bind
method to listen to the event.
Early Exit from Function
To end a function early, we can use the return
keyword.
It can be placed anywhere to end a function early.
For example, we can write:
const myfunction = () => {
if (shouldStop) {
return;
}
}
Removing Items from Local Storage When the Tab or Window is Closed
To remove the item from local storage when the tab or window is closed, we can listen to the beforeunload
event.
In the listener function, we can call removeItem
to remove the item.
For instance, we can write:
window.onbeforeunload = () => {
localStorage.removeItem(key);
return '';
};
The listener should return a string.
Selecting “selected” on Selected <select> Option in a React Component
We can set the value
prop of the select
element to set the selected option.
For instance, we can write:
<select value={chosenItem}>
<option value="A">apple</option>
<option value="B">banana</option>
<option value="O">orange</option>
</select>
We set the chosenItem
state with setState
in a class component.
Or we can use the state change function returned from the useState
method to set it.
Resize HTML5 Canvas to Fit Window
To resize the HTML5 canvas to fit the window, we can change the width and height of the canvas with JavaScript.
For instance, we can write:
`const resizeCanvas = () => {
const canvas =` document.getElementById('canvas'),
`const ctx = canvas.getContext('2d');
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
}`
window.addEventListener('resize', resizeCanvas, false);
innerWidth
sets the width to the window width and innerHeight
sets the height to the window height.
We watch the resize
event to set the dimensions.
Adding Hours to JavaScript Date Object
We can add hours to the JavaScript date object with the getTime
method to get the timestamp.
Then we add the milliseconds to the timestamp to add the number of hours we want.
For example, we can write:
date.setTime(date.getTime() + (hours * 60 * 60 * 1000));
We use setTime
to set the timestamp of the new date.
Check if the Array is Empty or does not Exist
To check if an array is empty or doesn’t exist, we can use the Array.isArray
method and check the length
property.
For instance, we can write:
if (!Array.isArray(array) || !array.length) {
// ...
}
We check if array
is an array with Array.isArray
.
Then we check if the length is 0 or not with !array.length
.
If both are true
then we know it’s not an array
If only !array.length
is true
then we know that array
is an empty array.
Conclusion
We can disable ESLint rules with comments or .eslintignore
.
The DOMSubtreeModified
is emitted when the DOM structure changed.
JavaScript objects can be created from constructors or classes.