Categories
JavaScript Answers

How to Refresh a Page with JavaScript?

Refreshing a page is an operation that we have to do sometimes.

In this article, we’ll look at how we can refresh a page with JavaScript.

location.reload() with No Argument

The location.reload() method is one method that we can call to refresh a page with JavaScript.

It does the same thing as the reload button in our browsers.

This method can only be called if it’s issued from the same domain as the app itself.

history.go(0)

The history.go method lets us load a specific page from the session history.

We can use it to move forward by passing in a positive number, and move backward if we pass in a negative number.

And if we pass in 0, we can refresh the page.

history.go()

Passing in nothing to history.go is the same as passing in 0.

It’ll also refresh the page.

location.href = location.pathname

We can assign location.pathname , which has the part of the URL after the hostname.

We can assign it to location.href to trigger navigation to the same page, which is the same as refreshing the page.

location.href is the property that we can assign to navigate to the given URL.

location.replace

The location.replace replaces the current resource with the provided URL.

replace doesn’t save a record into session history if we trigger navigation with it.

For instance, we can write:

location.replace(location.pathname)

to reload the page since location.pathname has the URL path to the current page.

location.reload with true

We can call location.reload(true) to refresh a page by fetching a fresh, non-cached copy of the page HTML.

Nothing will be served from the cache.

This is the same as doing a hard refresh in the browser.

location.reload(true) behaves the same as location.reload() for browsers where the argument isn’t accepted like Google Chrome.

Conclusion

There are several ways we can refresh a page with JavaScript.

Categories
JavaScript Answers

How to Get the Length of a JavaScript Object?

Getting the length of a JavaScript object means getting the number of properties in an object.

This is something we might do sometimes.

In this article, we’ll look at how to get the length of a JavaScript object.

Object.keys

The Object.keys lets us get the non-inherited string keys of an object as an array.

This means we can use the length property of the returned array to get the length of an object.

This method has been available since ES6, so we can use it safely anywhere.

For instance, we can write:

const obj = {
  a: 1,
  b: 2
}
const size = Object.keys(obj).length;
console.log(size)

We call Object.keys with the obj object to get an array of non-inherited string keys from obj .

It doesn’t include non-enumerable properties, which are properties that we can’t loop through with the for-in loop.

Object.getOwnPropertyNames()

We can use the Object.getOwnPropertyNames() method to get all non-inherited string keys of an object, including non-inherited properties.

For instance, we can write:

const obj = {
  a: 1,
  b: 2
}
const size = Object.getOwnPropertyNames(obj).length;
console.log(size)

There’s no difference between the previous example and this one since all the properties of obj are enumerable.

However, if there’re any non-enumerable properties set for an array, then we’ll get different results because of the extra non-enumerable properties returned with Object.getOwnPropertyNames .

Symbol Keys

The 2 methods above don’t return any symbol keys.

To return symbol keys, we’ve to use the Object.getOwnPropertySymbols method.

For instance, if we have an object with symbol keys, then we can call this method by writing:

const obj = {
  [Symbol('a')]: 1,
  [Symbol('b')]: 2
}
const size = Object.getOwnPropertySymbols(obj).length;
console.log(size)

We get the size is 2 since there’re 2 symbol keys in the object.

If an object has both symbol and string keys, then we can use Object.keys or Object.getOwnPropertyNames with Object.getOwnPropertySymbols .

For instance, we can write:

const obj = {
  [Symbol('a')]: 1,
  [Symbol('b')]: 2,
  c: 3
}
const symbolSize = Object.getOwnPropertySymbols(obj).length;
const stringSize = Object.getOwnPropertyNames(obj).length;
const size = symbolSize + stringSize
console.log(size)

We add symbolSize and stringSize together to get the total number of keys in obj .

So size is 3.

Conclusion

To get the number of string keys in an object, we can use Object.getOwnPropertyNames or Object.keys .

And to get the number of symbol keys of an object, we can use Object.getOwnPropertySymbols .

Categories
JavaScript Answers

How to Format a Number with Commas as Thousands Digit Separators in JavaScript?

Formatting a number with commas as thousands digit separators is something we do to make numbers easy to read.

In this article, we’ll take a look at how to format numbers with commas as thousands digit separators in JavaScript.

Replace with Regex

We can use the replace method with a regex to add a comma every 3 digits.

To do this, we write:

const str = (1234567890).toString().replace(/B(?=(d{3})+(?!d))/g, ",");
console.log(str)

The B(?=(d{3})+ looks for groups of 3 digits before the decimal place.

The B keeps replace from adding a comma at the beginning of the string.

?= is a lookahead assertion.

It means we only match 3 digits if the 3 digit pattern is followed by a non-word boundary.

?! is a negative lookahead assertion.

It means we match the one-digit pattern only if it’s preceded by the 3 digit pattern.

So we make sure that we insert commas only if 3 digits are followed by another digit.

So we get ‘1,234,567,890’ as the value of str

The toLocaleString Method

The toLocaleString method lets us format a number to a string with commas as thousands separators automatically.

For instance, we can write:

const str = (1234567890).toLocaleString()
console.log(str)

We call toLocaleString directly on the number that we want to format.

So we get ‘1,234,567,890’ as the value of str

We can also set the locale to guarantee that the formatted value will always have the commas:

const str = (1234567890).toLocaleString('en-US')
console.log(str)

NumberFormat Constructor

We can also use the format method of a NumberFormat instance.

To use it, we write:

const nf = new Intl.NumberFormat();
const str = nf.format(1234567890);
console.log(str)

We create a Intl.NumberFormat instance.

Then we call format on the instance with a number.

Then we get the same result as the other examples.

Conclusion

We can add commas as thousands separators with a regex replace, or we can use formatter functions to do the same thing.

Categories
JavaScript Answers

How to do Object Comparison in JavaScript?

Comparing object properties and values is something that we need to do sometimes in our JavaScript code.

In this article, we’ll look at how to compare objects in JavaScript.

JSON.stringify

The JSON.stringify method lets us convert a JavaScript object into a JSON string.

Once we converted our object into a string, we can compare the stringified value against another object that’s stringified.

For instance, we can write:

const obj1 = {
  a: 1
}
const obj2 = {
  a: 1
}
console.log(JSON.stringify(obj1) === JSON.stringify(obj2))

We have 2 objects, obj1 and obj2 .

Then we call JSON.stringify on both objects and check for equality with the === operator.

The order of the properties matter since they’re going to stringified in the same order that they are in the object.

Since obj1 and obj2 are the same stringified, then the boolean expression in the last line should be true .

Comparing Each Property of an Object

We can compare each property of the objects that we want to compare.

For instance, we can write:

const obj1 = {
  a: 1
}
const obj2 = {
  a: 1
}

function objectEquals(x, y) {
  if (x === y) {
    return true;
  }

  if (!(x instanceof Object) || !(y instanceof Object)) {
    return false;
  }

  if (x.constructor !== y.constructor) {
    return false;
  }

  for (const p in x) {
    if (!x.hasOwnProperty(p)) {
      continue;
    }

    if (!y.hasOwnProperty(p)) {
      return false;
    }

    if (x[p] === y[p]) {
      continue;
    }

    if (typeof(x[p]) !== "object") {
      return false;
    }

    if (!objectEquals(x[p], y[p])) {
      return false;
    }
  }

  for (const p in y) {
    if (y.hasOwnProperty(p) && !x.hasOwnProperty(p)) {
      return false;
    }
  }
  return true;
}

console.log(objectEquals(obj1, obj2))

In the objectEquals function, we check if x and y are equal with the === operator.

If they’re equal, then we return true .

The next if block checks if either of them isn’t an object literal with the instanceof operator.

If either of them aren’t, then we return false since it’s impossible for them to be the same if either of them isn’t an object.

Next, we loop through the properties of x .

If a property p isn’t an own property of x , then we ignore it with continue .

If y doesn’t have an inherited property that is in x , then they aren’t the same, so we return false .

If x[p] and y[p] are the same, then use continue to check the new property.

If x[p] isn’t an object, we return false since it’s impossible for x and y to be equal if a primitive value isn’t equal.

Then we also have to remember to check the remaining levels of x and y for equality with objectEquals(x[p], y[p]) .

If any of them aren’t equal, then we return false .

Next, we loop through y and check if there are any non-inherited properties in y that isn’t in x .

If there is, then we know they aren’t equal and we return false .

If all the checks pass, then we return true since we know they’re definitely equal in this case.

Conclusion

We can write our own code to compare complex objects, or we can use JSON.stringify to compare 2 objects as JSON strings.

Categories
JavaScript Answers

How to Remove a Specific Item from a JavaScript Array?

Removing an item from a JavaScript array is something that we have to do often.

In this article, we’ll look at how to remove a specific item from a JavaScript array.

The indexOf and splice Methods

One way to remove an item from an array is to use the indexOf method to get the index of the item we want to remove.

Then we can use the splice method to remove an item with the given index.

For instance, we can write:

const array = [1, 2, 3];

console.log(array);

const index = array.indexOf(2);
if (index > -1) {
  array.splice(index, 1);
}

We have the array array.

Then we call indexOf to get the index of 2 in array .

And then we call splice with index and 1 to remove 1 item starting with index index .

This means we remove the item with index index in array with splice if index is bigger than -1.

indexOf returns -1 if the item doesn’t exist in array .

The filter Method

We can call filter to return an array without the item we want to remove.

For instance, we can write:

let array = [1, 2, 3];
const value = 3
array = array.filter((item) => {
  return item !== value
})

We have the array which is the array, and value which is the value want to remove from array .

Then we call filter with a callback to return item !== value .

This means that we want the array returned by item to not include the item with the value value .

Therefore, array should be [1, 2] .

Removing Multiple Items

If we want to remove multiple items, we can also use the filter method, but with a different callback.

To remove multiple items, we can write:

let array = [1, 2, 3];
const forDeletion = [2, 3]
const value = 3
array = array.filter((item) => {
  return !forDeletion.includes(item)
})
console.log(array)

We call array.filter with a callback that checks if the item isn’t in the forDeletion array.

forDeletion is an array with the items we want to delete.

So if it’s not included in forDeletion , then we want to keep them.

Since 2 and 3 in in forDeletion , that means only 1 is kept in the returned array.

Conclusion

The array instances’ includes , indexOf , splice , and filter methods are handy for removing items in an array.