JavaScript Exam
JavaScript Exam
❮ PreviousNext ❯
Strings are for storing text
Using Quotes
A JavaScript string is zero or more characters written inside quotes.
Example
let text = "John Doe";
Try it Yourself »
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.
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).
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 backslash escape character (\) turns special characters into string
characters:
\\ \ Backslash
Examples
\" inserts a double quote in a string:
let text = "We are the so-called \"Vikings\" from the north.";
Try it Yourself »
Try it Yourself »
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.
Example
document.getElementById("demo").innerHTML =
"Hello Dolly!";
Try it Yourself »
Example
document.getElementById("demo").innerHTML = "Hello " +
"Dolly!";
Try it Yourself »
Template Strings
Templates were introduced with ES6 (JavaScript 2016).
Example
let text =
`The quick
brown fox
jumps over
the lazy dog`;
Try it Yourself »
Note
Templates are not supported in Internet Explorer.
let x = "John";
But strings can also be defined as objects with the keyword new:
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.
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?
The reference contains descriptions and examples of all string properties and
methods.
Example
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
Try it Yourself »
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 »
Examples
Get the third letter of name:
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.
Browser Support
at() is an ES2022 feature.
Property Access [ ]
Example
let text = "HELLO WORLD";
let char = text[0];
Try it Yourself »
Note
Property access might be a little unpredictable:
Example
let text = "HELLO WORLD";
text[0] = "A"; // Gives no error, but does not work
Try it Yourself »
• slice(start, end)
• substring(start, end)
• substr(start, length)
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:
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:
This example slices out a portion of a string from position -12 to position -6:
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
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 »
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.
Example
let text1 = " Hello World! ";
let text2 = text1.trim();
Try it Yourself »
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 »
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 »
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:
Note
The padStart() method is a string method.
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.
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.
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.
Examples
Create copies of a text:
Syntax
string.repeat(count)
Parameters
Parameter Description
count Required.
The number of copies wanted.
Return Value
Type Description
Browser Support
repeat() is an ES6 feature (JavaScript 2015).
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.
If you want to replace all matches, use a regular expression with the /g flag set.
See examples below.
Example
let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");
Try it Yourself »
Example
let text = "Please visit Microsoft!";
let newText = text.replace("MICROSOFT", "W3Schools");
Try it Yourself »
Example
let text = "Please visit Microsoft!";
let newText = text.replace(/MICROSOFT/i, "W3Schools");
Try it Yourself »
Note
Regular expressions are written without quotes.
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.
Example
text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");
Try it Yourself »
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.
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 »
The reference contains descriptions and examples of all string properties and
methods.
avaScript String Search
❮ PreviousNext ❯
Example
let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate");
Try it Yourself »
Note
JavaScript counts positions from zero.
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 »
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 »
They accept the same arguments (parameters), and return the same value?
The two methods are NOT equal. These are the differences:
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
Examples
Perform a search for "ain":
let text = "The rain in SPAIN stays mainly in the plain";
text.match("ain");
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.
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.
Examples
Check if a string includes "world":
Examples
Returns true:
Returns false:
Returns false:
Returns true:
Examples
Check if a string ends with "Doe":
Try it Yourself »
Notes
endsWith() is case sensitive.
The reference contains descriptions and examples of all string properties and
methods.
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 »
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.
${...}
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
Variable Substitutions
Template Strings allow variables in strings:
Example
let firstName = "John";
let lastName = "Doe";
Try it Yourself »
Expression Substitution
Template Strings allow expressions in strings:
Example
let price = 10;
let VAT = 0.25;
Try it Yourself »
HTML Templates
Example
let header = "Template Strings";
let tags = ["template strings", "javascript", "es6"];
html += `</ul>`;
Try it Yourself »
Browser Support
Template Strings is an ES6 feature (JavaScript 2015).
JavaScript Arrays
❮ PreviousNext ❯
An array is a special variable, which can hold more than one value:
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?
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:
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 »
Example
const cars = new Array("Saab", "Volvo", "BMW");
Try it Yourself »
The two examples above do exactly the same.
For simplicity, readability and execution speed, use the array literal method.
ADVERTISEMENT
cars[0] = "Opel";
Example
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
Try it Yourself »
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Result:
Banana,Orange,Apple,Mango
Try it Yourself »
Example
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
Try it Yourself »
Array:
const person = ["John", "Doe", 46];
Try it Yourself »
Object:
const person = {firstName:"John", lastName:"Doe", age:46};
Try it Yourself »
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;
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.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
function myFunction(value) {
text += "<li>" + value + "</li>";
}
Try it Yourself »
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).
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 »
These two different statements both create a new empty array named points:
These two different statements both create a new array containing 6 numbers:
A Common Error
const points = [40];
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:
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 »
See Also:
Search Methods
Sort Methods
Iteration Methods
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 »
Examples
Get the third element of fruits using at():
Try it Yourself »
Try it Yourself »
The at() method is supported in all modern browsers since March 2022:
Chrome 92 Edge 92 Firefox 90 Sa
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.
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:
Try it Yourself »
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
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 »
Try it Yourself »
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.
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 »
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
Try it Yourself »
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.unshift("Lemon");
Try it Yourself »
Changing Elements
Array elements are accessed using their index number:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[0] = "Kiwi";
Try it Yourself »
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Kiwi";
Try it Yourself »
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0];
Try it Yourself »
Try it Yourself »
Note
The concat() method does not change the existing arrays. It always returns a
new array.
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:
Try it Yourself »
Try it Yourself »
Note
The copyWithin() method overwrites the existing values.
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.
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:
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:
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.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 2, "Lemon", "Kiwi");
Try it Yourself »
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.
Example
const months = ["Jan", "Feb", "Mar", "Apr"];
const spliced = months.toSpliced(0, 1);
Try it Yourself »
Example
Slice out a part of an array starting from array element 1 ("Orange"):
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"):
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.
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.
The reference contains descriptions and examples of all Array properties and
methods.
See Also:
Basic Methods
Sort Methods
Iteration Methods
Note: The first item has position 0, the second item has position 1, and so on.
Example
Search an array for the item "Apple":
Syntax
array.indexOf(item, start)
If the item is present more than once, it returns the position of the first
occurrence.
Example
Search an array for the item "Apple":
Syntax
array.lastIndexOf(item, start)
start Optional. Where to start the search. Negative values will start at the given position c
beginning
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.
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);
Browser Support
find() is an ES6 feature (JavaScript 2015).
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);
Browser Support
findIndex() is an ES6 feature (JavaScript 2015).
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.
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.
The reference contains descriptions and examples of all Array properties and
methods.
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 »
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 »
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.
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.
Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
Try it Yourself »
Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
Try it Yourself »
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
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 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:
<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 »
Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(){return 0.5 - Math.random()});
Try it Yourself »
The most popular correct method, is called the Fisher Yates shuffle, and was
introduced in data science as early as 1938!
Example
const points = [40, 100, 1, 5, 25, 10];
Try it Yourself »
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.
Example
function myArrayMin(arr) {
return Math.min.apply(null, arr);
}
Try it Yourself »
Example
function myArrayMax(arr) {
return Math.max.apply(null, arr);
}
Try it Yourself »
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:
Try it Yourself »
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:
Try it Yourself »
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.
Example
cars.sort(function(a, b){return a.year - b.year});
Try it Yourself »
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 »
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
The reference contains descriptions and examples of all Array properties and
methods.
See Also:
Basic Array Methods
Array Search Methods
Array Sort Methods
Example
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
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 »
The map() method does not execute the function for array elements without
values.
Example
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);
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 »
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:
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);
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 »
The reduce() method works from left-to-right in the array. See also reduceRight().
Example
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);
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);
Example
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction, 100);
function myFunction(total, value) {
return total + value;
}
Try it Yourself »
The reduceRight() works from right-to-left in the array. See also reduce().
Example
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduceRight(myFunction);
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 »
This example checks if all array values are larger than 18:
Example
const numbers = [45, 4, 9, 16, 25];
let allOver18 = numbers.every(myFunction);
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);
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:
Example
Create an Array Iterator object, containing the keys of the array:
Browser Support
keys() is an ES6 feature (JavaScript 2015).
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"]
Browser Support
entries() is an ES6 feature (JavaScript 2015).
Example
const months = ["Januar", "Februar", "Mar", "April"];
const myMonths = months.with(2, "March");
Try it Yourself »
Example
const q1 = ["Jan", "Feb", "Mar"];
const q2 = ["Apr", "May", "Jun"];
const q3 = ["Jul", "Aug", "Sep"];
const q4 = ["Oct", "Nov", "May"];
Try it Yourself »
Browser Support
... is an ES6 feature (JavaScript 2015).
The reference contains descriptions and examples of all Array properties and
methods.
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 »
Example
// You can create a constant array:
const cars = ["Saab", "Volvo", "BMW"];
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:
Example
This will not work:
const cars;
cars = ["Saab", "Volvo", "BMW"];
Try it Yourself »
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 »
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
Example
var cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
{
var cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // 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
}
Example
const cars = ["Volvo", "BMW"]; // Allowed
{
const cars = ["Volvo", "BMW"]; // Allowed
}
{
const cars = ["Volvo", "BMW"]; // Allowed
}
The reference contains descriptions and examples of all Array properties and
methods.