Categories
JavaScript Answers

How to Extend the JavaScript Error Constructor?

To throw errors in our JavaScript apps, we usually through an object that’s the instance of the Error constructor.

In this article, we’ll look at how to extend the JavaScript Error constructor with our own constructor.

Create Our Own Constructor Function

One way to extend the built-in Error constructor is to create our own constructor that gets data from the Error constructor.

For instance, we can write:

function MyError(message) {
  this.name = 'MyError';
  this.message = message;
  this.stack = (new Error()).stack;
}
MyError.prototype = new Error();
throw new MyError('error occurred')

We create the MyError constructor that takes the message parameter.

We set message as the value of the message property.

And we get the stack trace from the stack property of the Error instance.

We set MyError.prototype to a new Error instance so that a MyError instance is also an Error instance.

In the constructor, we set the name which will be logged when an error is thrown.

Then we throw a MyError instance with the throw keyword.

Once the error, is thrown, we should see it in the log.

And if we log myError instanceof Error and myError instanceof MyError , we should see that both are true since we set MyError.prototype to a new Error instance.

Use the Class Syntax and extends Keyword to extend the Error Constructor

The class syntax is added to ES6 so that we can create constructors that inherit constructors easily.

However, underneath the syntactic sugar, prototypical inheritance is still used as we have in the previous example.

To extend the Error constructor, we write:

class MyError extends Error {
  constructor(message) {
    super(message);
    this.name = 'MyError';
  }
}

const myError = new MyError('error occurred')
console.log(myError instanceof Error)
console.log(myError instanceof MyError)
throw myError

We create the MyError class with the extends keyword to create a subclass of the Error class.

The constructor takes the message parameter and we pass that into the Error constructor by calling super .

We also set our own name property in the constructor.

And then we instantiate the MyError class the same way as before.

And if we use the instanceof operator on Error and MyError , we see that they’re both true .

When we throw an error, we see the message as we did before.

Conclusion

We can use regular prototypical inheritance or the class syntax to create our own constructor that inherits data from the Error constructor.

Categories
JavaScript Answers

How to Listen for Changes to HTML Elements with the contenteditable Attribute with JavaScript?

Elements with the contenteditable attribute added to it lets users edit the content inside the element.

Sometimes, we may want to listen for change events that are made to the element.

In this article, we’ll look at how to listen for changes triggered in elements that have the contenteditable attribute applied.

Listen to the input Event Emitted by the Element

When we change the content of an element that has the contenteditable attribute added, then input event will be emitted.

Therefore, we can listen to the input event of the element to listen for changes in its content.

For instance, we can write the following HTML:

<div contenteditable>
  hello world
</div>

And then we can add an event listener with the addEventListener with:

const div = document.querySelector("div")
div.addEventListener("input", (e) => {
  console.log(e);
}, false);

When we change the content in the div, we’ll see the input event listener run.

We can get the element’s attributes and styles with the e.target property.

The e.timestamp property is the time in milliseconds at which the event is created.

MutationObserver

We can also use the MutationObserver to watch for changes to the content of an element.

This is because it can listen for changes in the DOM, including any content changes in an element.

For instance, we can write:

const div = document.querySelector("div")
const observer = new MutationObserver((mutationRecords) => {
  console.log(mutationRecords[0].target.data)
})
observer.observe(div, {
  characterData: true,
  subtree: true,
})

and keep the HTML the same.

We pass in a callback with the mutationRecords object to get the mutation records.

chartacterData set to true means we watch for text content changes.

And subtree set to true means we watch for the element’s DOM subtree changes.

We get the latest content of the div with the mutationRecords[0].target.data property.

Conclusion

We can watch for changes of the content of an HTML with the contenteditable attribute applied with the MutationObserver or listen to the input event of the element.

Categories
JavaScript Answers

How to Get the Loop Counter or Index Using for-of Loop in JavaScript?

The for-of loop is an easy-to-use loop that comes with JavaScript that lets us loop through arrays and iterable objects easily.

However, there’s no way to get the index of the element being looped through with it directly.

In this article, we’ll look at how to get the loop counter or index with the for-of loop in JavaScript.

Array.prototype.forEach

One way to get the index while iterating through an array is to use the forEach method.

We can pass in a callback with the index of the item being looped through in the 2nd parameter.

So we can write:

const arr = [565, 15, 642, 32];
arr.forEach((value, i) => {
  console.log('%d: %s', i, value);
});

We call forEach with a callback that has the value with the value in arr being iterated through.

i has the index of value .

And so we get:

0: 565
1: 15
2: 642
3: 32

Array.prototype.entries

JavaScript arrays also have the entries method to return an array of arrays with the index of the item and the item itself.

For instance, we can write:

const arr = [565, 15, 642, 32];
for (const [i, value] of arr.entries()) {
  console.log('%d: %s', i, value);
}

We destructure the index and value from the array entry and then we log both values with the console log.

So we get:

0: 565
1: 15
2: 642
3: 32

as a result.

Conclusion

There are several ways we can use to loop through an array and access the index and the value of the entry during each iteration.

Categories
JavaScript Answers

How to Check if a Div Does Not Exist with JavaScript?

Sometimes, we want to check if a div does not exist with JavaScript.

In this article, we’ll look at how to check if a div does not exist with JavaScript.

Check if a Div Does Not Exist with JavaScript

To check if a div does not exist with JavaScript, we can check if the document.getElementById or document.querySelector returns a null value.

For instance, we can write:

if (!document.getElementById("given-id")) {
  console.log('not exist')
}

if (!document.querySelector("#given-id")) {
  console.log('not exist')
}

We have 2 if statements.

The first one calls document.getElementById to check if an element with the ID given-id exists.

The 2nd one calls document.querySelector to do the same thing.

They both log 'not exist' since they don’t exist.

Also, we can write:

if (document.getElementById("given-id") === null) {
  console.log('not exist')
}

if (document.querySelector("#given-id") === null) {
  console.log('not exist')
}

to do the same thing by checking explicitly if null is returned.

We should get the same result as before the elements with ID given-id doesn’t exist.

Conclusion

To check if a div does not exist with JavaScript, we can check if the document.getElementById or document.querySelector returns a null value.

Categories
JavaScript Answers

How to Convert an Integer Array into a String Array in JavaScript?

Sometimes, we want to convert an integer array to a string array in JavaScript.

In this article, we’ll look at how to convert an integer array to a string array in JavaScript.

Convert an Integer Array into a String Array in JavaScript

To convert an integer array to a string array in JavaScript, we can use the map method to do so.

For instance, we can write:

const arr = [1, 2, 3, 4, 5];
const strArr = arr.map(String)
console.log(strArr)

to create the arr number array.

Then we call map on arr with the String function as its callback.

The String function takes in the item we want to convert into a string and return the string version of the argument as a result.

Therefore strArr is:

["1", "2", "3", "4", "5"]

Conclusion

To convert an integer array to a string array in JavaScript, we can use the map method to do so.