35 Built-In JavaScript Methods for Numbers and Arrays: With Definition and Examples

Table of Contents +

35 Built-In JavaScript Methods for Numbers and Arrays: With Definition and Examples

YouTube video

Everything in JavaScript is an object. Only six things are not objects: null, undefined, strings, numbers, Booleans, and symbols. Everything else is an object or can be converted to one.

The six non-object data types are called primitive data types. That’s because they are the most basic data types available in JavaScript.

Anything that’s not primitive is an object. Objects are more complex than primitive values and have properties and methods.

That includes arrays, functions, regular expressions, conditionals, objects, and any else you know about JavaScript.

So, What’s an Object?

Simply put, an object is a collection of key-value pairs. That means that all objects have a set of properties and corresponding values. Objects are used to store multiple items in a single variable.

Here’s an example:

let personName = ‘Alex’;

let person Age = 34;

let person DOB = ‘1987-06-07’;

These are three variables assigned to different properties of a person. So, instead of having three separate variables, we can group them into one “person” object.”

So, it becomes something like this:

let person = {

    name: ‘Alex’,

    age: 34,

    dob: ‘1987-06-07’

};

And we can now access these properties like this:

person.name; // returns “Alex”

person.age; // returns 34

person.dob; // returns 1987-06-07

Objects are incredibly versatile and can hold any type of data, including other objects. That makes them extremely useful for organizing and managing complex data structures.

An object can also hold a function as one of its properties. 

Here’s an example:

let person = {

    name: ‘Alex’,

    age: 34,

    getBirthYear: function() {

        return 2021 – this.age;

    }

};

console.log(person.getBirthYear());// returns 1987

getBirthYear is a function and a method. A function in the sense that it performs a specific task and returns a value, and a method in the sense that it belongs to an object.

The Difference between a function and a method also lies in the way it’s called. In the case of a function, it’s called independently by its name, while a method is called using the object it belongs to.

Objects are not limited to having only properties and methods. They can also have nested objects or arrays as their values.

Here’s an example:

let person = {

    name: ‘Alex’,

    age: 34,

    contactInfo: {

        email: ‘alex@example.com’,

        phone: 123-456-7890

    }

};

person.contactInfo.email; // returns alex@example.com

As you can see, objects are powerful data structures in JavaScript and a key concept to understand for any developer. They allow us to organize and manipulate complex data more logically and efficiently.

So, why is Almost Everything in JavaScript an Object? 

JavaScript is a multi-paradigm language, meaning it supports multiple programming styles. One of those styles is object-oriented programming (OOP). 

In OOP, objects are at the core, and everything revolves around them. This approach allows for modularity, encapsulation, and code abstraction, resulting in more efficient and maintainable programs.

Let’s use an array example to explain why almost everything in JavaScript is an object. 

let array_example= [1, 2, 3, 4, 5,]

Now go to any website, right-click on it, and select “Inspect Element”. Click on ‘Console’.

You might want to clear the console first — just right-click on it and select ‘Clear console’.

Enter the array again and click enter.

Next, try typing the array name followed by a dot (.), and you’ll see a list of built-in methods for arrays. 

array_example. // shows a list of methods available for arrays

Here are a few examples:

  • array_example.length; // returns the length of the array (5)
  • array_example.push(6); // adds 6 to the end of the array (returns [1,2,3,4,5,6]
  • array_example.pop(); // removes and returns the last element in the array (returns[1,2,3,4.5] after removing 6 from the array. 
  • array_example.splice(1, 2); // removes two elements starting at index 1

As you can see, the array is considered an object in JavaScript, and these built-in methods are properties of that object. 

They’re functions inside the object that allow us to perform certain actions on the data contained within the array. 

This is just one of the many examples of how JavaScript uses objects to organize and manipulate data.

The same applies to variables, functions, and even some primitive data types like strings and numbers. 

For example: 

let string_example = “Hello”;

string_example.length; // returns the length of the string

string_example.toLowerCase(); // converts the string to lowercase

string_example.toUpperCase(); // converts the string to uppercase

In this case, the variable ‘string_example’ is an object that contains properties and methods for manipulating strings.

Even functions can have built-in methods in JavaScript. 

For example:

function addition(num1, num2) {

  return num1 + num2;

}

addition.toString(); // returns the string version of the function

addition.call({}, 1, 2); // calls the function and sets’ this’ to an empty object

In this case, the function’ addition’ is also considered an object with its own built-in methods.

35 Commonly Used Built-In JavaScript Methods for Numbers and Arrays: With Definition and Examples

Now, let’s take a look at some commonly used built-in methods in JavaScript:

As a Side Note: Even primitive data types like strings and numbers have built-in methods in JavaScript. That’s because, behind the scenes, these primitive data types are temporarily converted into objects when a method is called on them. 

That allows JavaScript to manipulate these data types in the same way it manipulates objects, making the code more efficient and streamlined.

Method #1: A Constructor for Number Objects

In JavaScript, numbers are primitive data types. However, the number () constructor can be used to create number objects. These objects have built-in methods that can be called on them.

For example:

let num_example = 4;

let num_object = new Number(4);

typeof(num_example); // returns ‘number’

typeof(num_object); // returns ‘object’

let num_example = 4;

let num_object = new Number(4);

typeof(num_example); // returns ‘number’

typeof(num_object); // returns ‘object’

Syntax for creating a Number object:

let num_object = new Number(number); 

Note: The ‘new Number’ keyword is used to create an instance of the Number object. You also want to observe the space between the ‘new’ keyword and the ‘Number’ object. 

Method #2: toFixed(n)

This method rounds a number to ‘n’ decimal places and returns the rounded number. If the number of decimal places is not specified, it defaults to 0.

Example:

let num = 4.5678;

num.toFixed(2); // returns “4.57”

num.toFixed(); // returns “5”

 Method #3: toString()

This method converts a number to a string. It takes an optional parameter, which specifies the base of the number system that should be used to represent numeric values. The default base is 10.

Example:

let num = 10;

num.toString(); // returns “10”

num.toString(2); // returns “1010”

Method #4: toExponential(n)

This method returns a string representing the number in exponential notation with ‘n’ decimal places. If the number of decimal places is not specified, it defaults to zero. 

Example:

let num = 1000;

num.toExponential(); // returns “1e+3”

num.toExponential(2); // returns “1.00e+3”

Method #5: toLocaleString()

This method returns a string with a language-sensitive representation of the number. It takes two optional parameters, which specify the locale and formatting options for the string.

Example:

let num = 1234567890;

num.toLocaleString(); // returns “1,234,567,890”

num.toLocaleString(‘en-US’, {style: ‘currency’, currency: ‘USD’});

Method #6: valueOf()

This method returns the primitive value of a Number object. It is usually used to convert an instance of the Number object to a primitive value.

Example:

let num = new Number(1234);

num.valueOf(); // returns 1234

Method #7: toPrecision(n)

The precision method returns a string representing the number with ‘n’ significant digits. If the parameter is not specified, it defaults to as many digits as necessary to represent the value.

Example:

let num = 12.3456;

num.toPrecision(); // returns “12.3456”

num.toPrecision(3); // returns “12.3”

The Difference Between toFixed and toPrecision

The main difference between the toFixed converts a number to a string, keeping up the specified number of decimals. 

‘toFixed (0)’ tells the computer that you only want to see 0 decimals, and it doesn’t round the number.

It will round the number if you have a non-zero decimal. For example, 2.33 becomes 2 when num.toFixed(0) is called, 2.58 becomes 3.

toFixed(4) will give you four decimal places of a number. It rounds the result if necessary.

For example, 89.27934 becomes 89.2793 when toFixed(4) is used.

toPrecision formats a number to a specified number length.

For example, toprecision(3) will format a number into three numbers (e.g. 9.92675487 becomes 9.93).

If you want to format a number with a certain amount of decimals, use toFixed, and if you want to format it with a certain length (including decimals), use toPrecision.

Method #8: Number.isNaN()

The isNaN method determines whether the passed value is NaN. This method returns true or false based on the passed value.

Example:

Number.isNaN(NaN); // returns true

Number.isNaN(5); // returns false

Number.isNaN(‘str’); // returns false

Here’s an example of how this method can be used in code:

Why does x = ‘number’ return NaN as a false when it should be true? JavaScript coerces number strings into numbers when needed, like when ‘5’ is used in a math operation. Here, you’re putting strings into the isNaN() method, and it expects numbers.

What’s the Difference Between isNaN and Number.isNaN?

The `isNaN()` method is a global function that determines whether the passed value is NaN. It coerces strings into numbers when performing mathematical operations, making it suitable for checking if a string is NaN.

On the other hand, the `Number.isNaN()` returns true if a Number is not a number, and false if it is. It does not coerce strings into numbers, so the 5 string would be considered false.

To sum up, `isNaN()` is used for checking NaN values in general, while `Number.isNaN()` is more precise in determining whether a value is actually of type Number.

Method #9: Math.abs()

The Math.abs() method returns the absolute value of a number. This method takes in a number and returns its absolute value.

Example:

Math.abs(-23); // returns 23

Math.abs(10.5); // returns 10.5

Method #10: Math.max()

The Math.max() method returns the largest of the zero or more numbers passed as arguments. This method takes in one or more numbers and returns the largest number.

Example:

Math.max(1, 5, 10); // returns 10

Math.max(-3, -20, -10); // returns -3

Method #11: Math.min()

The Math.min() method returns the smallest of the zero or more numbers passed as arguments. This method takes in one or more numbers and returns the smallest number.

Example:

Math.min(1, 5, 10); // returns 1

Math.min(-3, -20, -10); // returns -20

Additional Information

It’s important to note that for methods like Math.max() and Math.min(), the arguments can also be arrays of numbers. In this case, the method will return the largest or smallest number in the array respectively.

Example:

Math.max([1, 5, 10]); // returns 10

Math.min([-3, -20, -10]); // returns -20

Array Methods

Method #12: Array.isArray()

The Array.isArray() method checks if a given value is an array. This method takes in one argument and returns a boolean value.

Example: 

Array.isArray([1, 2, 3]); // returns true 

Array.isArray(‘hello’); // returns false

Here’s how you can use this method in an if statement to perform different actions based on whether the value is an array or not:

Method #13: Array.reduce()

The array.reduce() method applies a function against an accumulator and each array value (from left to right) to reduce it to a single value. This method takes in two arguments: a callback function and an initial value for the accumulator.

The syntax:

Array.reduce((accumulator, currentValue) => accumulator + currentValue, initialValue)

Example:

let arr = [2, 3, 4];

let initialValue = 1

let x = arr.reduce((accumulator, currentValue)=> accumulator + currentValue, initialValue)

console.log(x);

In this example, the accumulator starts with a value of 1 and adds each element in the array, resulting in a final value of 10.

So, it goes 1 + 2, 3+ 3, 6+ 4. Hence, the final value is 10.

Example 2

let arr2 = [16, 70, 80];

let initialValue = 60;

let x = arr2.reduce((accumulator, currentValue)=> accumulator – currentValue, initialValue)

console.log(x);

In this example, the accumulator starts with a value of 60 and subtracts each element in the array from it, resulting in a final value of -106. 

So, it goes 60-16 = 44, 44-70 = -26, -26-80 = -106. Hence, the final value is -106.

The value on the other side of the = sign is the accumulator value. The value on the left side of + or – sign is the currentValue, which will change with each iteration.

Method #14. Array.reduceRight()

The Array.reduceRight() method is similar to the array.reduce() method, but it iterates through the array from right to left. That means that the last element in the array will be used as the initial value for the accumulator, and the first element will be used as the currentValue.

Example:

let arr = [‘a’, ‘b’, ‘c’];

let x = arr.reduceRight((accumulator, currentValue)=> accumulator + currentValue);

console.log(x)

;In this example, the reduceRight method will start with “c” as the accumulator value and add each element in reverse order. So it goes c+b+a, resulting in a final value of “cba”.

One common use case for Array.reduceRight() is when dealing with strings. Using this method, you can easily reverse a string without writing a separate function.

Example 2:

const array1 = [

    [1, 2],

    [2, 3],

    [3, 4],

  ];

const flattenedArray = array1.reduceRight((accumulator, currentValue)=> accumulator.concat(currentValue), []);

console.log(flattenedArray);

const flattened = array1.reduce((accumulator, currentValue)=> accumulator.concat(currentValue), []);

console.log(flattened);

 

The reduce and reduceRight methods can also be used to flatten arrays, reducing multiple nested arrays into a single array. That’s achieved by providing an empty initial value as the accumulator and using concat() method inside the reduceRight function.

This technique can be useful when working with large datasets or multi-dimensional arrays.

#Method #15. Array.filter()

The filter method is used to create a new array with all elements that pass the test implemented by the provided function. It takes in a callback function as an argument and returns a new array containing only the elements that meet the criteria set in the callback function.

The syntax for the filter method looks like this:

let newArray = array.filter((element, index, arr) => condition);

The callback function takes in three parameters: element (the current element being processed), index (the index of the current element), and arr (the original array). The condition can be any logic that evaluates to a boolean value. If the condition is true, then the element is included in the new array. If it’s false, then it’s not included.

Example:

const numbers = [1, 2, 3, 4, 5];

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

console.log(evenNumbers); //output: [2,4]

The filter method can also be used with objects, where the callback function checks for a specific property or value. It is a powerful method for manipulating and extracting data from arrays.

Method #16. Array.split()

The split method is used to split a string into an array of substrings based on a specified separator. It takes in the separator as an argument and returns an array containing all the substrings.

The syntax for the split method looks like this:

let newArray = string.split(separator);

The separator can be any character or sequence of characters that you want to use to split the string. If no separator is specified, the entire string will be returned as a single element in the array.

Example 1:

const sentence = “I love JavaScript”;

const words = sentence.split(” “);

console.log(words); //output: [“I”, “love”, “JavaScript”]

The returned array can then be manipulated or accessed like any other array.

Example 2

const ourAgency = ‘MediaOneMarketing’;

const ourAgencySpelling = ourAgency.split(‘’

console.log(ourAgencySpelling) //output: [“M”,”e”,”d”,”i”,”a”, “O”, “n”, “e”, “M”, “a”, “r”, “k”, “e” , “t” ,”i” ,”n” ,”g”]

Method #17. Array.charAt()

The charAt method is used to retrieve a specific character from a string, based on its index. It takes in the index as an argument and returns the character at that position.

The syntax for the charAt method looks like this:

string.charAt(index);

The index starts at 0, which represents the first character of the string. If no index is specified, the default value of 0 will be used.

Example 1:

const sentence = “I Love JavaScript”;

const firstLetter = sentence.charAt(0);

const secondLetter = sentence.charAt(1);

const eightLetter = sentence.charAt(2);

console.log(firstLetter)

console.log(secondLetter)

console.log(eightLetter)

The method considers empty spaces as characters, so be mindful of the index you provide.

Example 2:

const ourAgency = ‘MediaOneMarketing’;

const ourAgencyAbrv = ourAgency.charAt(0) + ourAgency.charAt(8); 

console.log(ourAgencyAbrv);

Method #18. Array.map()

The map method is used to create a new array by performing a specific operation on each element of the original array. It takes a callback function as an argument, specifying the operation to be performed. The syntax for this method looks like this:

array.map(function(currentValue,index,array){…});

The parameters in the callback function are optional, but you can use them to access the current element, its index in the array, and the original array itself.

Example:

const numbers = [1, 2, 3];

const multipliedNumbers = numbers.map(function(num){

    return num * 2;

});

console.log(multipliedNumbers); //output: [2, 4, 6]

Method #19. Array.find()

The find method is used to retrieve the first element in an array that satisfies a given condition. It takes in a callback function as an argument. The syntax for this method looks like this:

array.find(function(currentValue,index,array){…});

The parameters in the callback function are optional, but you can use them to access the current element, its index in the array, and the original array itself. The find method will return the first element that meets the condition specified in the callback function. If no element satisfies the condition, it will return undefined.

Example

const animals = [“dog”, “cat”, “bird”];

const foundAnimal = animals.find(function(animal){

    return animal === “cat”;

});

console.log(foundAnimal);

Method #20. Array.findIndex()

Similar to the find method, the findIndex method is used to retrieve the index of the first element in an array that satisfies a given condition. It takes in a callback function as an argument, and the syntax for this method looks like this:

array.findIndex(function(currentValue,index,array){…});

Example 1:

const numbers = [5, 10, 15];

const index = numbers.findIndex(function(num){

    return num > 10;

});

console.log(index); //output: 2

If no element satisfies the condition, the findIndex method will return -1.

Example 2:

const numbers = [5, 10, 15];

const index = numbers.findIndex(function(num){

    return num > 20;

});

console.log(index); //output: -1

Method #21: Array.push()

The push method is used to add one or more elements to the end of an array. It takes in multiple arguments, and the syntax for this method looks like this:

array.push(element1, …, elementN);

Example:

const fruits = [“apple”, “orange”];

fruits.push(“banana”, “mango”);

console.log(fruits); //output: [“apple”, “orange”, “banana”, “mango”]

Method #22: Array.pop()

The pop method is used to remove the last element from an array and return that element. It does not take in any arguments, and the syntax for this method looks like this:

array.pop();

Example: 

const numbers = [1, 2, 3, 4, 5, 6, 7];

const lastNumber = numbers.pop();

console.log(lastNumber); //output: 7

console.log(numbers); //output: [1, 2, 3, 4, 5, 6]

Method #23: Array.shift()

The shift method is used to remove the first element from an array and return that element. It does not take in any arguments, and the syntax for this method looks like this:

array.shift();

Example:

const numbers = [1, 2, 3];

const firstNumber = numbers.shift();

console.log(firstNumber); //output: 1

console.log(numbers); //output: [2, 3]

Method #24: Array.unshift()

The unshift method is used to add one or more elements to the beginning of an array. It takes in multiple arguments, and the syntax for this method looks like this:

array.unshift(element1, …, elementN);

Example:

const fruits = [“apple”, “orange”];

fruits.unshift(“banana”, “mango”);

console.log(fruits); //output: [“banana”, “mango”, “apple”, “

Method #25: Array.slice()

The slice method extracts a section of an array and returns a new array with the selected elements. It takes two arguments, the starting and ending indexes (optional). The syntax for this method looks like this:

array.slice(startIndex, endIndex);

Example:

const numbers = [1, 2, 3, 4, 5];

const slicedNumbers = numbers.slice(1, 3);

console.log(slicedNumbers); //output: [2, 3]

Method #26: Array.splice()

The splice method adds or removes elements from an array at a specific index. It takes in three arguments: the starting index, the number of elements to be removed, and the elements to be added. 

The syntax for this method looks like this:

array.splice(startIndex, deleteCount, element1, …, elementN);

Example:

const numbers = [1, 2, 3];

numbers.splice(1, 0, 4);

console.log(numbers); //output: [1, 4, 2, 3]

numbers.splice(2, 1, “a”, “b”);

console.log(numbers); //output: [1, 4, “a”, “b”]

#27. Array.sort()

The sort method sorts the elements of an array in place and returns the sorted array. It takes in an optional compare function that specifies the order in which the elements should be sorted. The syntax for this method looks like this:

array.sort(compareFunction);

Example:

const names = [‘John’, ‘Alice’, ‘Bob’];

console.log(names.sort()); //output: [‘Alice’, ‘Bob’, ‘John’]

console.log(names.sort((a, b) => a.length b.length)); //output: [‘Bob’, ‘John’, ‘Alice’] 

In the first example, the names are sorted alphabetically because no compare function is provided. In the second example, we specify a custom compare function that sorts the names by their length in ascending order. 

The expression a.length – b.length compares the length of two strings and returns a negative number if the first string is shorter, zero if they have equal length, or a positive number if the first string is longer. This results in the names being sorted by their length.

Method #28: Array.toSpliced() 

Array.toSpliced is the copying version of the splice method. It takes in two parameters, start and deleteCount, and returns a new array with the specified elements removed from the original array. The syntax for this method looks like this:

array.toSpliced(start, deleteCount);

Example:

const letters = [‘a’, ‘b’, ‘c’, ‘d’];

const splicedLetters = letters.toSpliced(1, 1);

const splicedLetters2 = letters.toSpliced(1, 2);

console.log(letters); //output: [‘a’, ‘b’, ‘c’, ‘d’]

console.log(splicedLetters); //output: [‘a’, ‘c’, ‘d’]

console.log(splicedLetters2); //output: [‘a’, ‘d’]

Method #29. Array.every()

Similar to the find method, every also takes in a callback function as an argument, but instead of returning the first match, it checks if all elements in the array satisfy the condition. If even one element fails to meet the criteria, the method returns false. The syntax for this method looks like this:

array.every(callback(element));

Example:

const numbers = [1, 2, 3];

const isGreaterThanZero = (element) => element > 0;

console.log(numbers.every(isGreaterThanZero)); //output: true

Method #30: Array.some()

This method is similar to every but returns true if at least one element in the array satisfies the condition. The syntax for this method looks like this:

array.some(callback(element));

Method #31: Array.includes()

The includes method checks if an array contains a specific value and returns true or false accordingly. It takes in two arguments, the value to search for and an optional starting index from which to begin the search. The syntax for this method looks like this:

array.includes(value, startIndex);

Example:

const pets = [‘dog’, ‘cat’, ‘fish’];

console.log(pets.includes(‘cat’)); //output: true

console.log(pets.includes(‘bird’)); //output: false

Method #32: Array.indexOf()

The indexOf method returns the index of the first occurrence of a specified value in an array. If the value is not found, the method returns -1. 

It takes in two arguments, the value to search for and an optional starting index from which to begin the search. The syntax for this method looks like this:

array.indexOf(value, startIndex);

Example:

const fruits = [‘apple’, ‘banana’, ‘orange’];

console.log(fruits.indexOf(‘banana’)); //output: 1

console.log(fruits.indexOf(‘grapes’)); //output: -1

Method #33: Array.flat()

The flat method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. The default depth is 1. It takes in one optional argument, the depth level to flatten the array to. The syntax for this method looks like this:

array.flat(depth);

Examples:

const nestedArray = [1, [2, 3], [4, 5, [6, 7]]];

console.log(nestedArray.flat()); //output: [1, 2, 3, 4, 5, [6, 7]]

console.log(nestedArray.flat(2)); //output: [1, 2, 3, 4 ,5 ,6 ,7]

Method #34: Array.flatMap()

The flatMap method first maps each element using a mapping function, then flattens the result into a new array. It combines the functionality of map and flat methods in one. The syntax for this method looks like this:

array.flatMap(callbackFn);

Example:

const numbers = [1, 2, 3];

console.log(numbers.flatMap(x => [x, x * 2])); //output: [1, 2, 2, 4, 3, 6]

In the example above, the callback function multiplies each element by 2 and returns an array with both the original number and its doubled value. Then, the flatMap method flattens this result into a new array.

Method #35: Array.forEach()

The forEach method executes a provided function once for each array element. It does not return anything and only iterates over the array’s values. The syntax for this method looks like this:

array.forEach(callbackFn);

Example:

const animals = [‘cat’, ‘dog’, ‘rabbit’];

animals.forEach(animal => console.log(`I have a ${animal} as a pet.`));

//output: I have a cat as a pet.

//        I have a dog as a pet.

//        I have a rabbit as a pet.

The callback function takes in up to three arguments: the current element, its index, and the array itself. In the example above, we use an arrow function to log a sentence for each animal in the array.

#36. Array.toSorted() 

The toSorted method is the copying version of the sort method. It takes in an optional compare function and returns a new sorted array, leaving the original array unchanged. The syntax for this method looks like this:

array.toSorted(compareFunction);

Example:

const numbers = [3, 1, 5];

const sortedNumbers = numbers.toSorted();

console.log(numbers); //output: [3, 1, 5]

console.log(sortedNumbers); //output: [1, 3, 5] 

The original array number remains unchanged while the new sorted array sortedNumbers is returned.

 

About the Author

Tom Koh

Tom is the CEO and Principal Consultant of MediaOne, a leading digital marketing agency. He has consulted for MNCs like Canon, Maybank, Capitaland, SingTel, ST Engineering, WWF, Cambridge University, as well as Government organisations like Enterprise Singapore, Ministry of Law, National Galleries, NTUC, e2i, SingHealth. His articles are published and referenced in CNA, Straits Times, MoneyFM, Financial Times, Yahoo! Finance, Hubspot, Zendesk, CIO Advisor.

Share:

Search Engine Optimisation (SEO)

Search Engine Marketing (SEM)

PSG Grants: The Complete Guide

How do you kickstart your technology journey with limited resources? The Productivity Solution Grant (PSG) is a great place to start. The Productivity Solution Grant

Is SEO Better Or SEM Better?

I think we can all agree that Google SEO is pretty cool! A lot of people get to enjoy high rankings on Google and other

Social Media

Technology

Branding

Business

Most viewed Articles

Other Similar Articles