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.
Print a Circular Structure in a JSON-like Format
We can use the util
library to print circular structures.
It has an inspect
method that lets us print these structures.
So we can write:
console.log(util.inspect(obj));
to do that.
There’s also the circular-json
package that does the same thing.
We install it by running:
npm i --save circular-json
and write:
const CircularJSON = require('circular-json');
const json = CircularJSON.stringify(obj);
There’s also the flatted
package.
We install it by running:
npm i flatted
Then we can write:
import {parse, stringify} from 'flatted';
const foo = [{}];
foo[0].foo = foo;
foo.push(foo);
stringify(foo);
Check if Object Property Exists with a Variable Holding the Property
We can use the hasOwnProperty
method or in
operator to check if a property exists.
For example, we can write:
const prop = 'prop';
if (obj.hasOwnProperty(prop)) {
//...
}
or we can write:
const prop = 'prop';
if (prop in obj) {
//...
}
Check if a User has Scrolled to the Bottom
We can check with plain JavaScript.
We write:
el.onscroll = () => {
if(el.scrollTop + el.clientHeight === el.scrollHeight) {
// ...
}
}
We run an event handler on scroll.
To check that the user scrolled to the bottom, we check that the sum of scrollTop
and clientHeight
is the same as the scrollHeight
.
scrollTop
is the number of pixels that the element is scrolled vertically.
clientHeight
is the height of the element in pixels.
Padding is included, but borders, margins, and horizontal scrollbars are excluded.
Determine Equality for Two JavaScript Objects
We use the LodashisEqual
method to check for deep equality.
For instance, we can write:
_.isEqual(object, other);
Enumerate the properties of a JavaScript Object
To enumerate the properties of a JavaScript object, we can use the for-in loop or Object.keys
.
For instance, we can write:
for (const p in obj) {
if (obj.hasOwnProperty(p)){
//...
}
}
We call hasOwnProperty
to check if a property is in an object.
This is because for-in enumerates all properties in the prototype chain.
Likewise, we can use Object.keys
:
for (const p of Object.keys(obj)) {
//...
}
We use the for-of loop instead of the for-in loop since Object.keys
returns an array of the own keys.
Converting a String to a Date in JavaScript
We can use the Date
constructor to parse a date string into a Date
instance:
const parts = '2014-04-03'.split('-');
const date = new Date(parts[0], parts[1] - 1, parts[2]);
console.log(date.toDateString());
We extract the date string’s year, month, and date.
Then we put them in the Date
constructor.
We’ve to subtract 1 from the month because month 0 is January, 1 is February, etc.
Then we get the correct date.
Detect if a Browser Window is not Currently Active
To check if a browser window is active or not, we can watch the visibilitychange
event in our code.
For instance, we can write:
document.addEventListener("visibilitychange", onchange);
Where onchange
is:
const `onchange =` () => {
if (document.hidden) {
//...
} else {
//...
}
}
We check the document.hidden
property to check if a page is hidden.
Read a File One Line at a Time in Node.js
We can use the readline
module to read a file one line at a time.
For instance, we cabn write:
const lineReader = require('readline').createInterface({
input: require('fs').createReadStream('file')
});
lineReader.on('line', (line) => {
console.log(line);
});
We use the readline
module and pass in an object with the read stream for the file.
Then listen to the line
event to get the lines.
JavaScript Equivalent to PHP isset()
PHP’s isset
function has several equivalents in JavaScript.
We can use the typeof
operator, hasOwnProperty
, or the in
operator.
For instance, we can write:
if (typeof obj.foo !== 'undefined') {
// ...
}
to check if obj.foo
is defined or not.
We can also write:
if (obj.hasOwnProperty('foo')) {
// ...
}
or:
if ('foo' in obj) {
// ...
}
Then in
operator checks if the property exists in obj
‘s prototypes, so we should be aware of that.
Conclusion
There many ways to check if a property exists.
We can use libraries to print circular JSON.
Deep equality of objects can be checked with Lodash.