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.

Categories
JavaScript Answers

How to Shuffle a JavaScript Array?

Shuffling a JavaScript array is something that we’ve to do sometimes.

In this article, we’ll look at how to shuffle a JavaScript array.

Swapping Array Entries Randomly

One way to shuffle a JavaScript array is to swap different array entries’ positions randomly.

For instance, we can write:

const shuffleArray = (array) => {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
}

const arr = [1, 2, 3]
shuffleArray(arr)
console.log(arr)

In the shuffleArray function, we loop through the array with the for a loop.

Then we pick a random index from the array with the Math.random method.

And then we do the swap after that by getting the entries and assigning them to the other item’s position.

array is changed in place.

So after calling shuffleArray on arr , we get an array with the items swapped in position.

This is called the Durstenfeld shuffle, which is an optimized version of the Fisher-Yates shuffle algorithm.

The sort Method and Math.random

We can use the sort method and Math.random together to shuffle an array.

For instance, we can write:

const arr = [1, 2, 3].sort(() => .5 - Math.random());
console.log(arr)

We return a random number between -0.5 and 0.5 in the callback to lets us shuffle the array.

This is because if the returned number is negative, then the position of 2 elements it’s iterating through stays the same.

Otherwise, they’re swapped.

However, this is biased and it’s also slow.

But this is the easiest way to shuffle an array with JavaScript.

Conclusion

There’re a few ways to shuffle an array with JavaScript.

They all needs the Math.random method to pick a random number.

Categories
JavaScript Answers

How to Check if an Object has a Specific Property in JavaScript?

JavaScript objects are created dynamically.

This means that we may not know what content is in a JavaScript object.

Therefore, we’ve to find ways to check if an object contains a specific property.

In this article, we’ll look at how to check if an object has a specific property in JavaScript.

The hasOwnProperty Method

The hasOwnProperty is a method that are inherited from the Object.prototype .

Most objects inherit from them unless we specify them not to be inherited from it.

Therefore, we can write:

const obj = {
  a: 1,
  b: 2,
  c: 3
}

console.log(obj.hasOwnProperty('a'))
console.log(obj.hasOwnProperty('d'))

to call hasOwnProperty with the property name string.

The first console log should log true since a is in obj .

The second console log should log false since d is not in obj .

The hasOwnProperty method is inherited from Object.prototype , so it can easily be overwritten by other pieces of code.

To avoid this issue, we can call hasOwnProperty with call by writing:

const obj = {
  a: 1,
  b: 2,
  c: 3
}

console.log(Object.prototype.hasOwnProperty.call(obj, 'a'))
console.log(Object.prototype.hasOwnProperty.call(obj, 'd'))

We call hasOwnProperty with Object.prototype.hasOwnProperty.call which can’t be overwritten like with the hasOwnProperty method.

The first argument is the value of this , which should be set to the object we’re checking the property for.

And the 2nd argument is the property name string itself, which is the first argument of hasOwnProperty when we call it the first way.

Therefore, we should get the same result as before.

The in Operator

The in operator lets us check for non-inherited and inherited properties.

It’ll return true if there’s an inherited or non-inherited property with the given property name.

For instance, if we have:

const obj = {
  a: 1,
  b: 2,
  c: 3
}

console.log('a' in obj)
console.log('hasOwnProperty' in obj)

Then they both log true since a is in obj itself.

And hasOwnProperty is inherited from Object.prototype .

Lodash has Method

We can also use the Lodash has method to check if a property is a non-inherited property of an object.

For instance, if we write:

const obj = {
  a: 1,
  b: 2,
  c: 3
}

console.log(_.has(obj, 'a'))
console.log(_.has(obj, 'hasOwnProperty'))

Then the first console log logs true .

And the 2nd console log logs false .

Conclusion

There’re many ways to check if a property is in an object.

We can also distinguish them between inherited and non-inherited properties.

Categories
JavaScript Answers

How to Detect an “Invalid Date” Date Instance in JavaScript?

If we’re trying to parse JavaScript dates, sometimes we may get ‘invalid date’ values.

If we try to parse invalid date values, then our JavaScript program may crash.

In this article, we’ll look at how to detect an ‘invalid date’ date instance with JavaScript.

instanceof and isNaN

We can combine the use of the instanceof operator and the isNaN function to check for invalid dates.

The instanceof operator lets us whether an object is created from the Date constructor.

And the isNaN function lets us check whether the object converts to a timestamp when we try to cast it to a number.

isNaN tries to cast an object to a number before checking if it’s a number.

For example, we can write:

const isValidDate = (d) => {
  return d instanceof Date && !isNaN(d);
}

const validDate = new Date(2021, 1, 1)
const invalidDate = new Date('abc')
console.log(isValidDate(validDate))
console.log(isValidDate(invalidDate))

to create the isValidDate function which returns the expression d instanceof Date && !isNaN(d); to do both checks.

Then we can call it with validDate and invalidDate , which are valid and invalid date objects respectively.

Date.parse

We can also use the Date.parse method to try to parse a Date instance into a date.

For instance, we can write:

const validDate = new Date(2021, 1, 1)
const invalidDate = new Date('abc')
console.log(!isNaN(Date.parse(validDate)))
console.log(!isNaN(Date.parse(invalidDate)))

Date.parse returns a UNIX timestamp if it’s a valid date.

So if we pass in validDate to Date.parse , we should get an integer timestamp returned.

And if we pass in invalidDate , we should get NaN returned.

This means we can use isNaN again to check whether the result returned by Date.parse is a number.

instanceof and isFinite

We can call isFinite instead of isNaN in our valid date check.

This is because isFinite only returns true if anything that can be converted to a finite number is passed in as an argument.

To use it, we write:

const isValidDate = (d) => {
  return d instanceof Date && isFinite(d);
}
const validDate = new Date(2021, 1, 1)
const invalidDate = new Date('abc')
console.log(isValidDate(validDate))
console.log(isValidDate(invalidDate))

This way, we can get rid of the negation before isNaN , which makes the isValidDate function easier to read.

Conclusion

We can check for valid date objects with the instanceof operator, isNaN , isFinite , or Date.parse .