Categories
JavaScript Answers

How to Remove Insignificant Trailing Zeros from a JavaScript Number?

Sometimes, we want to remove insignificant trailing zeroes from a JavaScript number.

In this article, we’ll look at ways to remove insignificant trailing zeroes from a JavaScript number.

Using the Number.prototype.toString Method

We can convert a number to a number string with the JavaScript number’s toString method.

The toString method will remove any insignificant trailing zeroes from the number.

For instance, if we have:

const n = 1.245000  
const noZeroes = n.toString()  
console.log(noZeroes)

Then noZeroes is '1.245' .

Using the Number.prototype.toFixed Method

We can use the JavaScript number to toFixed method to convert a number into the number string with the number of decimal places we want to show.

Then we can convert it back to a number with the parseFloat or Number functions.

For instance, we can write:

const n = 1.245000  
const noZeroes = parseFloat(n.toFixed(5));  
console.log(noZeroes)

We call toFixed with 5 to return a number with 5 decimal places.

The toFixed method automatically discards the insignificant trailing zeroes.

After that, we use parseFloat to convert the number string back to a number.

Therefore, we get the same result as the previous example.

We can replace parseFloat with Number by writing:

const n = 1.245000  
const noZeroes = Number(n.toFixed(4));  
console.log(noZeroes)

and get the same result.

Conclusion

To remove insignificant trailing zeroes from a number, we can call toFixed or toString to convert it to a number string.

And to convert the number string back to a number, we can use the parseFloat or Number functions.

Categories
JavaScript Answers

How to Match an Exact String with JavaScript?

Sometimes, we want to find an exact string within our JavaScript code.

In this article, we’ll look at how to find an exact string with JavaScript.

Using the String.prototype.match Method

We can use the JavaScript string instance’s match method to search for a string that matches the given pattern.

For instance, we can write:

const str1 = 'abc'
const str2 = 'abcd'
console.log(str1.match(/^abc$/))
console.log(str2.match(/^abc$/))

to call match with a regex that matches the exact word.

^ is the delimiter for the start of the word.

And $ is the delimiter for the end of the word.

Therefore, the regex matches the exact word in between the delimiters.

The first console log should log 'abc' as a match.

And the 2nd console log should log null .

We can convert the matched strings to an array.

For instance, we can write:

const str1 = 'abc'
console.log([...str1.match(/^abc$/)])

We use the spread operator to convert the match object to an array since the match object is an iterable object.

Conclusion

We can match an exact string with JavaScript by using the JavaScript string’s match method with a regex pattern that has the delimiters for the start and end of the string with the exact word in between those.

Categories
JavaScript Answers

How to Avoid Browser Popup Blockers with JavaScript Code?

Sometimes when we try to open a window with the window.open method, we may see the browser permission popup asking for permission to open the popup created by window.open .

In this article, we’ll look at how to avoid browser popup blockers within our JavaScript code.

Avoid Calling window.open in Async Functions

To avoid the permission popup for opening the popup, we should use avoid calling window.open in a function that returns a promise or in callbacks for functions like setTimeout , setInterval , or any other async function.

This is because, a popup can only be opened from an app without permission with direct user action.

The depth of the call chain may also matter since some older browsers requires permission is window.open isn’t called by the function that’s run immediately after a user action.

Therefore, we should call window.open within synchronous functions run as a result of direct user action to avoid the popup permission popup from showing in any browser.

We can check if a popup is blocked by checking if window.open returns null or undefined .

For instance, we can check if a popup window is blocked by writing:

const pop = (url, w, h) => {
  const popup = window.open(url, '_blank', 'toolbar=0,location=0,directories=0,status=1,menubar=0,titlebar=0,scrollbars=1,resizable=1,width=500,height=500');
  return popup !== null && typeof popup !== 'undefined'
}
console.log(pop('https://example.com'))

We call window.open with the url as the first argument and a string with some settings as the 3rd argument.

Then we return is popup isn’t null and popup isn’t undefined .

If the popup opens, then popup shouldn’t be null and it shouldn’t be undefined .

And so pop should return true if the popup opens.

Conclusion

We can avoid browser popup blockers by calling window.open in a synchronous function.

Categories
JavaScript Answers

How to Get a Subset of a JavaScript Object’s Properties?

Sometimes, we may want to get a subset of JavaScript properties from an object.

In this article, we’ll look at ways to get a subset of JavaScript object’s properties to a place where we can use them.

Object Destructuring

The shortest and easiest way to get a subset of a JavaScript object’s properties is to use the object destructuring syntax.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
};
const {
  a,
  b
} = object
const picked = {
  a,
  b
}
console.log(picked)

We have an object with properties a , b , and c .

To get the properties, we can destructure them to assign them to their own variables.

We did that with:

const {
  a,
  b
} = object

Now a is assigned to object.a .

And b is assigned to object.b .

Then we can put them into another object with:

const picked = {
  a,
  b
}

And so picked is:

{a: 1, b: 2}

We can also do destructuring in function parameters.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
};
const pick = ({
  a,
  b
}) => ({
  a,
  b
})
const picked = pick(object);
console.log(picked)

to create a pick function that returns an object with the a and b properties destructured from the object parameter.

So when we call pick with object , we get that picked is the same as before.

Lodash

We can also use Lodash’s pick method to return an object with the given properties.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
};
const picked = _.pick(object, ['a', 'b']);
console.log(picked)

We call pick with the object to extract properties from.

And the array has the property name strings we want to get.

So picked is the same as the other examples.

Array.prototype.reduce

We can use the JavaScript array reduce method to get the properties from an object and put them into another object.

For instance, we can write:

const object = {
  a: 1,
  b: 2,
  c: 3
};
const picked = ['a', 'b'].reduce((resultObj, key) => ({
  ...resultObj,
  [key]: object[key]
}), {});
console.log(picked)

We call reduce on the [‘a’, ‘b’] array which are the property name strings for the properties we want to get from object .

resultObj has the object with the picked properties.

key has the key we want to get from the array.

We return an object with resultObj spread and the key with its corresponding value appended to the end of it.

The 2nd argument of reduce is an empty object so we can spread the properties into it.

And so picked has the same result as before.

Conclusion

We can get a subset of the properties of JavaScript wit destructuring assignment, array reduce , or the Lodash pick method.

Categories
JavaScript Answers

How to Conditionally Add a Member to a JavaScript Object?

Sometimes, we want to conditionally add a member to a JavaScript object.

In this article, we’ll look at how to conditionally add a member to a JavaScript object.

Spread Operator

We can use the spread operator to spread an object into another object conditionally.

For instance, we can write:

const condition = true  
const obj = {  
  ...(condition && {  
    b: 5  
  })  
}  
console.log(obj)

We use the && operator to return the object only when condition is true .

If the object is returned then it’ll be spread into obj .

And so we get:

{b: 5}

as a result.

Instead of using the && operator, we can also use the ternary operator by writing:

const condition = true  
const obj = {  
  ...(condition ? {  
    b: 5  
  } : {})  
}  
console.log(obj)

We return an empty object when condition is false instead of null .

Object.assign

Also, we can use the Object.assign method to merge an object into another object.

For instance, we can write:

const condition = true  
const obj = Object.assign({}, condition ? {  
  b: 5  
} : null)  
console.log(obj)

We have the condition check in the 2nd argument of the Object.assign method.

We return the object only when condition is true .

Otherwise, null is returned.

Since condition is true , we have the same result for obj .

Conclusion

We can add properties to an object conditionally with the spread operator or the Object.assign method.

We can use the ternary operator or && operator to specify what to add given the condition.