Categories
JavaScript Answers

How to Convert a Date to GMT with JavaScript?

Sometimes, we want to convert a date to GMT with JavaScript.

In this article, we’ll look at how to convert a date to GMT with JavaScript.

Convert a Date to GMT with JavaScript

To convert a date to GMT with JavaScript, we can use the JavaScript date’s toUTCString method to do so.

For instance, we can write:

const gmt = new Date("Fri Jan 20 2022 11:51:36 GMT-0500").toUTCString()  
console.log(gmt)

to convert the JavaScript Date instance to a GMT date string.

Therefore, gmt is 'Thu, 20 Jan 2022 16:51:36 GMT’ .

Since the original date-time is 5 hours behind GMT, the GMT date-time is 5 hours ahead of it.

Conclusion

To convert a date to GMT with JavaScript, we can use the JavaScript date’s toUTCString method to do so.

Categories
JavaScript Answers

How to Fix the ‘Duplicate Declaration‘ Warning for Loop Variables with JavaScript?

Sometimes, we may run into the ‘duplicate declaration‘ warning for loop variables with JavaScript.

In this article, we’ll look at how to fix the ‘duplicate declaration‘ warning for loop variables with JavaScript.

Fix the ‘Duplicate Declaration‘ Warning for Loop Variables with JavaScript

To fix the ‘duplicate declaration‘ warning for loop variables with JavaScript, we should make sure we use let instead of var to declare our loop variables.

For instance, instead of writing:

for (var i = 0; i < 100; i++) {
  // ...
}

for (var i = 0; i < 500; i++) {
  // ...
}

where the i variable from both loops are hoisted to the top and so they’re counted as duplicate declarations, we write:

for (let i = 0; i < 100; i++) {
  // ...
}

for (let i = 0; i < 500; i++) {
  // ...
}

Then we declare i for both loop blocks.

Since let is block-scoped, they’re considered separate variable declarations.

Conclusion

To fix the ‘duplicate declaration‘ warning for loop variables with JavaScript, we should make sure we use let instead of var to declare our loop variables.

Categories
JavaScript Answers

How to Find the Index of an Object in an Array From a Given Object?

Sometimes, we want to find the index of an object in an array from a given object.

In this article, we’ll look at how to find the index of an object in an array from a given object.

Find the Index of an Object in an Array From a Given Object

To find the index of an object in an array from a given object, we can use the JavaScript array’s and Object.entries methods and also the JavaScript array’s every method.

JavaScript array’s entries method returns an array of arrayt with the index and entry of the array.

The Object.entries method returns an array of array of key-value pairs of an object.

And the JavaScript array’s every method returns whether every entry of an array matches a given condition.

For instance, we can write:

const indexOf = (arr, obj) => {
  for (const [index, aObj] of arr.entries()) {
    const allEqual = Object
      .entries(aObj)
      .every(([key, val]) => {
        return obj[key] === val
      })
    if (allEqual) {
      return index;
    }
  }
  return -1;
}

const obj = {
  x: 1,
  y: 2
};
const arr = [{
    x: 1,
    y: 2
  },
  {
    x: 3,
    y: 4
  }
]
const index = indexOf(arr, obj)
console.log(index)

We create the indexOf function that takes an arr array and obj object.

In it, we have a for-of loop to loop through each entry of the arr array.

Then we get the key-value pairs of each entry with the Object.entries method.

Next, we call every with the key and val key-value pair and check if they obj[key] is the same as the val value.

And we assign that value to allEqual .

If that’s true , then we return the index ,

If we loop through all the entries and found nothing, then we return -1.

Next, we call indexOf with arr and obj and get that index is 0.

Conclusion

To find the index of an object in an array from a given object, we can use the JavaScript array’s and Object.entries methods and also the JavaScript array’s every method.

JavaScript array’s entries method returns an array of arrayt with the index and entry of the array.

The Object.entries method returns an array of array of key-value pairs of an object.

And the JavaScript array’s every method returns whether every entry of an array matches a given condition.

Categories
JavaScript Answers

How to Preload Images Using JavaScript?

Sometimes, we want to preload images using JavaScript.

In this article, we’ll look at how to preload images using JavaScript.

Preload Images Using JavaScript

To preload images using JavaScript, we can create Image instances for each image URL.

For instance, we can write:

const preload = (sources) => {
  const images = [];
  for (const s of sources) {
    const image = new Image();
    image.src = s
    images.push(image)
  }
}

preload([
  'https://picsum.photos/id/0/5616/3744',
  'https://picsum.photos/id/10/2500/1667'
])

to create the preload function that takes the sources array which has an array of image URLs.

In the function, we create the images array to store the Image instances.

Then we loop through the sources with the for-of loop.

In the loop body, we create a new Image instance.

And we set the src property of it to the source entry s .

Finally, we call images.push to add the entry to images .

Conclusion

To preload images using JavaScript, we can create Image instances for each image URL.

Categories
JavaScript Answers

How to Listen for All Events on an Element with JavaScript?

Sometimes, we want to listen for all events on an element with JavaScript.

In this article, we’ll look at how to listen for all events on an element with JavaScript.

Listen for All Events on an Element with JavaScript

To listen for all events on an element with JavaScript, we can loop through the keys of the window object to see which property starts with on .

Then we can take the part of the key after on as the event name and call addEventListener with it to listen to the event.

For instance, we can write:

Object.keys(window).forEach(key => {  
  if (/^on/.test(key)) {  
    window.addEventListener(key.slice(2), event => {  
      console.log(event);  
    });  
  }  
});

to get the keys from window with Object.keys .

Then we call forEach with a callback that takes the key .

And if the key starts with on , then we call window.addEventListener on it with the key without the on part, which we get with key.slice(2) .

The 2nd argument for window.addEventListener is the event handler callback.

Now when we do anything to the browser window, we’ll see the event object logged.

Conclusion

To listen for all events on an element with JavaScript, we can loop through the keys of the window object to see which property starts with on .

Then we can take the part of the key after on as the event name and call addEventListener with it to listen to the event.