0% found this document useful (0 votes)
5 views94 pages

JavaScript Exam

This document provides an overview of JavaScript strings, including how to create them using quotes, the use of escape characters, and the introduction of template strings in ES6. It explains various string methods for manipulating strings, such as extracting characters, modifying case, trimming whitespace, and padding. Additionally, it highlights the immutability of strings and the differences between string literals and string objects.

Uploaded by

brianmangaoang0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views94 pages

JavaScript Exam

This document provides an overview of JavaScript strings, including how to create them using quotes, the use of escape characters, and the introduction of template strings in ES6. It explains various string methods for manipulating strings, such as extracting characters, modifying case, trimming whitespace, and padding. Additionally, it highlights the immutability of strings and the differences between string literals and string objects.

Uploaded by

brianmangaoang0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 94

JavaScript Strings

❮ PreviousNext ❯
Strings are for storing text

Strings are written with quotes

Using Quotes
A JavaScript string is zero or more characters written inside quotes.

Example
let text = "John Doe";
Try it Yourself »

You can use single or double quotes:

Example
let carName1 = "Volvo XC60"; // Double quotes
let carName2 = 'Volvo XC60'; // Single quotes
Try it Yourself »

Note
Strings created with single or double quotes works the same.

There is no difference between the two.

Quotes Inside Quotes


You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:

Example
let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';

Try it Yourself »

Template Strings
Templates were introduced with ES6 (JavaScript 2016).

Templates are strings enclosed in backticks (`This is a template string`).

Templates allow single and double quotes inside a string:

Example
let text = `He's often called "Johnny"`;

Try it Yourself »

Note
Templates are not supported in Internet Explorer.

String Length
To find the length of a string, use the built-in length property:

Example
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
Try it Yourself »

Escape Characters
Because strings must be written within quotes, JavaScript will misunderstand
this string:

let text = "We are the so-called "Vikings" from the north.";

The string will be chopped to "We are the so-called ".

To solve this problem, you can use an backslash escape character.

The backslash escape character (\) turns special characters into string
characters:

Code Result Description

\' ' Single quote

\" " Double quote

\\ \ Backslash

Examples
\" inserts a double quote in a string:

let text = "We are the so-called \"Vikings\" from the north.";
Try it Yourself »

\' inserts a single quote in a string:

let text= 'It\'s alright.';

Try it Yourself »

\\ inserts a backslash in a string:

let text = "The character \\ is called backslash.";


Try it Yourself »

Six other escape sequences are valid in JavaScript:

Code Result

\b Backspace

\f Form Feed

\n New Line

\r Carriage Return

\t Horizontal Tabulator

\v Vertical Tabulator

Note
The 6 escape characters above were originally designed to control typewriters,
teletypes, and fax machines. They do not make any sense in HTML.

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
Breaking Long Lines
For readability, programmers often like to avoid long code lines.

A safe way to break up a statement is after an operator:

Example
document.getElementById("demo").innerHTML =
"Hello Dolly!";
Try it Yourself »

A safe way to break up a string is by using string addition:

Example
document.getElementById("demo").innerHTML = "Hello " +
"Dolly!";
Try it Yourself »

Template Strings
Templates were introduced with ES6 (JavaScript 2016).

Templates are strings enclosed in backticks (`This is a template string`).

Templates allow multiline strings:

Example
let text =
`The quick
brown fox
jumps over
the lazy dog`;

Try it Yourself »
Note
Templates are not supported in Internet Explorer.

JavaScript Strings as Objects


Normally, JavaScript strings are primitive values, created from literals:

let x = "John";

But strings can also be defined as objects with the keyword new:

let y = new String("John");

Example
let x = "John";
let y = new String("John");

Try it Yourself »
Do not create Strings objects.

The new keyword complicates the code and slows down execution speed.

String objects can produce unexpected results:


When using the == operator, x and y are equal:

let x = "John";
let y = new String("John");
Try it Yourself »
When using the === operator, x and y are not equal:

let x = "John";
let y = new String("John");
Try it Yourself »
Note the difference between (x==y) and (x===y).
(x == y) true or false?
let x = new String("John");
let y = new String("John");
Try it Yourself »
(x === y) true or false?

let x = new String("John");


let y = new String("John");
Try it Yourself »
Comparing two JavaScript objects always returns false.

Complete String Reference


For a complete String reference, go to our:

Complete JavaScript String Reference.

The reference contains descriptions and examples of all string properties and
methods.

JavaScript String Methods


❮ PreviousNext ❯

Basic String Methods


Javascript strings are primitive and immutable: All string methods produce a
new string without altering the original string.

String length String toUpperCase()


String charAt() String toLowerCase()
String charCodeAt() String concat()
String at() String trim()
String [ ] String trimStart()
String slice() String trimEnd()
String substring() String padStart()
String substr() String padEnd()
String repeat()
String replace()
See Also: String replaceAll()
String split()
String Search Methods
String Templates

JavaScript String Length


The length property returns the length of a string:

Example
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
Try it Yourself »

Extracting String Characters


There are 4 methods for extracting string characters:

• The at(position) Method


• The charAt(position) Method
• The charCodeAt(position) Method
• Using property access [] like in arrays

JavaScript String charAt()


The charAt() method returns the character at a specified index (position) in a
string:

Example
let text = "HELLO WORLD";
let char = text.charAt(0);
Try it Yourself »
JavaScript String charCodeAt()
The charCodeAt() method returns the code of the character at a specified index in
a string:

The method returns a UTF-16 code (an integer between 0 and 65535).

Example
let text = "HELLO WORLD";
let char = text.charCodeAt(0);
Try it Yourself »

JavaScript String at()


ES2022 introduced the string method at():

Examples
Get the third letter of name:

const name = "W3Schools";


let letter = name.at(2);
Try it Yourself »

Get the third letter of name:

const name = "W3Schools";


let letter = name[2];
Try it Yourself »

The at() method returns the character at a specified index (position) in a string.

The at() method is supported in all modern browsers since March 2022:

Note
The at() method is a new addition to JavaScript.
It allows the use of negative indexes while charAt() do not.

Now you can use myString.at(-2) instead of charAt(myString.length-2).

Browser Support
at() is an ES2022 feature.

JavaScript 2022 (ES2022) is supported in all modern browsers since March


2023:

Chrome 94 Edge 94 Firefox 93 Safa

Sep 2021 Sep 2021 Oct 2021 Mar

Property Access [ ]
Example
let text = "HELLO WORLD";
let char = text[0];
Try it Yourself »

Note
Property access might be a little unpredictable:

• It makes strings look like arrays (but they are not)


• If no character is found, [ ] returns undefined, while charAt() returns an
empty string.
• It is read only. str[0] = "A" gives no error (but does not work!)

Example
let text = "HELLO WORLD";
text[0] = "A"; // Gives no error, but does not work
Try it Yourself »

Extracting String Parts


There are 3 methods for extracting a part of a string:

• slice(start, end)
• substring(start, end)
• substr(start, length)

JavaScript String slice()


slice() extracts a part of a string and returns the extracted part in a new string.

The method takes 2 parameters: start position, and end position (end not
included).

Example
Slice out a portion of a string from position 7 to position 13:

let text = "Apple, Banana, Kiwi";


let part = text.slice(7, 13);
Try it Yourself »

Note
JavaScript counts positions from zero.

First position is 0.

Second position is 1.

Examples
If you omit the second parameter, the method will slice out the rest of the
string:
let text = "Apple, Banana, Kiwi";
let part = text.slice(7);
Try it Yourself »

If a parameter is negative, the position is counted from the end of the string:

let text = "Apple, Banana, Kiwi";


let part = text.slice(-12);
Try it Yourself »

This example slices out a portion of a string from position -12 to position -6:

let text = "Apple, Banana, Kiwi";


let part = text.slice(-12, -6);
Try it Yourself »

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

JavaScript String substring()


substring() is similar to slice().

The difference is that start and end values less than 0 are treated as 0
in substring().

Example
let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);
Try it Yourself »

If you omit the second parameter, substring() will slice out the rest of the string.
JavaScript String substr()
substr() is similar to slice().

The difference is that the second parameter specifies the length of the
extracted part.

Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);
Try it Yourself »

If you omit the second parameter, substr() will slice out the rest of the string.

Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(7);
Try it Yourself »

If the first parameter is negative, the position counts from the end of the string.

Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(-4);
Try it Yourself »

Converting to Upper and Lower Case


A string is converted to upper case with toUpperCase():

A string is converted to lower case with toLowerCase():

JavaScript String toUpperCase()


Example
let text1 = "Hello World!";
let text2 = text1.toUpperCase();
Try it Yourself »

JavaScript String toLowerCase()


Example
let text1 = "Hello World!"; // String
let text2 = text1.toLowerCase(); // text2 is text1 converted to lower
Try it Yourself »

JavaScript String concat()


concat() joins two or more strings:

Example
let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);
Try it Yourself »

The concat() method can be used instead of the plus operator. These two lines
do the same:

Example
text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");

Note
All string methods return a new string. They don't modify the original string.

Formally said:
Strings are immutable: Strings cannot be changed, only replaced.

JavaScript String trim()


The trim() method removes whitespace from both sides of a string:

Example
let text1 = " Hello World! ";
let text2 = text1.trim();
Try it Yourself »

JavaScript String trimStart()


ECMAScript 2019 added the String method trimStart() to JavaScript.

The trimStart() method works like trim(), but removes whitespace only from the
start of a string.

Example
let text1 = " Hello World! ";
let text2 = text1.trimStart();

Try it Yourself »

JavaScript String trimStart() is supported in all modern browsers since January


2020:

Chrome 66 Edge 79 Firefox 61 Saf

Apr 2018 Jan 2020 Jun 2018 Sep


JavaScript String trimEnd()
ECMAScript 2019 added the string method trimEnd() to JavaScript.

The trimEnd() method works like trim(), but removes whitespace only from the
end of a string.

Example
let text1 = " Hello World! ";
let text2 = text1.trimEnd();

Try it Yourself »

JavaScript String trimEnd() is supported in all modern browsers since January


2020:

Chrome 66 Edge 79 Firefox 61 Sa

Apr 2018 Jan 2020 Jun 2018 Se

JavaScript String Padding


ECMAScript 2017 added two new string methods to
JavaScript: padStart() and padEnd() to support padding at the beginning and at
the end of a string.

JavaScript String padStart()


The padStart() method pads a string from the start.

It pads a string with another string (multiple times) until it reaches a given
length.
Examples
Pad a string with "0" until it reaches the length 4:

let text = "5";


let padded = text.padStart(4,"0");
Try it Yourself »

Pad a string with "x" until it reaches the length 4:

let text = "5";


let padded = text.padStart(4,"x");
Try it Yourself »

Note
The padStart() method is a string method.

To pad a number, convert the number to a string first.

See the example below.

Example
let numb = 5;
let text = numb.toString();
let padded = text.padStart(4,"0");
Try it Yourself »

Browser Support
padStart() is an ECMAScript 2017 feature.

ES2017 is supported in all modern browsers since September 2017:

Chrome 58 Edge 15 Firefox 52 Saf

Apr 2017 Apr 2017 Mar 2017 Sep

padStart() is not supported in Internet Explorer.


JavaScript String padEnd()
The padEnd() method pads a string from the end.

It pads a string with another string (multiple times) until it reaches a given
length.

Examples
let text = "5";
let padded = text.padEnd(4,"0");
Try it Yourself »
let text = "5";
let padded = text.padEnd(4,"x");
Try it Yourself »

Note
The padEnd() method is a string method.

To pad a number, convert the number to a string first.

See the example below.

Example
let numb = 5;
let text = numb.toString();
let padded = text.padEnd(4,"0");
Try it Yourself »

Browser Support
padEnd() is an ECMAScript 2017 feature.

ES2017 is supported in all modern browsers since September 2017:


Chrome 58 Edge 15 Firefox 52 Saf

Apr 2017 Apr 2017 Mar 2017 Sep

padEnd() is not supported in Internet Explorer.

JavaScript String repeat()


The repeat() method returns a string with a number of copies of a string.

The repeat() method returns a new string.

The repeat() method does not change the original string.

Examples
Create copies of a text:

let text = "Hello world!";


let result = text.repeat(2);
Try it Yourself »
let text = "Hello world!";
let result = text.repeat(4);
Try it Yourself »

Syntax
string.repeat(count)

Parameters

Parameter Description

count Required.
The number of copies wanted.
Return Value

Type Description

String A new string containing the copies.

Browser Support
repeat() is an ES6 feature (JavaScript 2015).

ES6 is fully supported in all modern browsers since June 2017:

Chrome 51 Edge 15 Firefox 54 Saf

May 2016 Apr 2017 Jun 2017 Sep

repeat() is not supported in Internet Explorer.

Replacing String Content


The replace() method replaces a specified value with another value in a string:

Example
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");

Try it Yourself »
Note
The replace() method does not change the string it is called on.

The replace() method returns a new string.

The replace() method replaces only the first match

If you want to replace all matches, use a regular expression with the /g flag set.
See examples below.

By default, the replace() method replaces only the first match:

Example
let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");

Try it Yourself »

By default, the replace() method is case sensitive. Writing MICROSOFT (with


upper-case) will not work:

Example
let text = "Please visit Microsoft!";
let newText = text.replace("MICROSOFT", "W3Schools");

Try it Yourself »

To replace case insensitive, use a regular expression with an /i flag


(insensitive):

Example
let text = "Please visit Microsoft!";
let newText = text.replace(/MICROSOFT/i, "W3Schools");

Try it Yourself »

Note
Regular expressions are written without quotes.

To replace all matches, use a regular expression with a /g flag (global


match):

Example
let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace(/Microsoft/g, "W3Schools");

Try it Yourself »

Note
You will learn a lot more about regular expressions in the chapter JavaScript
Regular Expressions.

JavaScript String ReplaceAll()


In 2021, JavaScript introduced the string method replaceAll():

Example
text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");
Try it Yourself »

The replaceAll() method allows you to specify a regular expression instead of a


string to be replaced.

If the parameter is a regular expression, the global flag (g) must be set,
otherwise a TypeError is thrown.

Example
text = text.replaceAll(/Cats/g,"Dogs");
text = text.replaceAll(/cats/g,"dogs");

Try it Yourself »
Note
replaceAll() is an ES2021 feature.

replaceAll() does not work in Internet Explorer.

Converting a String to an Array


If you want to work with a string as an array, you can convert it to an array.

JavaScript String split()


A string can be converted to an array with the split() method:

Example
text.split(",") // Split on commas
text.split(" ") // Split on spaces
text.split("|") // Split on pipe
Try it Yourself »

If the separator is omitted, the returned array will contain the whole string in
index [0].

If the separator is "", the returned array will be an array of single characters:

Example
text.split("")
Try it Yourself »

Complete String Reference


For a complete String reference, go to our:

Complete JavaScript String Reference.

The reference contains descriptions and examples of all string properties and
methods.
avaScript String Search
❮ PreviousNext ❯

String Search Methods


String indexOf() String match()
String lastIndexOf() String matchAll()
String search() String includes()
String startsWith()
String endsWith()
See Also:
Basic String Methods
String Templates

JavaScript String indexOf()


The indexOf() method returns the index (position) of the first occurrence of a
string in a string, or it returns -1 if the string is not found:

Example
let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate");
Try it Yourself »

Note
JavaScript counts positions from zero.

0 is the first position in a string, 1 is the second, 2 is the third, ...

JavaScript String lastIndexOf()


The lastIndexOf() method returns the index of the last occurrence of a specified
text in a string:
Example
let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("locate");
Try it Yourself »

Both indexOf(), and lastIndexOf() return -1 if the text is not found:

Example
let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("John");
Try it Yourself »

Both methods accept a second parameter as the starting position for the
search:

Example
let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate", 15);
Try it Yourself »

The lastIndexOf() methods searches backwards (from the end to the beginning),
meaning: if the second parameter is 15, the search starts at position 15, and
searches to the beginning of the string.

Example
let text = "Please locate where 'locate' occurs!";
text.lastIndexOf("locate", 15);
Try it Yourself »

JavaScript String search()


The search() method searches a string for a string (or a regular expression) and
returns the position of the match:

Examples
let text = "Please locate where 'locate' occurs!";
text.search("locate");
Try it Yourself »
let text = "Please locate where 'locate' occurs!";
text.search(/locate/);
Try it Yourself »

Did You Notice?


The two methods, indexOf() and search(), are equal?

They accept the same arguments (parameters), and return the same value?

The two methods are NOT equal. These are the differences:

• The search() method cannot take a second start position argument.


• The indexOf() method cannot take powerful search values (regular
expressions).

You will learn more about regular expressions in a later chapter.

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

JavaScript String match()


The match() method returns an array containing the results of matching a string
against a string (or a regular expression).

Examples
Perform a search for "ain":
let text = "The rain in SPAIN stays mainly in the plain";
text.match("ain");
Try it Yourself »

Perform a search for "ain":

let text = "The rain in SPAIN stays mainly in the plain";


text.match(/ain/);
Try it Yourself »

Perform a global search for "ain":

let text = "The rain in SPAIN stays mainly in the plain";


text.match(/ain/g);
Try it Yourself »

Perform a global, case-insensitive search for "ain":

let text = "The rain in SPAIN stays mainly in the plain";


text.match(/ain/gi);
Try it Yourself »

Note
If a regular expression does not include the g modifier (global
search), match() will return only the first match in the string.

Read more about regular expressions in the chapter JS RegExp.

JavaScript String matchAll()


The matchAll() method returns an iterator containing the results of matching a
string against a string (or a regular expression).

Example
const iterator = text.matchAll("Cats");

Try it Yourself »

If the parameter is a regular expression, the global flag (g) must be set,
otherwise a TypeError is thrown.
Example
const iterator = text.matchAll(/Cats/g);

Try it Yourself »

If you want to search case insensitive, the insensitive flag (i) must be set:

Example
const iterator = text.matchAll(/Cats/gi);

Try it Yourself »

Notes
matchAll() is an ES2020 feature.

matchAll() does not work in Internet Explorer.

JavaScript String includes()


The includes() method returns true if a string contains a specified value.

Otherwise it returns false.

Examples
Check if a string includes "world":

let text = "Hello world, welcome to the universe.";


text.includes("world");
Try it Yourself »

Check if a string includes "world". Start at position 12:

let text = "Hello world, welcome to the universe.";


text.includes("world", 12);
Try it Yourself »
Notes
includes() is case sensitive.

includes() is an ES6 feature.

includes() is not supported in Internet Explorer.

JavaScript String startsWith()


The startsWith() method returns true if a string begins with a specified value.

Otherwise it returns false:

Examples
Returns true:

let text = "Hello world, welcome to the universe.";


text.startsWith("Hello");
Try it Yourself »

Returns false:

let text = "Hello world, welcome to the universe.";


text.startsWith("world")
Try it Yourself »

A start position for the search can be specified:

Returns false:

let text = "Hello world, welcome to the universe.";


text.startsWith("world", 5)
Try it Yourself »

Returns true:

let text = "Hello world, welcome to the universe.";


text.startsWith("world", 6)
Try it Yourself »
Notes
startsWith() is case sensitive.

startsWith() is an ES6 feature.

startsWith() is not supported in Internet Explorer.

JavaScript String endsWith()


The endsWith() method returns true if a string ends with a specified value.

Otherwise it returns false:

Examples
Check if a string ends with "Doe":

let text = "John Doe";


text.endsWith("Doe");
Try it Yourself »

Check if the 11 first characters of a string ends with "world":

let text = "Hello world, welcome to the universe.";


text.endsWith("world", 11);

Try it Yourself »

Notes
endsWith() is case sensitive.

endsWith() is an ES6 feature.

endsWith() is not supported in Internet Explorer.


Complete String Reference
For a complete String reference, go to our:

Complete JavaScript String Reference.

The reference contains descriptions and examples of all string properties and
methods.

JavaScript Template Strings


❮ PreviousNext ❯

String Templates
Template Strings
Template Literals
Beloved child has many names

Back-Tics Syntax
Template Strings use back-ticks (``) rather than the quotes ("") to define a
string:

Example
let text = `Hello World!`;

Try it Yourself »

Quotes Inside Strings


Template Strings allow both single and double quotes inside a string:
Example
let text = `He's often called "Johnny"`;

Try it Yourself »

Multiline Strings
Template Strings allow multiline strings:

Example
let text =
`The quick
brown fox
jumps over
the lazy dog`;

Try it Yourself »

Interpolation
Template String provide an easy way to interpolate variables and expressions
into strings.

The method is called string interpolation.

The syntax is:

${...}

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT

Variable Substitutions
Template Strings allow variables in strings:

Example
let firstName = "John";
let lastName = "Doe";

let text = `Welcome ${firstName}, ${lastName}!`;

Try it Yourself »

Automatic replacing of variables with real values is called string interpolation.

Expression Substitution
Template Strings allow expressions in strings:

Example
let price = 10;
let VAT = 0.25;

let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;

Try it Yourself »

Automatic replacing of expressions with real values is called string


interpolation.

HTML Templates
Example
let header = "Template Strings";
let tags = ["template strings", "javascript", "es6"];

let html = `<h2>${header}</h2><ul>`;


for (const x of tags) {
html += `<li>${x}</li>`;
}

html += `</ul>`;

Try it Yourself »

Browser Support
Template Strings is an ES6 feature (JavaScript 2015).

ES6 is fully supported in all modern browsers since June 2017:

Chrome 51 Edge 15 Firefox 54 Saf

May 2016 Apr 2017 Jun 2017 Sep

Template Strings is not supported in Internet Explorer.

Complete String Reference


For a complete String reference, go to our:

Complete JavaScript String Reference.


The reference contains descriptions and examples of all string properties and
methods.

JavaScript Arrays
❮ PreviousNext ❯
An array is a special variable, which can hold more than one value:

const cars = ["Saab", "Volvo", "BMW"];


Try it Yourself »

Why Use Arrays?


If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:

let car1 = "Saab";


let car2 = "Volvo";
let car3 = "BMW";

However, what if you want to loop through the cars and find a specific one? And
what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the
values by referring to an index number.

Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.

Syntax:

const array_name = [item1, item2, ...];


It is a common practice to declare arrays with the const keyword.

Learn more about const with arrays in the chapter: JS Array Const.
Example
const cars = ["Saab", "Volvo", "BMW"];
Try it Yourself »

Spaces and line breaks are not important. A declaration can span multiple lines:

Example
const cars = [
"Saab",
"Volvo",
"BMW"
];
Try it Yourself »

You can also create an array, and then provide the elements:

Example
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";

Try it Yourself »

Using the JavaScript Keyword new


The following example also creates an Array, and assigns values to it:

Example
const cars = new Array("Saab", "Volvo", "BMW");
Try it Yourself »
The two examples above do exactly the same.

There is no need to use new Array().

For simplicity, readability and execution speed, use the array literal method.
ADVERTISEMENT

Accessing Array Elements


You access an array element by referring to the index number:

const cars = ["Saab", "Volvo", "BMW"];


let car = cars[0];
Try it Yourself »
Note: Array indexes start with 0.

[0] is the first element. [1] is the second element.

Changing an Array Element


This statement changes the value of the first element in cars:

cars[0] = "Opel";

Example
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
Try it Yourself »

Converting an Array to a String


The JavaScript method toString() converts an array to a string of (comma
separated) array values.

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();

Result:

Banana,Orange,Apple,Mango
Try it Yourself »

Access the Full Array


With JavaScript, the full array can be accessed by referring to the array name:

Example
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
Try it Yourself »

Arrays are Objects


Arrays are a special type of objects. The typeof operator in JavaScript returns
"object" for arrays.

But, JavaScript arrays are best described as arrays.

Arrays use numbers to access its "elements". In this


example, person[0] returns John:

Array:
const person = ["John", "Doe", 46];
Try it Yourself »

Objects use names to access its "members". In this


example, person.firstName returns John:

Object:
const person = {firstName:"John", lastName:"Doe", age:46};
Try it Yourself »

Array Elements Can Be Objects


JavaScript variables can be objects. Arrays are special kinds of objects.

Because of this, you can have variables of different types in the same Array.

You can have objects in an Array. You can have functions in an Array. You can
have arrays in an Array:

myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;

Array Properties and Methods


The real strength of JavaScript arrays are the built-in array properties and
methods:

cars.length // Returns the number of elements


cars.sort() // Sorts the array

Array methods are covered in the next chapters.

The length Property


The length property of an array returns the length of an array (the number of
array elements).

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;
Try it Yourself »
The length property is always one more than the highest array index.

Accessing the First Array Element


Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[0];
Try it Yourself »

Accessing the Last Array Element


Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits[fruits.length - 1];
Try it Yourself »

Looping Array Elements


One way to loop through an array, is using a for loop:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;

let text = "<ul>";


for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
Try it Yourself »
You can also use the Array.forEach() function:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];

let text = "<ul>";


fruits.forEach(myFunction);
text += "</ul>";

function myFunction(value) {
text += "<li>" + value + "</li>";
}
Try it Yourself »

Adding Array Elements


The easiest way to add a new element to an array is using the push() method:

Example
const fruits = ["Banana", "Orange", "Apple"];
fruits.push("Lemon"); // Adds a new element (Lemon) to fruits
Try it Yourself »

New element can also be added to an array using the length property:

Example
const fruits = ["Banana", "Orange", "Apple"];
fruits[fruits.length] = "Lemon"; // Adds "Lemon" to fruits
Try it Yourself »
WARNING !

Adding elements with high indexes can create undefined "holes" in an array:

Example
const fruits = ["Banana", "Orange", "Apple"];
fruits[6] = "Lemon"; // Creates undefined "holes" in fruits
Try it Yourself »
Associative Arrays
Many programming languages support arrays with named indexes.

Arrays with named indexes are called associative arrays (or hashes).

JavaScript does not support arrays with named indexes.

In JavaScript, arrays always use numbered indexes.

Example
const person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
person.length; // Will return 3
person[0]; // Will return "John"
Try it Yourself »
WARNING !!
If you use named indexes, JavaScript will redefine the array to an object.

After that, some array methods and properties will produce incorrect results.

Example:
const person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
person.length; // Will return 0
person[0]; // Will return undefined
Try it Yourself »

The Difference Between Arrays and Objects


In JavaScript, arrays use numbered indexes.
In JavaScript, objects use named indexes.

Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays. When to use Objects.


• JavaScript does not support associative arrays.
• You should use objects when you want the element names to be strings
(text).
• You should use arrays when you want the element names to
be numbers.

JavaScript new Array()


JavaScript has a built-in array constructor new Array().

But you can safely use [] instead.

These two different statements both create a new empty array named points:

const points = new Array();


const points = [];

These two different statements both create a new array containing 6 numbers:

const points = new Array(40, 100, 1, 5, 25, 10);


const points = [40, 100, 1, 5, 25, 10];
Try it Yourself »

The new keyword can produce some unexpected results:

// Create an array with three elements:


const points = new Array(40, 100, 1);
Try it Yourself »
// Create an array with two elements:
const points = new Array(40, 100);
Try it Yourself »
// Create an array with one element ???
const points = new Array(40);
Try it Yourself »

A Common Error
const points = [40];

is not the same as:

const points = new Array(40);


// Create an array with one element:
const points = [40];
Try it Yourself »
// Create an array with 40 undefined elements:
const points = new Array(40);
Try it Yourself »

How to Recognize an Array


A common question is: How do I know if a variable is an array?

The problem is that the JavaScript operator typeof returns "object":

const fruits = ["Banana", "Orange", "Apple"];


let type = typeof fruits;
Try it Yourself »

The typeof operator returns object because a JavaScript array is an object.

Solution 1:
To solve this problem ECMAScript 5 (JavaScript 2009) defined a new
method Array.isArray():

Array.isArray(fruits);
Try it Yourself »

Solution 2:
The instanceof operator returns true if an object is created by a given
constructor:

const fruits = ["Banana", "Orange", "Apple"];

(fruits instanceof Array);


Try it Yourself »

Nested Arrays and Objects


Values in objects can be arrays, and values in arrays can be objects:

Example
const myObj = {
name: "John",
age: 30,
cars: [
{name:"Ford", models:["Fiesta", "Focus", "Mustang"]},
{name:"BMW", models:["320", "X3", "X5"]},
{name:"Fiat", models:["500", "Panda"]}
]
}

To access arrays inside arrays, use a for-in loop for each array:

Example
for (let i in myObj.cars) {
x += "<h1>" + myObj.cars[i].name + "</h1>";
for (let j in myObj.cars[i].models) {
x += myObj.cars[i].models[j];
}
}

Try it Yourself »

Complete Array Reference


For a complete Array reference, go to our:

Complete JavaScript Array Reference.


The reference contains descriptions and examples of all Array properties and
methods.

JavaScript Array Methods


❮ PreviousNext ❯

Basic Array Methods


Array length Array shift()
Array toString() Array unshift()
Array at() Array delete()
Array join() Array concat()
Array pop() Array copyWithin()
Array push() Array flat()
Array splice()
Array toSpliced()
Array slice()

See Also:
Search Methods
Sort Methods
Iteration Methods

JavaScript Array length


The length property returns the length (size) of an array:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = fruits.length;

Try it Yourself »
JavaScript Array toString()
The JavaScript method toString() converts an array to a string of (comma
separated) array values.

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();

Result:

Banana,Orange,Apple,Mango

Try it Yourself »

JavaScript Array at()


ES2022 intoduced the array method at():

Examples
Get the third element of fruits using at():

const fruits = ["Banana", "Orange", "Apple", "Mango"];


let fruit = fruits.at(2);

Try it Yourself »

Get the third element of fruits using []:

const fruits = ["Banana", "Orange", "Apple", "Mango"];


let fruit = fruits[2];

Try it Yourself »

The at() method returns an indexed element from an array.

The at() method returns the same as [].

The at() method is supported in all modern browsers since March 2022:
Chrome 92 Edge 92 Firefox 90 Sa

Apr 2021 Jul 2021 Jul 2021 M

Note
Many languages allow negative bracket indexing like [-1] to access elements from
the end of an object / array / string.

This is not possible in JavaScript, because [] is used for accessing both arrays
and objects. obj[-1] refers to the value of key -1, not to the last property of the
object.

The at() method was introduced in ES2022 to solve this problem.

JavaScript Array join()


The join() method also joins all array elements into a string.

It behaves just like toString(), but in addition you can specify the separator:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");

Result:

Banana * Orange * Apple * Mango

Try it Yourself »

Popping and Pushing


When you work with arrays, it is easy to remove elements and add new
elements.

This is what popping and pushing is:

Popping items out of an array, or pushing items into an array.

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

JavaScript Array pop()


The pop() method removes the last element from an array:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop();

Try it Yourself »

The pop() method returns the value that was "popped out":

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.pop();

Try it Yourself »

JavaScript Array push()


The push() method adds a new element to an array (at the end):
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");

Try it Yourself »

The push() method returns the new array length:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.push("Kiwi");

Try it Yourself »

Shifting Elements
Shifting is equivalent to popping, but working on the first element instead of the
last.

JavaScript Array shift()


The shift() method removes the first array element and "shifts" all other
elements to a lower index.

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.shift();

Try it Yourself »

The shift() method returns the value that was "shifted out":

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.shift();

Try it Yourself »

JavaScript Array unshift()


The unshift() method adds a new element to an array (at the beginning), and
"unshifts" older elements:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");

Try it Yourself »

The unshift() method returns the new array length:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");

Try it Yourself »

Changing Elements
Array elements are accessed using their index number:

Array indexes start with 0:

[0] is the first array element


[1] is the second
[2] is the third ...

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[0] = "Kiwi";

Try it Yourself »

JavaScript Array length


The length property provides an easy way to append a new element to an array:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi";

Try it Yourself »

JavaScript Array delete()


Warning !
Using delete() leaves undefined holes in the array.

Use pop() or shift() instead.

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0];

Try it Yourself »

Merging Arrays (Concatenating)


In programming languages, concatenation means joining strings end-to-end.
Concatenation "snow" and "ball" gives "snowball".

Concatenating arrays means joining arrays end-to-end.

JavaScript Array concat()


The concat() method creates a new array by merging (concatenating) existing
arrays:

Example (Merging Two Arrays)


const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];

const myChildren = myGirls.concat(myBoys);

Try it Yourself »

Note
The concat() method does not change the existing arrays. It always returns a
new array.

The concat() method can take any number of array arguments.

Example (Merging Three Arrays)


const arr1 = ["Cecilie", "Lone"];
const arr2 = ["Emil", "Tobias", "Linus"];
const arr3 = ["Robin", "Morgan"];
const myChildren = arr1.concat(arr2, arr3);

Try it Yourself »

The concat() method can also take strings as arguments:

Example (Merging an Array with Values)


const arr1 = ["Emil", "Tobias", "Linus"];
const myChildren = arr1.concat("Peter");
Try it Yourself »

Array copyWithin()
The copyWithin() method copies array elements to another position in an array:

Examples
Copy to index 2, all elements from index 0:

const fruits = ["Banana", "Orange", "Apple", "Mango"];


fruits.copyWithin(2, 0);

Try it Yourself »

Copy to index 2, the elements from index 0 to 2:

const fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];


fruits.copyWithin(2, 0, 2);

Try it Yourself »

Note
The copyWithin() method overwrites the existing values.

The copyWithin() method does not add items to the array.

The copyWithin() method does not change the length of the array.

Flattening an Array
Flattening an array is the process of reducing the dimensionality of an array.

Flattening is useful when you want to convert a multi-dimensional array into a


one-dimensional array.
JavaScript Array flat()
ES2019 Introduced the Array flat() method.

The flat() method creates a new array with sub-array elements concatenated to
a specified depth.

Example
const myArr = [[1,2],[3,4],[5,6]];
const newArr = myArr.flat();

Try it Yourself »

Browser Support
JavaScript Array flat() is supported in all modern browsers since January 2020:

Chrome 69 Edge 79 Firefox 62 Sa

Sep 2018 Jan 2020 Sep 2018 Se

JavaScript Array flatMap()


ES2019 added the Array flatMap() method to JavaScript.

The flatMap() method first maps all elements of an array and then creates a new
array by flattening the array.

Example
const myArr = [1, 2, 3, 4, 5, 6];
const newArr = myArr.flatMap(x => [x, x * 10]);
Try it Yourself »

Browser Support
JavaScript Array flatMap() is supported in all modern browsers since January
2020:

Chrome 69 Edge 79 Firefox 62 Sa

Sep 2018 Jan 2020 Sep 2018 Se

Splicing and Slicing Arrays


The splice() method adds new items to an array.

The slice() method slices out a piece of an array.

JavaScript Array splice()


The splice() method can be used to add new items to an array:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi");

Try it Yourself »

The first parameter (2) defines the position where new elements should
be added (spliced in).

The second parameter (0) defines how many elements should be removed.
The rest of the parameters ("Lemon" , "Kiwi") define the new elements to
be added.

The splice() method returns an array with the deleted items:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");

Try it Yourself »

Using splice() to Remove Elements


With clever parameter setting, you can use splice() to remove elements without
leaving "holes" in the array:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 1);

Try it Yourself »

The first parameter (0) defines the position where new elements should
be added (spliced in).

The second parameter (1) defines how many elements should be removed.

The rest of the parameters are omitted. No new elements will be added.

JavaScript Array toSpliced()


ES2023 added the Array toSpliced() method as a safe way to splice an array
without altering the original array.
The difference between the new toSpliced() method and the
old splice() method is that the new method creates a new array, keeping the
original array unchanged, while the old method altered the original array.

Example
const months = ["Jan", "Feb", "Mar", "Apr"];
const spliced = months.toSpliced(0, 1);

Try it Yourself »

JavaScript Array slice()


The slice() method slices out a piece of an array into a new array:

Example
Slice out a part of an array starting from array element 1 ("Orange"):

const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];


const citrus = fruits.slice(1);

Try it Yourself »

Note
The slice() method creates a new array.

The slice() method does not remove any elements from the source array.

Example
Slice out a part of an array starting from array element 3 ("Apple"):

const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];


const citrus = fruits.slice(3);

Try it Yourself »

The slice() method can take two arguments like slice(1, 3).
The method then selects elements from the start argument, and up to (but not
including) the end argument.

Example
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1, 3);

Try it Yourself »

If the end argument is omitted, like in the first examples, the slice() method
slices out the rest of the array.

Example
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(2);

Try it Yourself »

Automatic toString()
JavaScript automatically converts an array to a comma separated string when a
primitive value is expected.

This is always the case when you try to output an array.

These two examples will produce the same result:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();

Try it Yourself »

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

Try it Yourself »
Note
All JavaScript objects have a toString() method.

Searching Arrays
Searching arrays are covered in the next chapter of this tutorial.

Sorting Arrays
Sorting arrays covers the methods used to sort arraysg.

Iterating Arrays
Iterating arrays covers methods that operate on all array elements.

Complete Array Reference


For a complete Array reference, go to our:

Complete JavaScript Array Reference.

The reference contains descriptions and examples of all Array properties and
methods.

JavaScript Array Search


❮ PreviousNext ❯
Array Find and Search Methods
Array indexOf() Array find()
Array lastIndexOf() Array findIndex()
Array includes() Array findLast()
Array findLastIndex()

See Also:
Basic Methods
Sort Methods
Iteration Methods

JavaScript Array indexOf()


The indexOf() method searches an array for an element value and returns its
position.

Note: The first item has position 0, the second item has position 1, and so on.

Example
Search an array for the item "Apple":

const fruits = ["Apple", "Orange", "Apple", "Mango"];


let position = fruits.indexOf("Apple") + 1;
Try it Yourself »

Syntax
array.indexOf(item, start)

item Required. The item to search for.


start Optional. Where to start the search. Negative values will start at the given position c
end.

Array.indexOf() returns -1 if the item is not found.

If the item is present more than once, it returns the position of the first
occurrence.

JavaScript Array lastIndexOf()


Array.lastIndexOf() is the same as Array.indexOf(), but returns the position of the
last occurrence of the specified element.

Example
Search an array for the item "Apple":

const fruits = ["Apple", "Orange", "Apple", "Mango"];


let position = fruits.lastIndexOf("Apple") + 1;
Try it Yourself »

Syntax
array.lastIndexOf(item, start)

item Required. The item to search for

start Optional. Where to start the search. Negative values will start at the given position c
beginning

JavaScript Array includes()


ECMAScript 2016 introduced Array.includes() to arrays. This allows us to check if
an element is present in an array (including NaN, unlike indexOf).

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.includes("Mango"); // is true
Try it Yourself »

Syntax
array.includes(search-item)
Array.includes() allows to check for NaN values. Unlike Array.indexOf().

Browser Support
includes() is an ECMAScript 2016 feature.

ES 2016 is fully supported in all modern browsers since March 2017:

Chrome 52 Edge 15 Firefox 52 Safa

Jul 2016 Apr 2017 Mar 2017 May

includes() is not supported in Internet Explorer.

JavaScript Array find()


The find() method returns the value of the first array element that passes a test
function.

This example finds (returns the value of) the first element that is larger than
18:
Example
const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction);

function myFunction(value, index, array) {


return value > 18;
}
Try it Yourself »

Note that the function takes 3 arguments:

• The item value


• The item index
• The array itself

Browser Support
find() is an ES6 feature (JavaScript 2015).

ES6 is fully supported in all modern browsers since June 2017:

Chrome 51 Edge 15 Firefox 54 Saf

May 2016 Apr 2017 Jun 2017 Sep

find() is not supported in Internet Explorer.

JavaScript Array findIndex()


The findIndex() method returns the index of the first array element that passes
a test function.

This example finds the index of the first element that is larger than 18:

Example
const numbers = [4, 9, 16, 25, 29];
let first = numbers.findIndex(myFunction);

function myFunction(value, index, array) {


return value > 18;
}
Try it Yourself »

Note that the function takes 3 arguments:

• The item value


• The item index
• The array itself

Browser Support
findIndex() is an ES6 feature (JavaScript 2015).

ES6 is fully supported in all modern browsers since June 2017:

Chrome 51 Edge 15 Firefox 54 Saf

May 2016 Apr 2017 Jun 2017 Sep

findIndex() is not supported in Internet Explorer.

JavaScript Array findLast() Method


ES2023 added the findLast() method that will start from the end of an array and
return the value of the first element that satisfies a condition.

Example
const temp = [27, 28, 30, 40, 42, 35, 30];
let high = temp.findLast(x => x > 40);
Try it Yourself »
Browser Support
findLast() is an ES2023 feature.

It is supported in all modern browsers since July 2023:

Chrome 110 Edge 110 Firefox 115 Safa

Feb 2023 Feb 2023 Jul 2023 Mar

JavaScript Array findLastIndex() Method


The findLastIndex() method finds the index of the last element that satisfies a
condition.

Example
const temp = [27, 28, 30, 40, 42, 35, 30];
let pos = temp.findLastIndex(x => x > 40);
Try it Yourself »

Browser Support
findLastIndex() is an ES2023 feature.

It is supported in all modern browsers since July 2023:

Chrome 110 Edge 110 Firefox 115 Safa

Feb 2023 Feb 2023 Jul 2023 Mar


Complete Array Reference
For a complete Array reference, go to our:

Complete JavaScript Array Reference.

The reference contains descriptions and examples of all Array properties and
methods.

JavaScript Sorting Arrays


❮ PreviousNext ❯

Array Sort Methods

Alphabetic Sort Numeric


Array sort() Numeric Sort
Array reverse() Random Sort
Array toSorted() Math.min()
Array toReversed() Math.max()
Sorting Objects Home made Min()
Home made Max()

See Also:
Basic Methods
Search Methods
Iteration Methods

Sorting an Array
The sort() method sorts an array alphabetically:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();

Try it Yourself »

Reversing an Array
The reverse() method reverses the elements in an array:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.reverse();

Try it Yourself »

By combining sort() and reverse(), you can sort an array in descending order:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();

Try it Yourself »

JavaScript Array toSorted() Method


ES2023 added the toSorted() method as a safe way to sort an array without
altering the original array.

The difference between toSorted() and sort() is that the first method creates a
new array, keeping the original array unchanged, while the last method alters
the original array.
Example
const months = ["Jan", "Feb", "Mar", "Apr"];
const sorted = months.toSorted();

Try it Yourself »

JavaScript Array toReversed() Method


ES2023 added the toReversed() method as a safe way to reverse an array
without altering the original array.

The difference between toReversed() and reverse() is that the first method
creates a new array, keeping the original array unchanged, while the last
method alters the original array.

Example
const months = ["Jan", "Feb", "Mar", "Apr"];
const reversed = months.toReversed();

Try it Yourself »

Numeric Sort
By default, the sort() function sorts values as strings.

This works well for strings ("Apple" comes before "Banana").

If numbers are sorted as strings, "25" is bigger than "100", because "2" is
bigger than "1".

Because of this, the sort() method will produce incorrect result when sorting
numbers.

You can fix this by providing a compare function:

Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});

Try it Yourself »

Use the same trick to sort an array descending:

Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});

Try it Yourself »

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

The Compare Function


The purpose of the compare function is to define an alternative sort order.

The compare function should return a negative, zero, or positive value,


depending on the arguments:

function(a, b){return a - b}

When the sort() function compares two values, it sends the values to the
compare function, and sorts the values according to the returned (negative,
zero, positive) value.

If the result is negative, a is sorted before b.

If the result is positive, b is sorted before a.

If the result is 0, no changes are done with the sort order of the two values.

Example:
The compare function compares all the values in the array, two values at a
time (a, b).

When comparing 40 and 100, the sort() method calls the compare function(40,
100).

The function calculates 40 - 100 (a - b), and since the result is negative (-
60), the sort function will sort 40 as a value lower than 100.

You can use this code snippet to experiment with numerically and alphabetically
sorting:

<button onclick="myFunction1()">Sort Alphabetically</button>


<button onclick="myFunction2()">Sort Numerically</button>

<p id="demo"></p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;

function myFunction1() {
points.sort();
document.getElementById("demo").innerHTML = points;
}

function myFunction2() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>

Try it Yourself »

Sorting an Array in Random Order


Using a sort function, like explained above, you can sort an numeric array in
random order

Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(){return 0.5 - Math.random()});

Try it Yourself »

The Fisher Yates Method


The points.sort() method in the example above is not accurate. It will favor
some numbers over others.

The most popular correct method, is called the Fisher Yates shuffle, and was
introduced in data science as early as 1938!

In JavaScript the method can be translated to this:

Example
const points = [40, 100, 1, 5, 25, 10];

for (let i = points.length -1; i > 0; i--) {


let j = Math.floor(Math.random() * (i+1));
let k = points[i];
points[i] = points[j];
points[j] = k;
}

Try it Yourself »

Find the Lowest (or Highest) Array Value


There are no built-in functions for finding the max or min value in an array.

To find the lowest or highest value you have 3 options:

• Sort the array and read the first or last element


• Use Math.min() or Math.max()
• Write a home made function
Find Min or Max with sort()
After you have sorted an array, you can use the index to obtain the highest and
lowest values.

Sort Ascending:

Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
// now points[0] contains the lowest value
// and points[points.length-1] contains the highest value

Try it Yourself »

Sort Descending:

Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
// now points[0] contains the highest value
// and points[points.length-1] contains the lowest value

Try it Yourself »

Note
Sorting a whole array is a very inefficient method if you only want to find the
highest (or lowest) value.

Using Math.min() on an Array


You can use Math.min.apply to find the lowest number in an array:

Example
function myArrayMin(arr) {
return Math.min.apply(null, arr);
}

Try it Yourself »

Math.min.apply(null, [1, 2, 3]) is equivalent to Math.min(1, 2, 3).

Using Math.max() on an Array


You can use Math.max.apply to find the highest number in an array:

Example
function myArrayMax(arr) {
return Math.max.apply(null, arr);
}

Try it Yourself »

Math.max.apply(null, [1, 2, 3]) is equivalent to Math.max(1, 2, 3).

JavaScript Array Minimum Method


There is no built-in function for finding the lowest value in a JavaScript array.

The fastest code to find the lowest number is to use a home made method.

This function loops through an array comparing each value with the lowest
value found:

Example (Find Min)


function myArrayMin(arr) {
let len = arr.length;
let min = Infinity;
while (len--) {
if (arr[len] < min) {
min = arr[len];
}
}
return min;
}

Try it Yourself »

JavaScript Array Maximum Method


There is no built-in function for finding the highest value in a JavaScript array.

The fastest code to find the highest number is to use a home made method.

This function loops through an array comparing each value with the highest
value found:

Example (Find Max)


function myArrayMax(arr) {
let len = arr.length;
let max = -Infinity;
while (len--) {
if (arr[len] > max) {
max = arr[len];
}
}
return max;
}

Try it Yourself »

Sorting Object Arrays


JavaScript arrays often contain objects:

Example
const cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];

Even if objects have properties of different data types, the sort() method can be
used to sort the array.

The solution is to write a compare function to compare the property values:

Example
cars.sort(function(a, b){return a.year - b.year});

Try it Yourself »

Comparing string properties is a little more complex:

Example
cars.sort(function(a, b){
let x = a.type.toLowerCase();
let y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});

Try it Yourself »

Stable Array sort()


ES2019 revised the Array sort() method.

Before 2019, the specification allowed unstable sorting algorithms such as


QuickSort.

After ES2019, browsers must use a stable sorting algorithm:

When sorting elements on a value, the elements must keep their relative
position to other elements with the same value.
Example
const myArr = [
{name:"X00",price:100 },
{name:"X01",price:100 },
{name:"X02",price:100 },
{name:"X03",price:100 },
{name:"X04",price:110 },
{name:"X05",price:110 },
{name:"X06",price:110 },
{name:"X07",price:110 }
];

Try it Yourself »

In the example above, when sorting on price, the result is not allowed to come
out with the names in an other relative position like this:

X01 100
X03 100
X00 100
X03 100
X05 110
X04 110
X06 110
X07 110

Complete Array Reference


For a complete Array reference, go to our:

Complete JavaScript Array Reference.

The reference contains descriptions and examples of all Array properties and
methods.

JavaScript Array Iteration


❮ PreviousNext ❯

Array Iteration Methods


Array iteration methods operate on every array item:

Array forEach Array every()


Array map() Array some()
Array flatMap() Array from()
Array filter() Array keys()
Array reduce() Array entries()
Array reduceRight() Array with()
Array Spread (..

See Also:
Basic Array Methods
Array Search Methods
Array Sort Methods

JavaScript Array forEach()


The forEach() method calls a function (a callback function) once for each array
element.

Example
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);

function myFunction(value, index, array) {


txt += value + "<br>";
}
Try it Yourself »

Note that the function takes 3 arguments:

• The item value


• The item index
• The array itself

The example above uses only the value parameter. The example can be
rewritten to:
Example
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);

function myFunction(value) {
txt += value + "<br>";
}
Try it Yourself »

JavaScript Array map()


The map() method creates a new array by performing a function on each array
element.

The map() method does not execute the function for array elements without
values.

The map() method does not change the original array.

This example multiplies each array value by 2:

Example
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);

function myFunction(value, index, array) {


return value * 2;
}
Try it Yourself »

Note that the function takes 3 arguments:

• The item value


• The item index
• The array itself

When a callback function uses only the value parameter, the index and array
parameters can be omitted:
Example
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);

function myFunction(value) {
return value * 2;
}
Try it Yourself »

JavaScript Array flatMap()


ES2019 added the Array flatMap() method to JavaScript.

The flatMap() method first maps all elements of an array and then creates a new
array by flattening the array.

Example
const myArr = [1, 2, 3, 4, 5, 6];
const newArr = myArr.flatMap((x) => x * 2);
Try it Yourself »

Browser Support
JavaScript Array flatMap() is supported in all modern browsers since January
2020:

Chrome 69 Edge 79 Firefox 62 Sa

Sep 2018 Jan 2020 Sep 2018 Se

ADVERTISEMENT
JavaScript Array filter()
The filter() method creates a new array with array elements that pass a test.

This example creates a new array from elements with a value larger than 18:

Example
const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);

function myFunction(value, index, array) {


return value > 18;
}
Try it Yourself »

Note that the function takes 3 arguments:

• The item value


• The item index
• The array itself

In the example above, the callback function does not use the index and array
parameters, so they can be omitted:

Example
const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);

function myFunction(value) {
return value > 18;
}
Try it Yourself »

JavaScript Array reduce()


The reduce() method runs a function on each array element to produce (reduce
it to) a single value.

The reduce() method works from left-to-right in the array. See also reduceRight().

The reduce() method does not reduce the original array.

This example finds the sum of all numbers in an array:

Example
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);

function myFunction(total, value, index, array) {


return total + value;
}
Try it Yourself »

Note that the function takes 4 arguments:

• The total (the initial value / previously returned value)


• The item value
• The item index
• The array itself

The example above does not use the index and array parameters. It can be
rewritten to:

Example
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);

function myFunction(total, value) {


return total + value;
}
Try it Yourself »

The reduce() method can accept an initial value:

Example
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction, 100);
function myFunction(total, value) {
return total + value;
}
Try it Yourself »

JavaScript Array reduceRight()


The reduceRight() method runs a function on each array element to produce
(reduce it to) a single value.

The reduceRight() works from right-to-left in the array. See also reduce().

The reduceRight() method does not reduce the original array.

This example finds the sum of all numbers in an array:

Example
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduceRight(myFunction);

function myFunction(total, value, index, array) {


return total + value;
}
Try it Yourself »

Note that the function takes 4 arguments:

• The total (the initial value / previously returned value)


• The item value
• The item index
• The array itself

The example above does not use the index and array parameters. It can be
rewritten to:

Example
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduceRight(myFunction);
function myFunction(total, value) {
return total + value;
}
Try it Yourself »

JavaScript Array every()


The every() method checks if all array values pass a test.

This example checks if all array values are larger than 18:

Example
const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every(myFunction);

function myFunction(value, index, array) {


return value > 18;
}
Try it Yourself »

Note that the function takes 3 arguments:

• The item value


• The item index
• The array itself

When a callback function uses the first parameter only (value), the other
parameters can be omitted:

Example
const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every(myFunction);

function myFunction(value) {
return value > 18;
}
Try it Yourself »
JavaScript Array some()
The some() method checks if some array values pass a test.

This example checks if some array values are larger than 18:

Example
const numbers = [45, 4, 9, 16, 25];
let someOver18 = numbers.some(myFunction);

function myFunction(value, index, array) {


return value > 18;
}
Try it Yourself »

Note that the function takes 3 arguments:

• The item value


• The item index
• The array itself

JavaScript Array.from()
The Array.from() method returns an Array object from any object with a length
property or any iterable object.

Example
Create an Array from a String:

Array.from("ABCDEFG");

Try it Yourself »

Browser Support
from() is an ES6 feature (JavaScript 2015).
ES6 is fully supported in all modern browsers since June 2017:

Chrome 51 Edge 15 Firefox 54 Saf

May 2016 Apr 2017 Jun 2017 Sep

from() is not supported in Internet Explorer.

JavaScript Array keys()


The Array.keys() method returns an Array Iterator object with the keys of an
array.

Example
Create an Array Iterator object, containing the keys of the array:

const fruits = ["Banana", "Orange", "Apple", "Mango"];


const keys = fruits.keys();

for (let x of keys) {


text += x + "<br>";
}
Try it Yourself »

Browser Support
keys() is an ES6 feature (JavaScript 2015).

ES6 is fully supported in all modern browsers since June 2017:

Chrome 51 Edge 15 Firefox 54 Saf


May 2016 Apr 2017 Jun 2017 Sep

keys() is not supported in Internet Explorer.

JavaScript Array entries()


Example
Create an Array Iterator, and then iterate over the key/value pairs:

const fruits = ["Banana", "Orange", "Apple", "Mango"];


const f = fruits.entries();

for (let x of f) {
document.getElementById("demo").innerHTML += x;
}
Try it Yourself »

The entries() method returns an Array Iterator object with key/value pairs:

[0, "Banana"]
[1, "Orange"]
[2, "Apple"]
[3, "Mango"]

The entries() method does not change the original array.

Browser Support
entries() is an ES6 feature (JavaScript 2015).

ES6 is fully supported in all modern browsers since June 2017:

Chrome 51 Edge 15 Firefox 54 Saf

May 2016 Apr 2017 Jun 2017 Sep


entries() is not supported in Internet Explorer.

JavaScript Array with() Method


ES2023 added the Array with() method as a safe way to update elements in an
array without altering the original array.

Example
const months = ["Januar", "Februar", "Mar", "April"];
const myMonths = months.with(2, "March");
Try it Yourself »

JavaScript Array Spread (...)


The ... operator expands an iterable (like an array) into more elements:

Example
const q1 = ["Jan", "Feb", "Mar"];
const q2 = ["Apr", "May", "Jun"];
const q3 = ["Jul", "Aug", "Sep"];
const q4 = ["Oct", "Nov", "May"];

const year = [...q1, ...q2, ...q3, ...q4];

Try it Yourself »

Browser Support
... is an ES6 feature (JavaScript 2015).

ES6 is fully supported in all modern browsers since June 2017:


Chrome 51 Edge 15 Firefox 54 Saf

May 2016 Apr 2017 Jun 2017 Sep

... is not supported in Internet Explorer.

Complete Array Reference


For a complete Array reference, go to our:

Complete JavaScript Array Reference.

The reference contains descriptions and examples of all Array properties and
methods.

JavaScript Array Const


❮ PreviousNext ❯

ECMAScript 2015 (ES6)


In 2015, JavaScript introduced an important new keyword: const.

It has become a common practice to declare arrays using const:

Example
const cars = ["Saab", "Volvo", "BMW"];

Try it Yourself »
Cannot be Reassigned
An array declared with const cannot be reassigned:

Example
const cars = ["Saab", "Volvo", "BMW"];
cars = ["Toyota", "Volvo", "Audi"]; // ERROR

Try it Yourself »

Arrays are Not Constants


The keyword const is a little misleading.

It does NOT define a constant array. It defines a constant reference to an array.

Because of this, we can still change the elements of a constant array.

Elements Can be Reassigned


You can change the elements of a constant array:

Example
// You can create a constant array:
const cars = ["Saab", "Volvo", "BMW"];

// You can change an element:


cars[0] = "Toyota";

// You can add an element:


cars.push("Audi");

Try it Yourself »
Browser Support
The const keyword is not supported in Internet Explorer 10 or earlier.

The following table defines the first browser versions with full support for
the const keyword:

Chrome 49 IE 11 / Edge Firefox 36 Saf

Mar, 2016 Oct, 2013 Feb, 2015 Sep

Assigned when Declared


JavaScript const variables must be assigned a value when they are declared:

Meaning: An array declared with const must be initialized when it is declared.

Using const without initializing the array is a syntax error:

Example
This will not work:

const cars;
cars = ["Saab", "Volvo", "BMW"];

Arrays declared with var can be initialized at any time.

You can even use the array before it is declared:


Example
This is OK:

cars = ["Saab", "Volvo", "BMW"];


var cars;

Try it Yourself »

Const Block Scope


An array declared with const has Block Scope.

An array declared in a block is not the same as an array declared outside the
block:

Example
const cars = ["Saab", "Volvo", "BMW"];
// Here cars[0] is "Saab"
{
const cars = ["Toyota", "Volvo", "BMW"];
// Here cars[0] is "Toyota"
}
// Here cars[0] is "Saab"

Try it Yourself »

An array declared with var does not have block scope:

Example
var cars = ["Saab", "Volvo", "BMW"];
// Here cars[0] is "Saab"
{
var cars = ["Toyota", "Volvo", "BMW"];
// Here cars[0] is "Toyota"
}
// Here cars[0] is "Toyota"

Try it Yourself »
You can learn more about Block Scope in the chapter: JavaScript Scope.

ADVERTISEMENT

Redeclaring Arrays
Redeclaring an array declared with var is allowed anywhere in a program:

Example
var cars = ["Volvo", "BMW"]; // Allowed
var cars = ["Toyota", "BMW"]; // Allowed
cars = ["Volvo", "Saab"]; // Allowed

Redeclaring or reassigning an array to const, in the same scope, or in the same


block, is not allowed:

Example
var cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
{
var cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
}

Redeclaring or reassigning an existing const array, in the same scope, or in the


same block, is not allowed:

Example
const cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
var cars = ["Volvo", "BMW"]; // Not allowed
cars = ["Volvo", "BMW"]; // Not allowed

{
const cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
var cars = ["Volvo", "BMW"]; // Not allowed
cars = ["Volvo", "BMW"]; // Not allowed
}

Redeclaring an array with const, in another scope, or in another block, is


allowed:

Example
const cars = ["Volvo", "BMW"]; // Allowed
{
const cars = ["Volvo", "BMW"]; // Allowed
}
{
const cars = ["Volvo", "BMW"]; // Allowed
}

Complete Array Reference


For a complete Array reference, go to our:

Complete JavaScript Array Reference.

The reference contains descriptions and examples of all Array properties and
methods.

You might also like