Categories
JavaScript Tips

JavaScript Tips — Type Checks, Durations, and Promise Errors

Spread the love

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.

Difference between typeof and instanceof

instanceof should be used for checking if an object is an instance of a constructor.

For instance, we can write:

foo instanceof Foo;

to check if foo is an instance of the Foo constructor.

typeof should be used for checking primitive types and functions.

For instance, we can write:

typeof 1 === 'number'

or:

typeof () => {} === 'function'

and they both return true .

However typeof null returns 'object' , so we can’t use typeof to check null .

Convert an HTMLCollection to an Array

To convert an HTMLCollection to an array, we can use the Array.from method or the spread operator to convert the HTMLCollection into an array.

For instance, we can write:

const arr = Array.from(htmlCollection);

or:

const arr = [...htmlCollection];

Both ways also work with NodeLists.

Remove an Item from a JavaScript Object

To remove an item from a JavaScript object, we can use the delete operator.

For instance, we can write:

const obj = { foo: 1, bar: 2 };
delete obj.foo;

Then the foo property is removed from obj .

Open a New Window or Tab

To open a new window or tab, we can use the window.open method.

For instance, we can write:

window.open('http://example.com', '_blank');

'_blank' makes window.open open a new window.

Newline in JavaScript Alert Box

To display a new line in a JavaScript alert box, we can add the new line character to the string we pass into alert .

For instance, we can write:

alert("line 1nline 2");

Then we display 2 lines of text since we have the n newline character.

Change the Text of a span Element in JavaScript

We can changer the text of a span element by changing the textContent property.

For instance, we can write:

document.getElementById("aSpan").textContent = "new stuff";

We just get the span and set the textContent property to a new string.

Check if a User is Using IE

To check if a user is using IE, then we can check the user agent.

For instance, we can write:

const ua = window.navigator.userAgent;
const ieIndex = ua.indexOf("MSIE");

if (ieIndex >= 0 || !!ua.match(/Trident.*rv:11./))  {
  console.log('is IE');
}
else {
  console.log('not IE');
}

We get the user agent with window.navigator.userAgent .

Then we get the index of the 'MSIE' string in the user agent and see if it’s there.

We also check if there’s the word 'Trident' in it as another check.

With both together, we can check if a browser is IE or not.

Get Hours Difference Between 2 Dates in Moment.js

To get the hours different between 2 dates in moment.js, we can use the duration and diff methods.

For instance, we can write:

const duration = moment.duration(end.diff(start));
const hours = duration.asHours();

We call the duration method to get the duration from subtract the end by the start , which are both moment objects.

Then we call asHours on duration to convert the duration to hours.

Access Variable Property by Name as String in JavaScript Object

We can use the bracket nation to access a JavaScript property with a variable.

For instance, we can write:

const foo = obj['foo'];

to get the foo property of obj .

Nested properties can be accessed with multiple brackets.

For instance, if we have:

const obj = { a: 1, b: { x: 2 }};

Then we can access x by writing:

const foo = obj['b']['x'];

JavaScript Promises — reject vs. throw

We can use throw in a promise callback.

Otherwise, we use reject .

For instance, we can write:

new Promise(() => {
  throw 'error';
})

We can use throw in the callback that we pass into the Promise constructor.

throw also terminates the control flow.

We can use reject in there or anywhere else:

new Promise((resolve, reject) => {
  reject('error');
})

We call reject , but the things after it can still run if they’re there.

They can both be caught with the catch method.

Conclusion

typeof and instanceof are used for checking different things.

We can get the duration between 2 dates with moment.js.

HTMLCollection and NodeLists can be converted to arrays.

We can check the user agent to check if a user is using IE.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *