Categories
JavaScript JavaScript Basics

Check If an Array Contains and Item in JavaScript

There’re a few ways to check if an array contains an item in JavaScript.

We can use the includes, some, filter, find, findIndex, or indexOf to do the check. All methods are part of the array instance.

includes

The includes method takes in a value and returns true if it’s in the array or false otherwise. The check is done with === operator.

For instance, we can call includes as follows:

const arr = [1, 2, 3];
const result = arr.includes(1);

In the code above, we called includes on arr and then check if 1 is in it.

Therefore, it should return true so result is true.

some

The some method takes a callback with the condition of the item to check for. We can use it as follows:

const arr = [1, 2, 3];
const result = arr.some(a => a === 1);

In the code above, we passed in a callback to the some method to check if any array entry, which is the value of a is 1.

It returns true if it’s in the array and false otherwise, so we should get the same result.

filter

The filter method returns and array with the items that meet the condition returned by the callback included.

For instance, we can call it as follows:

const arr = [1, 2, 3];
const result = arr.filter(a => a === 1).length > 0;

In the code above, we called the filter method with the same callback, which returns an array with 1 in it. Then we get the length property of it and the make sure it’s bigger than 0.

Therefore, we get the same result as before by calling filter and adding the length check.

find

The find method returns the first entry in the array that meets the given condition returned in the callback.

If the item isn’t found, then undefined is returned.

For instance, we can write the following:

const arr = [1, 2, 3];
const result = typeof arr.find(a => a === 1) !== 'undefined'

In the code above, we use the typeof operator to check if the array item returned by find is undefined or not. If it’s not undefined, then it’s found. Otherwise, it’s not.

Then we should get the same result as before.

findIndex

The findIndex method returns the index of the first element in the array that meets the given condition returned in the callback.

If the item isn’t found, then -1 is returned.

For instance, we can write the following code to use findIndex:

const arr = [1, 2, 3];
const result = arr.findIndex(a => a === 1) !== -1;

In the code above, we called findIndex with the same callback used in the previous examples to search if any item in the array is 1. Then we check if the returned index isn’t -1.

Therefore, it should return the same boolean result as before, which is true.

indexOf

indexOf returns the index of the item that matches the value passed in as the argument.

It returns -1 if the value isn’t found.

For instance, we can use it as follows:

const arr = [1, 2, 3];
const result = arr.indexOf(1) !== -1;

We checked the returned array against -1 so that we can check if it’s in the array.

So we should get the same results as before.

some, find and findIndex are suitable for searching for any object, while the rest are suitable for primitive values since they let search with any condition instead of just letting us pass in a value or variable.

Objects are compared with the === operator so it doesn’t compare the structure of an object.

Categories
JavaScript JavaScript Basics

Append Item to a JavaScript Array

Appending an item to an array in JavaScript is easy. There’re 2 ways to do it. Either we can use the spread operator, or we can use the array instance’s push method.

To use the spread operator, we can take the original array, spread it into a new array and put the new item at the end, and then we assign it back to the original array.

For instance, we can do that as follows:

let arr = [1, 2, 3];
arr = [...arr, 4];

In the code above, we declare the array with let so that we can do the assignment after it.

Then we append the new array entry to it by using the spread operator and then add the new entry as we did in the 2nd line and assign it back to the original array.

Now arr is [1, 2, 3, 4].

The other way is to call the push method which appends the array item in place.

To do that, we can write:

const arr = [1, 2, 3];
arr.push(4);

Now we have the same result, but we don’t have to assign the modified array back to the original array as we did with the first example, so we can use const to declare the array.

Appending an item to an array is easy with JavaScript.

Categories
JavaScript

Introduction to the JS Destructuring Syntax

The JavaScript destructuring syntax lets us set object property values and array entries as variables without doing that ourselves explicitly.

Arrays

We can destructure arrays by defining the variables on the left side and assigning an array on the right side so that the variables on the left side will be assigned the array entries as values on the right side.

The number of variables on the left side don’t need to match the number of arrays entries on the right side.

Also, we can skip values that we don’t want to assign by putting in nothing or spaces between the commas. For instance, we can destructure an array into variables as follows:

const [one, two] = [1, 2, 3];

In the code above, we defined one and two on the left side, and have 1 and 2 as the first 2 entries of the array on the right side.

So, 1 is assigned to one and 2 is assigned to two.

If we want to only assign 3 to a variable, we can write:

const [, , three] = [1, 2, 3];

Then we would get 3 assigned to three since we skipped the first 2 entries on the left side.

Also, we can assign default values to the variables on the left side, which will be assigned if nothing’s assigned to it.

For instance, we can add one as follows:

const [, , foo = 5] = [1, 2];

In the code above, we defined the foo variable and assigned 5 as the default value for it. Since we don’t have a 3rd entry in the array on the right. foo will keep its default value 5.

Objects

We can also destructure objects property values into variables using the destructuring syntax.

It assigns the value of the property with the same name as the variable name. The nesting level is also matched.

For instance, we can use the destructuring assignment with objects as follows:

const {
  foo: {
    bar
  }
} = {
  foo: {
    bar: 1
  }
}

The code above will assign foo.bar on the right side to bar on the left side since the location and name are the same.

Therefore, bar will be 1.

Like with arrays, we can assign a default value to the variable on the left side.

For instance, we can write:

const {
  foo: {
    bar = 1
  }
} = {
  foo: {}
}

In the code above, we have the default value of bar set to 1. Since the object on the right has an empty object set as the value of foo, we get that bar is 1 since there’s no value assigned to bar.

Function Arguments

We can use the destructuring syntax on function arguments.

For instance, we can write:

const name = ({
  firstName,
  lastName
}) => `${firstName} ${lastName}`

to let our name function take an object with the firstName and lastName properties. Then we can call it as follows:

name({
  firstName: 'jane',
  lastName: 'smith'
})

and we’ll get 'jane smith' returned since the firstName and lastName properties are destructured into variables in the argument.

Loops

We can decompose array entries into variables in loops if we use the for...of loop.

For instance, given the following array:

const arr = [{
    firstName: 'jane',
    lastName: 'smith'
  },
  {
    firstName: 'john',
    lastName: 'smith'
  },
]

Then we can get the firstName and lastName properties from each entry in the for...of loop as follows via destructuring:

for (const {
    firstName,
    lastName
  } of arr) {
  console.log(`${firstName} ${lastName}`)
}

Then the console will log:

jane smith
john smith

Conclusion

The JavaScript destructuring syntax is one of the best features of JavaScript that has been released in the last few years. It makes code cleaner and easier to read while saving typing.

Categories
JavaScript JavaScript Basics

Add a Timer to Run Code Between Specified Time Intervals With JavaScript

Adding a timer is easy with JavaScript. There’re 2 methods for adding a timer into our JavaScript app. One is the setTimeout function. The other is the setInterval function.

Thr setInterval function lets us run code after a given delay in milliseconds repeatedly. It’s queued to be run after the given amount of delay time and then it’ll run the callback we pass in into the main thread.

For instance, we can use it as follows:

setInterval(() => console.log('hi'), 1000);

In the code above, we passed in a callback function as the first argument of the time setInterval function and a 1000 ms interval as the second argument.

Then we should see 'hi' logged in the console log output after every second.

We can also pass in arguments to the callback by passing in more arguments after the second argument. They can be accessed in the callback in the same order.

For instance, we can do that as follows:

setInterval((greeting) => console.log(greeting), 1000, 'hi');

In the code above, we passed 'hi' as the 3rd argument of setInterval, which will let us access the argument from the greeting parameter.

Therefore, we’ll see 'hi' logged in the console log output since greeting is 'hi'.

setInterval also takes a string instead of a callback as the first argument, where the string has the code that a callback normally has.

However, this prevents performance optimizations from being done and also presents security issues since attackers can potentially inject their own code as a string into the setInterval if we aren’t careful.

If we don’t need the timer any more, we can cancel the timer by calling the clearInterval function which takes the timer ID object that’s returned by setInterval.

For instance, we can do that as follows:

const timer = setInterval((greeting) => console.log(greeting), 1000, 'hi');
clearInterval(timer);

Since we called clearInterval immediately after calling setInterval, the callback won’t be called since we disposed of our timer with clearInterval.

Categories
JavaScript JavaScript Basics

Add a Timer With JavaScript

Adding a timer is easy with JavaScript. There’re 2 methods for adding a timer into our JavaScript app. One is the setTimeout function. The other is the setInterval function.

Thr setTimeout function lets us run code after a given delay in milliseconds. It’s queue to be run after the given amount of delay time and then it’ll run the callback we pass in into the main thread.

For instance, we can use it as follows:

setTimeout(() => console.log('hi'), 1000);

In the code above, we passed in a callback function as the first argument of the time setTimeout function and a 1000 ms delay as the second argument.

Then we should see 'hi' logged in the console log output after 1 second.

We can also pass in arguments to the callback by passing in more arguments after the second argument. They can be accessed in the callback in the same order.

For instance, we can do that as follows:

setTimeout((greeting) => console.log(greeting), 1000, 'hi');

In the code above, we passed 'hi' as the 3rd argument of setTimeout, which will let us access the argument from the greeting parameter.

Therefore, we’ll see 'hi' logged in the console log output since greeting is 'hi'.

setTimeout also takes a string instead of a callback as the first argument, where the string has the code that a callback normally has.

However, this prevents performance optimizations from being done and also presents security issues since attackers can potentially inject their own code as a string into the setTimeout if we aren’t careful.

If we don’t need the timer any more, we can cancel the timer by calling the clearTimeout function which takes the timer ID object that’s returned by setTimeout.

For instance, we can do that as follows:

const timer = setTimeout((greeting) => console.log(greeting), 1000, 'hi');
clearTimeout(timer);

Since we called clearTimeout immediately after calling setTimeout, the callback won’t be called since we disposed of our timer with clearTimeout.