Categories
JavaScript Answers

How to Initialize a JavaScript Date to a Particular Time Zone?

Sometimes, we may want to initialize a JavaScript date to a particular time zone.

The default time zone is UTC.

In this article, we’ll look at ways to initialize a JavaScript date into a particular time zone.

Add the Time Zone to the End of the Date String

We can add the time zone info to the end of the date string that we use to create the Date object.

For instance, we can write:

const d = new Date("2020-04-13T00:00:00.000+08:00");
console.log(d)

The +08:00 part means that the date string we have is 8 hours ahead of UTC.

So d is:

Sun Apr 12 2020 09:00:00 GMT-0700 (Pacific Daylight Time)

when we’re using a device set to the Pacific time zone.

Date.prototype.toLocaleString

The JavaScrip date object has the toLocaleString method to convert a date to a date string in the given time zone.

For instance, we can write:

const d = new Date("2020-04-13T00:00:00.000+08:00");
const dateStr = d.toLocaleString('en-US', {
  timeZone: 'America/New_York'
})
console.log(dateStr)

to do this.

We call toLocaleString on d with the locale as the first argument.

The 2nd argument is an object with the timeZone property set to 'America/New_York' so that we can return a date string in the New York time zone.

Therefore, dateStr is:

4/12/2020, 12:00:00 PM

which is the equivalent of the date and time we pass into the Date constructor in the New York time zone.

Getting the Hours

If we get the hours with getHours , then the hour returned will be the equivalent in the device’s time zone.

For instance, if we have:

const d = new Date("2020-04-13T00:00:00.000+08:00");
console.log(d.getHours())

The time in the string is midnight.

And the time zone is UTC +8.

So if we’re in the Pacific time zone, we get 9 since it’s Daylight Saving Time so it’s 7 hours behind UTC and 15 hours behind UTC +8.

Conclusion

We can initialize a date with the given time zone by adding the time zone information to the date string we use to create the Date instance in JavaScript.

Categories
JavaScript Answers

How to Convert JavaScript Map Keys to an Array?

JavaScript maps let us store key-value pairs easily in our code.

Sometimes, we may want to convert JavaScript map keys into an array.

In this article, we’ll look at how to convert JavaScript map keys into an array.

Array.from Method and Map.prototype.keys

We can call the Array.from with the keys method of a map to convert the keys of a map to an array.

The keys method return an iterator with all the keys.

And the Array.from method converts the iterator with keys into an array of keys.

For instance, we can write:

const map = new Map()
  .set('a', 1)
  .set('b', 2);
const keys = Array.from(map.keys());
console.log(keys)

We create a new Map instance to create a map.

Then we call set with the key and value that we want to set passed in in this order.

Next, we call Array.from with the return value of map.keys to return the iterator with the map keys to an array.

Therefore we get:

["a", "b"]

as the value of keys .

Spread Operator and Map.prototype.keys

Likewise, we can use the spread operator with the keys method to convert the iterator with keys to an array of keys.

For instance, we can write:

const map = new Map()
  .set('a', 1)
  .set('b', 2);
const keys = [...map.keys()];
console.log(keys)

And we get the same result for keys .

Conclusion

We can return an iterator with the map keys with the Map.prototype.keys method.

Then we can convert the iterator with keys to an array of keys either with the Array.from method or the spread operator.

Categories
JavaScript Answers

How to Declare Static Constants in ES6 Classes?

Sometimes, we may want to declare static constants in our JavaScript classes.

In this article, we’ll look at how to declare static constants in ES6 classes.

Add Getters in Our Class

To declare static constants in our ES6 classes, we can declare constants outside the class and add getters that return the constants in our class.

For instance, we can write:

const constant1 = 3,
  constant2 = 2;
class Example {
  static get constant1() {
    return constant1;
  }

  static get constant2() {
    return constant2;
  }
}

console.log(Example.constant1)
console.log(Example.constant2)

We declare constant1 and constant2 .

Then in the Example class, we create the constant1 and constant2 getters.

We add the static keyword before get so that we can make the static.

Then in the getter function, we return the constant1 and constant2 values respectively.

Likewise, we can write:

class Example {
  static get constant1() {
    return 3
  }

  static get constant2() {
    return 2
  }
}

Object.freeze(Example);
console.log(Example.constant1)
console.log(Example.constant2)

which is equivalent to what we have written above.

So when we log the values of Example.constant1 and Example.constant2 , we see 3 and 2 respectively.

Object.freeze

We can freeze the class to make the whole class immutable.

To do this, we write:

class Example {}
Example.constant1 = 3
Example.constant2 = 2
Object.freeze(Example);
console.log(Example.constant1)
console.log(Example.constant2)

We add our static properties with:

Example.constant1 = 3
Example.constant2 = 2

This works since classes are constructor functions, which are objects.

This also means we can use the Object.freeze method on Example to make the Example class immutable.

So we can log the values of the Example.constant1 and Example.constant2 properties and get their values.

We should see 3 and 2 respectively.

Conclusion

We can declare static constants in our JavaScript class by declaring static getters that returns constants declared outside the class.

Also, we can freeze the class with the Object.freeze method since it’s a regular object.

This makes the class immutable.

Categories
JavaScript Answers

How to Reject a Promise with the JavaScript async/await Syntax?

The async and await syntax lets us write promise code that runs sequentially very cleanly.

It lets us do everything that we do with regular promise code.

Sometimes, we may want to reject a promise in the async function.

In this article, we’ll look at how to reject a promise with the JavaScript async and await syntax.

Throw an Error

One way to reject a promise in an async function is to throw an error inside it.

For instance, we can write:

const fn = async () => {  
  try {  
    await Promise.resolve(1)  
    await Promise.reject('error')  
  } catch (error) {  
    throw new Error(error);  
  }  
}  
fn()

We create the fn async function that has some promise code.

In the try block, we call Promise.reject to invoke a rejected promise.

Then we throw an error within the catch block, which will catch the rejected promise.

The error value is the string we pass into the Promise.reject method.

So we should see the 'error' string logged in the console since we threw the error in the catch block.

Throwing an Error instance lets us see the stack trace of the error and the content.

We can also throw anything with the throw keyword.

So we can write:

const fn = async () => {  
  try {  
    await Promise.resolve(1)  
    await Promise.reject('error')  
  } catch (error) {  
    throw error;  
  }  
}  
fn()

to just throw the error itself without putting it into the Error constructor.

But then now the console won’t show the stack trace.

It’ll only show the error value.

Return a Rejected Promise

We can also return a rejected promise in our code.

For instance, we can write:

const fn = async () => {  
  await Promise.resolve(1)  
  return Promise.reject('error')  
}  
fn()

to return a rejected promise.

Then when we run the function, we’ll only see the value we pass into the Promise.reject method and no stack trace.

We can do the same thing with any other rejected promise.

Conclusion

There’re various ways we can use to reject a promise with the async and await syntax.

Categories
JavaScript Answers

How to Run a Function When a Page has Fully Loaded?

Sometimes, we want to run some code when our web page is fully loaded.

In this article, we’ll look at how to run a function when a page has fully loaded with JavaScript.

Listen to the load Event

The load event is triggered when a page is fully loaded.

Therefore, we can listen to the load event by attaching an event handler function to it to run code when the page is fully loaded.

For instance, we can write:

window.addEventListener('load', () => {  
  console.log("page is loaded")  
})

We call window.addEventListener to listen to the load event triggered on the page.

In the 2nd argument, we pass in a callback function that runs when the load event is triggered.

Therefore, we should see 'page is loaded' logged when the web page is loaded.

Listen to the DOMContentLoaded Event

Likewise, we can listen to the DOMContentLoaded event which is also triggered when the page is fully loaded.

So we can attach an event handler to it the same we did with the load event.

For instance, we can write:

window.addEventListener('DOMContentLoaded', () => {  
  console.log("page is loaded")  
})

to run the callback in the 2nd argument when the page is fully loaded.

Therefore, we should see 'page is loaded' logged when the web page is loaded.

Set the window.onload Method

We can set the window.onload method to a function we want to run code when the page is fully loaded.

This is because window.onload runs when the page is fully loaded.

To do this, we write:

window.onload = () => {  
  console.log("page is loaded")  
}

We just set the onload property to a function we want to run when the page is loaded.

Therefore, we should see 'page is loaded' logged when the web page is loaded.

Conclusion

There are several ways we can use to run a function when a web page fully loaded with JavaScript.