Categories
JavaScript Answers

What’s the Most Accurate Way to Check a JavaScript Object’s Type?

On many occasions, we would need to check for a JavaScript object’s data type because of its dynamic nature.

In this article, we’ll look at the most accurate way to check for JavaScript object’s type.

Use typeof for Primitive Values

We should use the typeof for checking primitive values except null

For instance, if we have:

console.log(typeof 1)  
console.log(typeof '')  
console.log(typeof true)  
console.log(typeof 1n)  
console.log(typeof undefined)  
console.log(typeof Symbol())

We use typeof to get the type for numbers, booleans, bigints, undefined , and symbols.

Therefore, we get:

number  
string  
boolean  
bigint  
undefined  
symbol

from the console log.

Since typeof null returns 'object' , we can’t use it to check if an expression returns null .

Use Object.getPrototypeOf to Get the Prototype of an Object

We can check the prototype of an object with the getPrototypeOf method.

For instance, if we have:

const o = {}  
const proto = Object.getPrototypeOf(o);  
console.log(proto === Object.prototype);

Then the console log logs true since an object literal inherits from Object.prototype .

We just pass in the object we get the prototype from with the Object.getPrototypeOf method.

And if we created an object from a constructor, we can do the same check.

For instance, we can write:

const o = new Date()  
const proto = Object.getPrototypeOf(o);  
console.log(proto === Date.prototype);

to check that o is created from the Date constructor.

This should also log true since o is created by instantiating Date .

Conclusion

We should use typeof to check the type of primitive values.

And we can use the Object.getPrototypeOf method to check for an object’s prototype.

Categories
JavaScript Answers

What’s the Difference Between ++x and x++ in JavaScript?

In JavaScript, we can increment the value of a numeric variable in 2 ways.

We can put ++ before or after the variable.

They look similar but they’re different.

In this article, we’ll look at the differences between ++x and x++ in JavaScript.

The difference between ++x and x++ is the ++x increments the variable and returns the new value of x as the value.

For instance, if we write:

let x = 1  
console.log(++x)  
console.log(x)

Then we see that both console logs log 2.

On the other hand, x++ increments the variable but it doesn’t return the new value of x as the value.

For instance, if we have:

let x = 1  
console.log(x++)  
console.log(x)

Then we see that the first console log logs 1, and the 2nd console log logs 2.

Conclusion

Even though ++x and x++ looks similar, they’re different.

++x increments the variable and returns the new value of x as the value.

While x++ increments the variable but it doesn’t return the new value of x as the value.

Categories
JavaScript Answers

How to Loop Through a Date Range with JavaScript?

Sometimes, we want to loop through a date range with JavaScript.

In this article, we’ll look at how to loop through a date range with JavaScript.

Using a while Loop

One way to loop through a date range with JavaScript is to use a while loop.

We can create variables for the start and end dates.

Then we can increment the start date until it reaches the end date.

To do this, we write:

const start = new Date("02/05/2020");
const end = new Date("02/10/2020");

let loop = new Date(start);
while (loop <= end) {
  console.log(loop);
  let newDate = loop.setDate(loop.getDate() + 1);
  loop = new Date(newDate);
}

We have the start and end variables with the start and end date respectively.

Then we create the loop variable that we use as the looping variable.

We increment the date of loop until it reaches end .

We do the incrementing by calling setDate with the loop.getdate() + 1 .

getDate lets us get the day of the month.

We assign the returned date to loop to increment it.

Therefore, we get:

Wed Feb 05 2020 00:00:00 GMT-0800 (Pacific Standard Time)
Thu Feb 06 2020 00:00:00 GMT-0800 (Pacific Standard Time)
Fri Feb 07 2020 00:00:00 GMT-0800 (Pacific Standard Time)
Sat Feb 08 2020 00:00:00 GMT-0800 (Pacific Standard Time)
Sun Feb 09 2020 00:00:00 GMT-0800 (Pacific Standard Time)
Mon Feb 10 2020 00:00:00 GMT-0800 (Pacific Standard Time)

from the console log.

Conclusion

We can loop through a date range with a while loop with a looping variable that’s set to the start date.

Then we increment the looping variable until it reaches the end date.

Categories
JavaScript Answers

How to Remove HTML Elements by Class Name?

Sometimes, we want to remove HTML elements by class name in our JavaScript code.

In this article, we’ll look at how to remove elements by class name.

Get the Parent Node of the Element and call removeChild on it

We can get the parent node of the element and call removeChild on each element to remove an element.

For instance, if we have the following HTML:

<div>  
  <p class='text'>  
    foo  
  </p>  
  <p class='text'>  
    bar  
  </p>  
  <p class='text'>  
    baz  
  </p>  
</div>

Then we can write:

const text = document.querySelectorAll('.text')  
for (const el of text) {  
  el.parentNode.removeChild(el);  
}

to select all the elements with the class text .

Then we use the for-of loop to loop through each element.

In the loop body, we get the parent node of the element with the parentNode property.

Then we call removeChild with the el element to remove it.

Call the remove Method

Element objects also have the remove method to let us remove an element.

For instance, if we have the following HTML:

<div>  
  <p class='text'>  
    foo  
  </p>  
  <p class='text'>  
    bar  
  </p>  
  <p class='text'>  
    baz  
  </p>  
</div>

Then we can write:

const text = document.querySelectorAll('.text')  
for (const el of text) {  
  el.remove();  
}

to remove each element selected with the remove method.

Conclusion

We can select all the elements with a given class and then remove them one by one in the for-of loop.

Each element can be removed with the remove or removeChild method.

Categories
JavaScript Answers

How to Prepend and Append an Element with Regular JavaScript?

Sometimes, we want to prepend or append a child element in a parent element on our web page.

In this article, we’ll look at how to prepend and append an element with regular JavaScript.

Prepend an Element

We can prepend an element by using the insertBefore method.

For instance, if we have the following HTML:

<div id='parent'>  
  <p>  
    hello world  
  </p>  
</div>

Then we can prepend an element before the p element in the div by writing:

const parent = document.getElementById("parent");  
const child = document.createElement("div");  
child.innerHTML = 'Are we there yet?';  
parent.insertBefore(child, parent.firstChild);

We get the div with document.getElementById .

Then we create a div with document.createElement .

And then we add some content to the child div by setting the innerHTML property.

Finally, we call parent.insertBefore with the child element we want to insert and parent.firstChild to prepend child before the first child node of parent .

Append an Element

We can append an element into a container element by using the appendChild method.

For instance, if we have the following HTML:

<div id='parent'>  
  <p>  
    hello world  
  </p>  
</div>

Then we can add a child after the p element by writing:

const parent = document.getElementById("parent");  
const child = document.createElement("div");  
child.innerHTML = 'Are we there yet?';  
parent.appendChild(child);

The first 3 lines are the same as the previous example.

The only difference is that we call parent.appendChild with child to add child after the p element.

Conclusion

We can use the insertBefore method to prepend an element as the first child element.

And we can use the appendChild method to add a child element as the last child of the parent element.