javascript

How to Add Days to a Date in JavaScript

1. Date setDate() and getDate() Methods

To add days to a Date in JavaScript, call the getDate() method on the Date to get the day of the month, then call the setDate() method on the Date, passing the sum of getDate() and the number of days to add.

For example:

function addDays(date, days) {
  date.setDate(date.getDate() + days);
  return date;
}

const date = new Date('2022-05-15T00:00:00.000Z');

const newDate = addDays(date, 5);

// 2022-05-20T00:00:00.000Z
console.log(newDate);

Our addDays() function takes a Date object and the number of days to add as arguments, and returns the same Date object with the newly added days.

The Date getDate() method returns a number between 1 and 31 that represents the day of the month of the particular date.

The Date setDate() method changes the day of the month of the Date object to the number passed as an argument.

If the number you specify would change the month or year of the Date, setDate() automatically updates the Date information to reflect this.

// April 25, 2022
const date = new Date('2022-04-25T00:00:00.000Z');

date.setDate(40);

// May 10, 2022
console.log(date); // 2022-05-10T00:00:00.000Z

console.log(date.getDate()); // 10

April has only 30 days, so passing 40 to setDate() increments the month by one and sets the day of the month to 10.

Avoiding Side Effects

The setDate() method mutates the Date object it is called on. This introduces a side effect into our addDays() function. To avoid modifying the passed Date and create a pure function, make a copy of the Date and call setDate() on this copy, instead of the original.

function addDays(date, days) {
  const dateCopy = new Date(date);
  dateCopy.setDate(date.getDate() + days);
  return dateCopy;
}

const date = new Date('2022-05-15T00:00:00.000Z');

const newDate = addDays(date, 5);

console.log(newDate); // 2022-05-20T00:00:00.000Z

// original not modified
console.log(date); // 2022-05-15T00:00:00.000Z

Functions that don’t modify external state (i.e., pure functions) tend to be more predictable and easier to reason about. This makes it a good practice to limit the number of side effects in your programs.

2. date-fns addDays() Function

Alternatively, you can use the pure addDays() function from the date-fns NPM package to quickly add days to a Date.

import { addDays } from 'date-fns';

const date = new Date('2022-05-15T00:00:00.000Z');

const newDate = addDays(date, 5);

console.log(newDate); // 2022-05-20T00:00:00.000Z

// original not modified
console.log(date); // 2022-05-15T00:00:00.000Z

How to Check if a String Contains Only Letters and Spaces in JavaScript

1. The RegExp test() Method

To check if a string contains only letters and spaces in JavaScript, call the test() method on this regex: /^[A-Za-z\s]*$/. If the string contains only letters and spaces, this method returns true. Otherwise, it returns false.

function onlyLettersAndSpaces(str) {
  return /^[A-Za-z\s]*$/.test(str);
}

const str1 = 'contains_underscore';
const str2 = 'only letters and spaces';

console.log(onlyLettersAndSpaces(str1)); // false
console.log(onlyLettersAndSpaces(str2)); // true

The RegExp test() method searches for a match between the regular expression and a specified string.

The / and / characters are used to start and end the regular expression.

The ^ character matches the beginning of the string, while the $ character matches the end of the string.

The square brackets ([]) are used to match any one of multiple specified patterns. In our example, we specify three patterns: A-Za-z, and \s. A-Z matches any uppercase letter, a-z matches any lowercase letter, and 0-9 matches any digit.

The * character matches zero or more occurrences of a particular pattern. We add it after the square brackets to match any of the patterns in the brackets as many times as possible.

How to Check if a String Contains At Least One Letter and One Space

The regular expression we used makes the method return true if the string contains only letters or only spaces.

const str1 = 'OnlyLetters';
const str2 = '  '; // only spaces
const str3 = 'letters and spaces';

console.log(onlyLettersAndSpaces(str1)); // true
console.log(onlyLettersAndSpaces(str2)); // true
console.log(onlyLettersAndSpaces(str3)); // true

To make sure the string contains at least one letter and one space, we’ll need to match the string against a regex that matches at least one letter (/[A-Za-z]/), and another that matches at least one space /\s/.

function atLeastOneLetterAndSpace(str) {
  return (
    /^[A-Za-z\s]*$/.test(str) &&
    /[A-Za-z]/.test(str) &&
    /\s/.test(str)
  );
}

const str1 = 'OnlyLetters';
const str2 = '  '; // Only spaces
const str3 = 'letters and spaces';

console.log(atLeastOneLetterAndSpace(str1)); // false
console.log(atLeastOneLetterAndSpace(str2)); // false
console.log(atLeastOneLetterAndSpace(str3)); // true

2. The String match() Method

We can also use the String match() method to check if a string contains only letters and spaces.

function onlyLettersAndSpaces(str) {
  return Boolean(str?.match(/^[A-Za-z\s]*$/));
}

const str1 = 'contains_underscore';
const str2 = 'only letters and spaces';

console.log(onlyLettersAndSpaces(str1)); // false
console.log(onlyLettersAndSpaces(str2)); // true

The String match() method returns an array of all the matches of a regular expression in a string. If there are no matches, it returns null.

const regex = /^[A-Za-z\s]*$/;

const str1 = 'contains_underscore';
const str2 = 'only letters and spaces';

// null
console.log(str1?.match(regex));

/**
[
  'only letters and spaces',
  index: 0,
  input: 'only letters and spaces',
  groups: undefined
]
 */
console.log(str2?.match(regex));

We pass the result of match() to the Boolean constructor to convert it to a BooleanBoolean() converts truthy values to true, and falsy values to false.

In JavaScript, there are six falsy values: undefinednullNaN0'' (empty string), and false. Every other value is truthy.

console.log(Boolean(undefined)); // false
console.log(Boolean(['letters'])); // true
console.log(Boolean(null)); // false
console.log(Boolean(5)); // true

We used the optional chaining operator (?.) on the string variable. If the variable is nullish (undefined or null), instead of an error being thrown when we try to call the match() method on it, this operator will prevent the method call and return undefined.

const str = null;

console.log(str?.match(/^[A-Za-z\s]*$/)); // undefined

How to Check if a String Contains Only Letters and Numbers in JavaScript

1. The RegExp test() Method

To check if a string contains only letters and numbers in JavaScript, call the test() method on this regex: /^[A-Za-z0-9]*$/. If the string contains only letters and numbers, this method returns true. Otherwise, it returns false.

function onlyLettersAndNumbers(str) {
  return /^[A-Za-z0-9]*$/.test(str);
}

const str1 = 'number60';
const str2 = 'contains spaces';
const str3 = 'has special characters !@#$%^&';

console.log(onlyLettersAndNumbers(str1)); // true
console.log(onlyLettersAndNumbers(str2)); // false
console.log(onlyLettersAndNumbers(str3)); // false

The RegExp test() method searches for a match between the regular expression and a specified string.

The / and / characters are used to start and end the regular expression.

The ^ character matches the beginning of the string, while the $ character matches the end of the string.

The square brackets ([]) are used to match any one of multiple specified patterns. In our example, we specify three patterns: A-Z, a-z, and 0-9.

A-Z matches any uppercase letter.

a-z matches any lowercase letter.

0-9 matches any digit.

The * character matches zero or more occurrences of a particular pattern. We add it after the square brackets to match any of the patterns in the brackets as many times as possible.

2. The String match() Method

We can use the String match() method in place of RegExp test().

function onlyLettersAndNumbers(str) {
  return Boolean(str.match(/^[A-Za-z0-9]*$/));
}

const str1 = 'number60';
const str2 = 'contains spaces';
const str3 = 'has special characters !@#$%^&';

console.log(onlyLettersAndNumbers(str1)); // true
console.log(onlyLettersAndNumbers(str2)); // false
console.log(onlyLettersAndNumbers(str3)); // false

The String match() method returns an array of all the matches of a regular expression in a string. If there are no matches, it returns null.

const str1 = 'number60';
const str2 = 'contains spaces';
const str3 = 'has special characters !@#$%^&';

// [ 'number60', index: 0, input: 'number60', groups: undefined ]
console.log(str1.match(/^[A-Za-z0-9]*$/));

console.log(str2.match(/^[A-Za-z0-9]*$/)); // null
console.log(str3.match(/^[A-Za-z0-9]*$/)); // null

We pass the result of match() to the Boolean constructor to convert it to a Boolean. Boolean() converts truthy values to true, and falsy values to false.

In JavaScript, there are six falsy values: undefined, null, NaN, 0, '' (empty string), and false. Every other value is truthy.

console.log(Boolean(undefined)); // false
console.log(Boolean(['number60'])); // true
console.log(Boolean(null)); // false
console.log(Boolean(5)); // true

Removing Letters and Numbers from a String

If you would like to remove any letters and numbers from the string, you can use the String replace() method.

function removeLettersAndNumbers(str) {
  return str.replace(/[A-Za-z0-9]/g, '');
}

const str1 = 'number!60 ?';
const str2 = '#wel_com%e';

console.log(removeLettersAndNumbers(str1)); // ! ?
console.log(removeLettersAndNumbers(str2)); // #_%

The String replace() method returns a new string with some or all matches of a specified pattern replaced by a replacement. We use an empty string ('') as the replacement to have all the letters and numbers removed in the resulting string.

We use the g (global) flag to match all the occurrences of the pattern in the string. If we don’t specify this flag, only the first match of a letter or number will be removed.

function removeLettersAndNumbers(str) {
  // 'g' flag not set
  return str.replace(/[A-Za-z0-9]/, '');
}

const str1 = 'number!60 ?';
const str2 = '#wel_com%e';

console.log(removeLettersAndNumbers(str1)); // umber!60 ?
console.log(removeLettersAndNumbers(str2)); // #el_com%e

How to Fix the Cannot Find Name ‘it’ Jest Error in TypeScript

To fix the “cannot find name ‘it'” Jest error, install the type definitions for Jest with npm i -D @types/jest and add them to the types array in your tsconfig.json file.

This error occurs when you try to use the it() function from Jest in a TypeScript file, but TypeScript cannot find the type definitions for the package.

Here is an example of the error occurring in Visual Studio Code:

The "cannot find name it" Jest error occurring in Visual Studio Code.

index.ts

// Cannot find name 'it'. Do you need to install type
// definitions for a test runner? Try 
// `npm i --save-dev @types/jest` or 
// `npm i --save-dev @types/mocha`. ts(2582)

describe('example', () => {
  it('adds two numbers together', () => {
    expect(2 + 2).toBe(4);
  });
});

Install the type definitions for Jest by running the following command in a terminal at the root directory of your project:

npm i -D @types/jest

If you didn’t already have Jest installed, you can install it with the type definitions in one command:

npm i -D @types/jest jest

Add typings to tsconfig.json types array

In some cases, this is all you need to do and the error will stop. But if it persists, you’ll need to add jest to the types array in your tsconfig.json file, so it looks something like this:

tsconfig.json

{
  "compilerOptions": {
    "types": [
      // ... other types
      "jest"
    ]
    // ..other settings
  }
}

Include test files

If the error still doesn’t go away, ensure that TypeScript does not ignore the directory containing your test files. If you’ve set the include array in your tsconfig.json file, ensure the patterns specified in this array match the directory where your test files are located.

For example, if your tests are located in a src directory, TypeScript will detect them with a configuration like this:

tsconfig.json

{
  "compilerOptions": {},
  "include": ["src/**/*"],
}

But if they’re located in a tests directory, we’ll need to add an additional glob pattern to make TypeScript detect them:

tsconfig.json

{
  "compilerOptions": {},
  "include": [
    "src/**/*",
    "tests/**/*"
  ],
}

We can also include glob patterns to match test files with a specific ending or extension. For example, we can include all files ending with “.spec.ts” and “.test.ts” with the following configuration:

tsconfig.json

{
  "compilerOptions": {},
  "include": [
    "src/**/*",
    "**/*.spec.ts",
    "**/*.test.ts"
  ],
}

How to Convert a String of Numbers to an Array in JavaScript

In this article, we’ll learn how to easily convert a string containing a comma-separated list of numbers to an array of these numbers in JavaScript.

String split() and Array map() Methods

To convert a string of numbers to an array, call the split() method on the string, passing a comma (,) as an argument, to get an array of the string representation of the numbers. Then use the map() method to transform each string in the array into a number. For example:

const str = '1,2,3,4';

const nums = str.split(',').map(Number);
console.log(nums); // [ 1, 2, 3, 4 ]

The String split() method divides a string into an array of characters using the specified separator. We pass a comma to separate the stringified numbers into separate elements in the resulting array.

console.log('1,2,3,4'.split(',')); // [ '1', '2', '3', '4' ]

The Array map() method creates a new array from the result of calling a callback function on each element of the original array. We pass the Number constructor to map(), so Number() will be called on each string in the array to convert it to a number.

We can use the map() method more explicitly like this:

const str = '1,2,3,4';

const nums = str.split(',').map((item) => Number(item));
console.log(nums); // [ 1, 2, 3, 4 ]

You might prefer this approach since it lets you see exactly what arguments you’re passing to the callback function. This can prevent bugs in situations where the callback function behaves differently depending on the number of arguments passed.

Apart from the Number constructor, we can also convert each item in the string array to a number with parseInt():

const str = '1,2,3,4';

const nums = str.split(',').map((item) => parseInt(item, 10));
console.log(nums); // [ 1, 2, 3, 4 ]

parseInt() parses a string and returns an integer of the specified base. We pass 10 as the second argument, so parseInt() uses base 10 to parse the string.

We can also use the unary operator (+) in place of parseInt() or Number(). This operator converts a non-numeric value into a number.

const str = '1,2,3,4';

const nums = str.split(',').map((item) => +item);
console.log(nums); // [ 1, 2, 3, 4 ]

How to Get the Length of a Number in JavaScript

1. length Property of String Representation

To get the length of a number, call the toString() method on the number to convert it to a string, then access the length property of the string, i.e., num.toString().length.

const num1 = 12345;
const num2 = 524;

console.log(num1.toString().length); // 5
console.log(num2.toString().length); // 3

We call the toString() method on the number to get its string representation.

const num1 = 12345;
const num2 = 524;

console.log(num1.toString()); // '12345'
console.log(num2.toString()); // '524'

String objects have a length property that returns the number of characters (UTF-16 code units) in a string. We use this to get the length of the number.

Getting the Length of Floats

For floating point numbers, the decimal point will be included when accessing the length property of the string representation of the float.

const float1 = 123.45; // 5 digits
const float2 = 524.1; // 4 digits

console.log(float1.toString().length); // 6
console.log(float2.toString().length); // 5

To avoid this and get the actual number of digits in the float, simply subtract 1 from length.

const float1 = 123.45; // 5 digits
const float2 = 524.1; // 4 digits

console.log(float1.toString().length - 1); // 5
console.log(float2.toString().length - 1); // 4

2. Math.ceil() and Math.log10() Methods

We can also use a purely mathematical approach to get the length of a number:

function getNumberLength(num) {
  return Math.ceil(Math.log10(num + 1));
}

const num1 = 12345;
const num2 = 524;

console.log(getNumberLength(num1)); // 5
console.log(getNumberLength(num2)); // 3

The Math.log10() method returns the logarithm of a number to the base 10.

console.log(Math.log10(12345)); // 4.091491094267951

And the Math.ceil() method rounds a number up to the next largest integer.

console.log(Math.ceil(4.091491094267951)); // 5

Unfortunately, this method doesn’t work for floats. It only returns the number of digits before the decimal point.

function getNumberLength(num) {
  return Math.ceil(Math.log10(num + 1));
}

const float1 = 123.45; // 5 digits
const float2 = 524.1; // 4 digits

console.log(getNumberLength(float1)); // 3
console.log(getNumberLength(float2)); // 3

How to Get the Substring Between Two Characters in JavaScript

1. String substring(), indexOf() and lastIndexOf() Methods

To get the substring of a string between two of its characters in JavaScript, call the slice() method on the string, passing the index after the first occurrence of the first character as the first argument, and the index of the last occurrence of the second character as the second argument. For example:

function getSubstring(str, char1, char2) {
  return str.substring(
    str.indexOf(char1) + 1,
    str.lastIndexOf(char2)
  );
}

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, ':', ';');
console.log(substr1); // two

const str2 = 'one?two!three';
const substr2 = getSubstring(str2, '?', '!');
console.log(substr2); // two

The String indexOf() method returns the position of the first occurrence of a value in a string. On the other hand, lastIndexOf() returns the position of the last occurrence of a value in a string.

The String substring() method returns the portion of a string between the start and end indexes, specified by the first and second arguments respectively. We add 1 to the result of indexOf() because we don’t want the first character to be included in the substring that we’re trying to get. However, we don’t need to subtract 1 from the result of lastIndexOf(), because substring() already excludes the character at the specified end index.

If the value doesn’t exist in the string, both indexOf() and lastIndexOf() will return -1. This means that when the first character doesn’t exist in the string, all of the string from the start to the last occurrence of the second character will be included in the string.

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, '-', ';');
console.log(substr1); // one:two

Also, when the second character doesn’t exist, all of the string from the beginning to the first occurence of the first character will be included in the string.

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, ':', '-');
console.log(substr1); // one

Depending on our use case, this might not be what we want. If we want an empty string ('') to be returned when either of the characters doesn’t exist, we’ll need to explicitly check for this:

function getSubstring(str, char1, char2) {
  const char1Index = str.indexOf(char1);
  const char2Index = str.lastIndexOf(char2);
  if (char1Index === -1) return '';
  if (char2Index === -1) return '';
  return str.substring(char1Index, char2Index);
}

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, '-', ';');
console.log(substr1); // '' (empty string)

const substr2 = getSubstring(str1, ':', '-');
console.log(substr2); // '' (empty string)

2. String split(), Array slice(), and Array join() Methods

Here’s another way to get the substring of a string between two of its characters:

function getSubstring(str, char1, char2) {
  return str
    .split(char1)
    .slice(1)
    .join('')
    .split(char2)
    .slice(0, -1)
    .join('');
}

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, ':', ';');
console.log(substr1); // two

const str2 = 'one?two!three';
const substr2 = getSubstring(str2, '?', '!');
console.log(substr2); // two

The String split() method divides a string using a specified separator.

const str1 = 'one:two;three';

// [ 'one', 'two;three' ]
console.log(str1.split(':')); 

The Array slice() methods extracts the elements of an array between the start and end indexes, which are specified by the first and second arguments respectively. We pass 1 as the first argument without specifying a second, so slice() extracts from the element at index 1 to the end of the string.

// ['two;three'];
console.log([ 'one', 'two;three' ].slice(1));

We call the Array join() method on the result of slice() to concatenate the elements of the array into a string.

const str1 = 'one:two;three';

// two;three
console.log(['two;three'].join(''));

We split this result again, this time by the second character.

// ['two', 'three'];
console.log('two;three'.split(';'));

We call slice() on the array resulting from this split, passing 0 and -1 as arguments, to copy all the array elements except the last one to a new array.

// [ 'two' ]
console.log(['two', 'three'].slice(0, -1));

Finally, we call join() on this result to get the string between the two characters.

Unlike the first method, this approach handles the case where one of the characters is not in the string by returning an empty string.

function getSubstring(str, char1, char2) {
  return str
    .split(char1)
    .slice(1)
    .join('')
    .split(char2)
    .slice(0, -1)
    .join('');
}

const str1 = 'one:two;three';
const substr1 = getSubstring(str1, '-', ';');
console.log(substr1); // '' (empty string)

const substr2 = getSubstring(str1, ':', '-');
console.log(substr2); // '' (empty string)

How to Add Minutes to a Date in JavaScript

1. Date setMinutes() and getMinutes() Methods

To add minutes to a Date in JavaScript, call the getMinutes() method on the Date to get the minutes, then call the setMinutes() method on the Date, passing the sum of getMinutes() and the minutes to add.

function addMinutes(date, minutes) {
  date.setMinutes(date.getMinutes() + minutes);

  return date;
}

const date = new Date('2022-05-15T00:00:00.000Z');

const newDate = addMinutes(date, 10);

// 2022-05-15T00:10:00.000Z
console.log(newDate);

Our addMinutes() function takes a Date and the number of minutes to add as arguments, and returns the same Date with the newly added minutes.

The Date getMinutes() method returns a number between 0 and 59 that represents the minutes of the Date.

The Date setMinutes() method takes a number representing minutes and set the minutes of the Date to that number.

If the minutes you specify would change the hour, day, month, or year of the Date, setMinutes() automatically updates the Date information to reflect this.

// 12:00 AM on May 15, 2022
const date = new Date('2022-05-15T00:00:00.000Z');

date.setMinutes(date.getMinutes() + 150);

// 2:30 AM on May 15, 2022
console.log(date); // 2022-05-15T02:30:00.000Z

In this example, passing 150 to setMinutes() increments the Date hours by 2 (120 minutes) and sets the minutes to 30.

Avoiding Side Effects

The setMinutes() method mutates the Date object it is called on. This introduces a side effect into our addMinutes() function. To avoid modifying the passed Date and create a pure function, make a copy of the Date and call setMinutes() on this copy, instead of the original:

function addMinutes(date, minutes) {
  const dateCopy = new Date(date);
  dateCopy.setMinutes(date.getMinutes() + minutes);

  return dateCopy;
}

const date = new Date('2022-05-15T00:00:00.000Z');

const newDate = addMinutes(date, 10);

console.log(newDate); // 2022-05-15T00:10:00.000Z

// Original not modified
console.log(date); // 2022-05-15T00:00:00.000Z

Tip

Functions that don’t modify external state (i.e., pure functions) tend to be more predictable and easier to reason about. This makes it a good practice to limit the number of side-effects in your programs.

2. date-fns addMinutes()

Alternatively, you can use the pure addMinutes() function from the date-fns NPM package to quickly add minutes to a Date.

import { addMinutes } from 'date-fns';

const date = new Date('2022-05-15T00:00:00.000Z');
const newDate = addMinutes(date, 10);

console.log(newDate); // 2022-05-15T00:10:00.000Z

// Original not modified.
console.log(date); // 2022-05-15T00:00:00.000Z

How to Split a Number into an Array in JavaScript

1. Array.from() Method

To split a number into an array in JavaScript, call the Array.from() method, passing the number converted to a string as the first argument, and the Number constructor as the second, i.e., Array.from(String(num), Number). For example:

function splitIntoArray(num) {
  return Array.from(String(num), Number);
}

const arr1 = splitIntoArray(1234);
console.log(arr1); // [ 1, 2, 3, 4 ]

const arr2 = splitIntoArray(4901);
console.log(arr2); // [ 4, 9, 0, 1 ]

The static Array from() method creates a new array from an array-like object, like a String or a Set.

// [ '1', '2', '3', '4' ]
console.log(Array.from('1234'));

The second argument we pass to from() is a map function that is called on every element of the array. We pass the Number constructor function so that each item in the array will be converted to a number.

We can do this more explicitly with the Array map() instance method:

const num = 1234;

// ['1', '2', '3', '4'];
const arrOfStrs = Array.from(String(num));

const arrOfNums = arrOfStrs.map((str) => Number(str));

console.log(arrOfNums); // [ 1, 2, 3, 4 ]

2. String split() Method

We can also split a number into an array with the String split() method. To do this:

  1. Convert the number to a string.
  2. Call the split() method on the string to convert it into an array of stringified digits.
  3. Call the map() method on this array to convert each string to a number.
function splitIntoArray(num) {
  return String(num).split('').map(Number);
}

const arr1 = splitIntoArray(1234);
console.log(arr1); // [ 1, 2, 3, 4 ]

const arr2 = splitIntoArray(4901);
console.log(arr2); // [ 4, 9, 0, 1 ]

The String split() method divides a string into an array of substrings based on the specified separator. We specify an empty string ('') as the separator to split the string into an array of all its characters.

// ['1', '2', '3', '4'];
console.log('1234'.split(''));

We call map() on this string array, passing the Number constructor to convert each element to a number and create a new number array.

// [ 1, 2, 3, 4 ]
console.log(['1', '2', '3', '4'].map(Number));

Tip

This:

// [1, 2, 3, 4]
console.log(['1', '2', '3', '4'].map(Number));

produces the same results as this:

// [ 1, 2, 3, 4 ]
console.log(['1', '2', '3', '4']
  .map((str) => Number(str)));

Although you might prefer to be more explicit with the second way, so you can see exactly what callback arguments you’re passing to Number.

How to Find the Even Numbers in an Array with JavaScript

1. Array filter() Method

To find the even numbers in array with JavaScript, call the filter() method on the array, passing a callback that returns true when the element is even, and false otherwise

const numbers = [7, 10, 15, 8, 13, 18, 6];

const evens = numbers.filter((num) => num % 2 === 0);

// [10, 8, 18, 6]
console.log(evens);

The filter() method creates a new array with all the elements that pass the test specified in the testing callback function. Only even numbers have a remainder of 0 when divided by 2, so filter() returns an array of all the even numbers in the original array.

Note: filter() preserves the order of the elements from the original array.

2. Array forEach() Method

Alternatively, we can find the odd numbers in an array with the Array forEach() method. We call forEach() on the array, and in the callback, we only add an element to the resulting array if it is even.

const numbers = [7, 10, 15, 8, 13, 18, 6];

const evens = [];
numbers.forEach((num) => {
  if (num % 2 === 0) {
    evens.push(num);
  }
});

// [ 10, 8, 18, 6 ]
console.log(evens);

3. for…of Loop

We can use the for...of loop in place of forEach() to iterate through the array and find the even numbers.

const numbers = [7, 10, 15, 8, 13, 18, 6];

const evens = [];
for (const num of numbers) {
  if (num % 2 === 0) {
    evens.push(num);
  }
}

// [ 10, 8, 18, 6 ]
console.log(evens);

4. Traditional for Loop

And we can’t forget the traditional for loop:

const numbers = [7, 10, 15, 8, 13, 18, 6];

const evens = [];
for (let i = 0; i < numbers.length; i++) {
  const num = numbers[i];
  if (num % 2 === 0) {
    evens.push(num);
  }
}

// [ 10, 8, 18, 6 ]
console.log(evens);

Performance Comparison

Let’s compare the performance of these four methods using an array with 10 million elements (with elements from 1 to 10 million).

const numbers = [...Array(10000000)].map(
  (_, index) => index + 1
);

function measurePerf(label, method) {
  console.time(label);
  method();
  console.timeEnd(label);
}

measurePerf('filter', () => {
  const evens = numbers.filter((num) => num % 2 === 0);
});

measurePerf('forEach', () => {
  const evens = [];
  numbers.forEach((num) => {
    if (num % 2 === 0) {
      evens.push(num);
    }
  });
});

measurePerf('for...of', () => {
  const evens = [];
  for (const num of numbers) {
    if (num % 2 === 0) {
      evens.push(num);
    }
  }
});

measurePerf('for', () => {
  const evens = [];
  for (let i = 0; i < numbers.length; i++) {
    const num = numbers[i];
    if (num % 2 === 0) {
      evens.push(num);
    }
  }
});

Results

Average

  • filter(): 300.216 ms
  • forEach(): 286.516 ms
  • for...of: 298.750 ms
  • for: 137.778 ms

The traditional for loop consistently comes out on top in this comparison. This doesn’t mean you must use it all the time, however. It’s not very often that you need to filter through an array with 10 million elements – in typical use cases, the performance gains you’d get from the for loop will be minuscule. In most scenarios, you’d be better off using filter() due to its greater conciseness and readability, and if you prefer the functional approach, despite its slower speed.