Categories
JavaScript Answers

How to Measure the Time Taken by a JavaScript Function to Execute?

Sometimes, we’ve to find out how long a JavaScript function takes to run.

In this article, we’ll look at how to measure the time taken by a JavaScript function to run.

The performance.now() Method

One way to measure the time taken by a JavaScript to code to run is to use the performance.now method.

It returns the timestamp of the current time in milliseconds.

Therefore, to use it, we can write:

const t0 = performance.now()  
for (let i = 0; i <= 1000; i++) {  
  console.log(i)  
}  
const t1 = performance.now()  
console.log(t1 - t0, 'milliseconds')

We call performance.now before and after running our code.

Then we subtract the time after the code is run from the time before it’s run to get the run time of the code.

The console.time and console.timeEnd Methods

We can use the console.time method to start measure the time it takes for a piece of code to run.

Then we can use the console.timeEnd method to stop the measurement.

They both take a string as the argument that we can use as an identifier of what we’re measuring.

So to start the measurement, we call console.time with a string identifier.

And to end the measurement, we call console.timeEnd with the same string identifier that we used with console.time .

For instance, we can write:

console.time('loop')  
for (let i = 0; i <= 1000; i++) {  
  console.log(i)  
}  
console.timeEnd('loop')

After calling timeEnd , we should get the identifier string with the time between the console.time and console.timeEnd method calls logged in milliseconds.

Conclusion

We can measure the time it takes to run a piece of JavaScript with the performance interface or console methods.

Categories
JavaScript Answers

How to Trim Whitespace from a String in JavaScript?

Trimming whitespace from a string is an operation that we have to do sometimes.

In this article, we’ll look at how to trim whitespace from a string in JavaScript.

String.prototype.trim

A simple way to trim whitespace from a string is to use the trim method available with JavaScript strings.

We just call it by writing:

console.log(' abc '.trim())

String.prototype.trimLeft

If we only need to trim whitespace from the start of the string, we can use the trimLeft method.

For instance, we can write:

console.log(' abc '.trimLeft())

to trim whitespace from the beginning of the string.

String.prototype.trimRight

If we only need to trim whitespace from the end of the string, we can use the trimRight method.

For instance, we can write:

console.log(' abc '.trimRight())

to trim whitespace from the end of the string.

Trim String with Regex Replace

We can search for whitespace with a regex and call replace to replace all the whitespace with empty strings.

For instance, we can write:

console.log(' abc '.replace(/^\s+|\s+$/g, ''))

to trim whitespace from both the start and the end.

^\s+ is the pattern for searching for whitespace at the start of the string.

^ means the start of the string.

Likewise, \s+$ is the pattern for searching for whitespace at the end of the string.

And $ means the end of the string.

The g flag means we search for all instances of whitespace in the string.

Then to trim only starting whitespace, we write:

console.log(' abc '.replace(/^\s+/, ''))

And to trim only trailing whitespace, we write:

console.log(' abc '.replace(`/\s+$/`, ''))

And to trim all kinds of whitespace, we write:

console.log(' abc '.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, '').replace(/\s+/g, ' '))

This includes the newline character in addition to spaces since we have \n in the regex.

Conclusion

We can trim whitespace from a string with built-in JavaScript methods or with regex replace.

Categories
JavaScript Answers

How to Trigger a Button Click with JavaScript on the Enter Key in a Text Box?

If we have a text box on our web page, we may want to trigger a button click when we press the enter key.

In this article, we’ll look at how to trigger a button click with JavaScript when an enter key is pressed in a text box.

Use the click Method

We can call the click method that’s available with HTML element node objects to click an element programmatically.

For instance, we can write the following HTML:

<input type="text" id="txtSearch"  />
<input type="button" id="btnSearch" value="Search" />

Then we can write the following JavaScript code to check for the Enter keypress and trigger a button click afterwards:

const txtSearchEl = document.getElementById('txtSearch')
const btnSearchEl = document.getElementById('btnSearch')

txtSearchEl.addEventListener('keydown', (event) => {
  if (event.keyCode == 13) {
    btnSearchEl.click()
  }
})

btnSearchEl.addEventListener('click', () => {
  console.log('search button clicked')
})

We get the 2 inputs with document.getElementById .

Then we call addEventListener on txtSearchEl with the 'keydown' string as the first argument to add an event listener for the keydown event.

Next, we pass in a callback as the 2nd argument that runs when the event is triggered.

In the callback, we check the keyCode property to see if it’s 13.

If it is, then the Enter key is pressed.

Then we get the btnSearchEl HTML element node object, which is the button below the text box, and call click on it.

The click method triggers the click programmatically.

Next, we add a click listener to the btnSearchEl element node object to do something when a button is clicked.

And so when click is called, we should see 'search button clicked' logged.

We can also check the event.key property instead of the event.keyCode property.

For instance, we can write:

const txtSearchEl = document.getElementById('txtSearch')
const btnSearchEl = document.getElementById('btnSearch')

txtSearchEl.addEventListener('keydown', (event) => {
  if (event.key === "Enter") {
    btnSearchEl.click()
  }
})

btnSearchEl.addEventListener('click', () => {
  console.log('search button clicked')
})

event.key returns a string with the name of the key we pressed, so it’s more intuitive than checking a key code.

Conclusion

We can trigger a button click after a key press by watching the keydown event with an event listener.

In the event listener, we call click on the button element object to trigger the click programmatically.

And we can attach a click event listener on the button element to do something when we click on the button.

Categories
JavaScript Answers

How to Get the Last Item in an Array?

Getting the last item in an array is something that we’ve to do sometimes in our JavaScript code.

In this article, we’ll look at how to get the last item in a JavaScript array.

Use the length Property

One way to get the last item of an array is to use the length property of an array.

For instance, we can write:

const arr = ['apple', 'orange', 'grape']
const last = arr[arr.length - 1]
console.log(last)

We use arr[arr.length — 1] to get the last item in the arr array.

Since JavaScript array index starts with 0, arr.length — 1 is the index of the last item of the array.

Therefore, the value of last is 'grape' .

The Array.prototype.slice Method

We can call an array’s slice method to get a part of the array.

Therefore, we can write:

const arr = ['apple', 'orange', 'grape']
const [last] = arr.slice(-1)
console.log(last)

We call arr.slice(-1) to return an array with the last item.

-1 is the index of the last item of the array.

Then we destructure the returned array and log the value with console.log .

The console log should be the same as the previous example.

Also, we can use slice with pop to return the last item of the array.

To do this, we write:

const arr = ['apple', 'orange', 'grape']
const last = arr.slice(-1).pop()
console.log(last)

pop remove an item from the end of the array and returns that item.

So we get the same results as the previous examples.

The Array.prototype.pop Method

We can just use the pop method without slice if we don’t care that the original array will have the last element removed.

For instance, we can write:

const arr = ['apple', 'orange', 'grape']
const last = arr.pop()
console.log(last, arr)

arr.pop removes the last item from arr and returns it.

And so last is 'grape' and arr is [“apple”, “orange”] .

Conclusion

We can use the length property of a JavaScript array, or its slice and pop methods to get the last item from an array.

Categories
JavaScript Answers

How to Check if a JavaScript String has a Number?

Checking if a JavaScript string is a number is something that we have to do often.

In this article, we’ll look at how we can check if a JavaScript string is a valid number.

Write Our Own Function

We can write our own function to check if a string is a numeric string.

For instance, we can write:

const isNumeric = (str) => {
  if (typeof str !== "string") return false
  return !isNaN(str) &&
    !isNaN(parseFloat(str))
}

console.log(isNumeric('123'))
console.log(isNumeric('abc'))

First, we check whether str is a string or not with the typeof operator.

This makes sure we’re checking a string instead of something else.

Then we call isNaN to see if we can convert it to a number and then check if the converted value is a number.

If isNaN returns false , then we know there’s a good chance that it’s a number.

However, it can also just take the numeric part of a string and convert that to a number if the string starts with a number.

Therefore, we also need to call parseFloat to parse the string into a number to make sure that the whole string is a number.

Then we can do the same check with isNaN to make sure parseFloat doesn’t return NaN .

Therefore, the first console log should log true .

And the 2nd console log should log false .

Unary Plus Operator

We can also use the unary plus operator to convert a string into a number.

To do this, we write:

console.log(+'123')
console.log(+'123abc')

The first console log logs 123

And the 2nd console log logs NaN .

The only catch is that an empty string converts to 0 with the unary plus operator.

parseInt

We can convert integer strings into an integer with parseInt .

For instance, we can write:

console.log(parseInt('123'))
console.log(parseInt('123abc'))

They both log 123 since parseInt will take the numeric part of the string if it starts with a number and convert that to a number.

But the string doesn’t start with a number, then it returns NaN .

parseFloat

We can use the parseFloat method to convert strings with decimal numbers to a number.

For instance, we can write:

console.log(parseFloat('123.45'))
console.log(parseFloat('123.45abc'))

They both log 123.45 since it also takes the numeric part of a string and tries to convert that to a number if the string starts with a number.

But the string doesn’t start with a number, then it also returns NaN .

Regex Check

Since we’re working with strings, we can also use a regex to check whether the number is a numeric string.

For instance, we can write:

const isNumeric = (value) => {
  return /^-?\d+$/.test(value);
}

console.log(isNumeric('123'))
console.log(isNumeric('123abc'))

The /^-?\d+$/ regex lets us check whether a string optionally starts with a negative sign with digits after it.

Therefore the first console log logs true and the 2nd logs false .

Conclusion

We can use regex or various built-in functions and operators to check whether a string is a number or not in JavaScript.