Array Object

The Array object is used to store multiple values in a single variable:

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

Array indexes are zero-based: The first element in the array is 0, the second is 1, and so on.

length

The length property sets or returns the number of elements in an array.

Return the length of an array:

array.length

 

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

let length = fruits.length;

 

Output: 4

 

Set the length of an array:

array.length = number

 

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

fruits.length = 2;

 

Output: Banana,Orange

concat()

The concat() method concatenates (joins) two or more arrays.

The concat() method returns a new array, containing the joined arrays.

The concat() method does not change the existing arrays.

Syntax

array1.concat(array2, array3, ..., arrayX)

 

Example

const arr1 = ["Cecilie", "Lone"];

const arr2 = ["Emil", "Tobias", "Linus"];

const arr3 = ["Robin"];

const children = arr1.concat(arr2,arr3);

 

Output: Cecilie, Lone, Emil, Tobias, Linus, Robin

copyWithin()

The copyWithin() method copies array elements to another position in the array.

The copyWithin() method overwrites the existing values.

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

Syntax

array.copyWithin(target, start, end)

 

Example

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

fruits.copyWithin(2, 0, 2);

 

Output: Banana,Orange,Banana,Orange,Kiwi

entries()

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

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

Syntax

array.entries()

 

Example

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

const f = fruits.entries();

 

Output: 0,Banana;1,Orange;2,Apple;3,Mango

every()

The every() method executes a function for each array element.

The every() method returns true if the function returns true for all elements.

The every() method returns false if the function returns false for one element.

The every() method does not execute the function for empty elements.

The every() method does not change the original array

Syntax

array.every(function(currentValue, index, arr), thisValue)

 

Example

const ages = [32, 33, 16, 40];

 

ages.every(checkAge)

 

function checkAge(age) {

return age > 18;

}

 

Output: false

some()

The some() method checks if any array elements pass a test (provided as a function).

The some() method executes the function once for each array element:

  • If the function returns true, some() returns true and stops.

  • If the function returns false, some() runs the next function.

The some() method does not execute the function for empty array elements.

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

Syntax

array.some(function(value, index, arr), this)

 

Example

const ages = [3, 10, 18, 20];

 

ages.some(checkAdult);

function checkAdult(age) {

return age > 18;

}

 

Output: true

fill()

The fill() method fills specified elements in an array with a value.

The fill() method overwrites the original array.

Start and end position can be specified. If not, all elements will be filled.

Syntax

array.fill(value, start, end)

 

Example

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

fruits.fill("Kiwi", 2, 4);

 

Output: Banana,Orange,Kiwi,Kiwi

filter()

The filter() method creates a new array filled with elements that pass a test provided by a function.

The filter() method does not execute the function for empty elements.

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

Syntax

array.filter(function(currentValue, index, arr), thisValue)

 

Example

const ages = [32, 33, 16, 40];

const result = ages.filter(checkAdult);

 

function checkAdult(age) {

return age >= 18;

}

 

Output: 32,33,40

find()

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

The find() method executes a function for each array element.

The find() method returns undefined if no elements are found.

The find() method does not execute the function for empty elements.

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

Syntax

array.find(function(currentValue, index, arr),thisValue)

 

Example

const ages = [3, 10, 18, 20];

const result = ages.find(checkAge);

 

function checkAge(age) {

return age > 18;

}

 

Output: 20

findIndex()

The findIndex() method executes a function for each array element.

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

The findIndex() method returns -1 if no match is found.

The findIndex() method does not execute the function for empty array elements.

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

Syntax

array.findIndex(function(currentValue, index, arr), thisValue)

 

Example

const ages = [3, 10, 18, 20];

const result = ages.find(checkAge);

 

function checkAge(age) {

return age > 18;

}

 

Output: 3

forEach()

The forEach() method calls a function for each element in an array.

The forEach() method is not executed for empty elements.

Syntax

array.forEach(function(currentValue, index, arr), thisValue)

 

Example

const fruits = ["apple", "orange", "cherry"];

fruits.forEach(myFunction);

 

Output: result of each array element

map()

map() creates a new array from calling a function for every array element.

map() calls a function once for each element in an array.

map() does not execute the function for empty elements.

map() does not change the original array.

Syntax

array.map(function(currentValue, index, arr), thisValue)

 

Example

const numbers = [65, 44, 12, 4];

const newArr = numbers.map(myFunction)

 

function myFunction(num) {

return num * 10;

}

 

Output: 650,440,120,40

from()

The Array.from() method returns an array from any object with a length property.

The Array.from() method returns an array from any iterable object.

Note: Array.from() is a static property of the JavaScript Array object. You can only use it as Array.from(). Using x.from(), where x is an array will return undefined.

Syntax

Array.from(object, mapFunction, thisValue)

 

Example

Array.from("ABCDEFG")

 

Output: A,B,C,D,E,F,G

includes()

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

The includes() method returns false if the value is not found.

The includes() method is case sensitive.

Syntax

array.includes(element, start)

 

Example

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

fruits.includes("Banana", 3);

 

Output: false

indexOf()

The indexOf() method returns the first index (position) of a specified value.

The indexOf() method returns -1 if the value is not found.

The indexOf() method starts at a specified index and searches from left to right.

By default the search starts at the first element and ends at the last.

Negative start values counts from the last element (but still searches from right to left).

Syntax

array.indexOf(item, start)

 

Example

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

let index = fruits.indexOf("Apple", 3);

 

Output: 4

lastIndexOf()

The lastIndexOf() method returns the last index (position) of a specified value.

The lastIndexOf() method returns -1 if the value is not found.

The lastIndexOf() starts at a specified index and searches from right to left.

By defalt the search starts at the last element and ends at the first.

Negative start values counts from the last element (but still searches from right to left).

Syntax

array.lastIndexOf(item, start)

 

Example

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

let index = fruits.lastIndexOf("Apple");

 

Output: 5

isArray()

The isArray() method returns true if an object is an array, otherwise false.

Note: Array.isArray() is a static property of the JavaScript Array object. You can only use it as Array.isArray(). Using x.isArray(), where x is an array will return undefined.

Syntax

Array.isArray(obj)

 

Example

let text = "W3Schools";

let result = Array.isArray(text);

 

Output: false

join()

The join() method returns an array as a string.

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

Any separator can be specified. The default is comma (,).

Syntax

array.join(separator)

 

Example

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

let text = fruits.join(" and ");

 

Output: Banana and Orange and Apple and Mango

keys()

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

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

Syntax

array.keys()

 

Example

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

const keys = Object.keys(fruits);

 

Output: 0,1,2,3

shift()

The shift() method removes the first item of an array.

The shift() method changes the original array.

The shift() method returns the shifted element.

Syntax

array.shift()

 

Example

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

fruits.shift();

 

Output: Banana, fruits = ["Orange", "Apple", "Mango"]

unshift()

The unshift() method adds new elements to the beginning of an array.

The unshift() method overwrites the original array.

Syntax

array.unshift(item1, item2, ..., itemX)

 

Example

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

fruits.unshift("Lemon","Pineapple");

 

Output: Lemon,Pineapple,Banana,Orange,Apple,Mango

pop()

The pop() method removes (pops) the last element of an array.

The pop() method changes the original array.

The pop() method returns the removed element.

Syntax

array.pop()

 

Example

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

fruits.pop();

 

Output: Mango; fruits = ["Banana", "Orange", "Apple"];

push()

The push() method adds new items to the end of an array.

The push() method changes the length of the array.

The push() method returns the new length.

Syntax

array.push(item1, item2, ..., itemX)

 

Example

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

fruits.push("Kiwi", "Lemon");

 

Output: Banana,Orange,Apple,Mango,Kiwi,Lemon

reduce()

The reduce() method executes a reducer function for array element.

The reduce() method returns a single value: the function's accumulated result.

The reduce() method does not execute the function for empty array elements.

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

Syntax

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

 

Example

const numbers = [15.5, 2.3, 1.1, 4.7];

document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);

 

function getSum(total, num) {

return total + num;

}

 

Output: 23.6

reduceRight()

The reduceRight() method executes a reducer function for each array element.

The reduceRight() method works from right to left.

The reduceRight() method returns a single value: the function's accumulated result.

The reduceRight() method does not execute the function for empty elements.

Syntax

array.reduceRight(function(total, currentValue, currentIndex, arr), initialValue)

 

Example

const numbers = [2, 45, 30, 100];

document.getElementById("demo").innerHTML = numbers.reduceRight(getSum);

 

function getSum(total, num) {

return total - num;

}

 

Output: 23

sort()

The sort() sorts the elements of an array.

The sort() overwrites the original array.

The sort() sorts the elements as strings in alphabetical and ascending order.

Note: Sorting alphabetically works well for strings ("Apple" comes before "Banana"). But, sorting numbers can produce incorrect results. "25" is bigger than "100", because "2" is bigger than "1". You can fix this by providing a "compare function" (See examples below).

Syntax

array.sort(compareFunction)

 

Example

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

fruits.sort();

 

Output: Apple,Banana,Mango,Orange

reverse()

The reverse() method reverses the order of the elements in an array.

The reverse() method overwrites the original array.

Syntax

array.reverse()

 

Example

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

fruits.reverse();

 

Output: Mango,Apple,Orange,Banana

slice()

The slice() method returns selected elements in an array, as a new array.

The slice() method selects from a given start, up to a (not inclusive) given end.

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

Syntax

array.slice(start, end)

 

Example

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

const citrus = fruits.slice(1, 3);

 

Output: Orange,Lemon

splice()

The splice() method adds and/or removes array elements.

The splice() method overwrites the original array.

Syntax

array.splice(index, howmany, item1, ....., itemX)

 

Example

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

 

fruits.splice(2, 1, "Lemon", "Kiwi");

 

Output: Banana,Orange,Lemon,Kiwi,Mango

Strings

A JavaScript string stores a series of characters like "John Doe".

A string can be any text inside double or single quotes:

let carName1 = "Volvo XC60";

let carName2 = 'Volvo XC60';

String indexes are zero-based:

The first character is in position 0, the second in 1, and so on.

String Properties and Methods

Normally, strings like "John Doe", cannot have methods or properties because they are not objects.

But with JavaScript, methods and properties are also available to strings, because JavaScript treats strings as objects when executing methods and properties.

length

The length property returns the length of a string.

The length property of an empty string is 0.

Syntax

string.length

Example

let text = "Hello World!";

let length = text.length;

 

Output: 12

charAt()

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

The index of the first character is 0, the second 1, ...

The index of the last character is string length - 1 (See Examples below).

Syntax

string.charAt(index)

 

Example

let text = "HELLO WORLD";

let letter = text.charAt(1);

 

Output: E

charCodeAt()

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

Syntax

string.charCodeAt(index)

 

Example

let text = "HELLO WORLD";

let code = text.charCodeAt(1);

 

Output: 69

concat()

The concat() method joins two or more strings.

The concat() method does not change the existing strings.

The concat() method returns a new string.

Syntax

string.concat(string1, string2, ..., stringX)

 

Example

let text1 = "Hello";

let text2 = "world!";

let result = text1.concat(" ", text2);

 

Output: Hello world!

startsWith()

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

Otherwise it returns false.

The startsWith() method is case sensitive.

Syntax

string.startsWith(searchValue, start)

 

Example

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

text.startsWith("world", 6);

 

Output: true

endsWith()

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

Otherwise it returns false.

The endsWith() method is case sensitive.

Syntax

string.endsWith(searchvalue, length)

 

Example

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

text.endsWith("world", 11);

 

Output: true

fromCharCode()

The String.fromCharCode() method converts Unicode values to characters.

The String.fromCharCode() is a static method of the String object.

The syntax is always String.fromCharCode().

You cannot use myString.fromCharCode().

Syntax

String.fromCharCode(n1, n2, ..., nX)

 

Example

let text = String.fromCharCode(72, 69, 76, 76, 79);

 

Output: Hello

includes()

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

Otherwise it returns false.

The includes() method is case sensitive.

Syntax

string.includes(searchvalue, start)

 

Example

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

let result = text.includes("world");

Output: true

 

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

let result = text.includes("world", 12);

Output: false

indexOf()

The indexOf() method returns the position of the first occurrence of a value in a string.

The indexOf() method returns -1 if the value is not found.

The indexOf() method is case sensitive

Syntax

string.indexOf(searchvalue, start)

 

Example

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

text.indexOf("e", 5);

 

Output: 14

lastIndexOf()

The lastIndexOf() method returns the index (position) of the last occurrence of a specified value in a string.

The lastIndexOf() method searches the string from the end to the beginning.

The lastIndexOf() method returns the index from the beginning (position 0).

Syntax

string.lastIndexOf(searchvalue, start)

 

Example

let text = "Hello planet earth, you are a great planet.";

let result = text.lastIndexOf("planet", 20);

 

Output: 6

localeCompare()

The localeCompare() method compares two strings in the current locale.

The localeCompare() method returns sort order -1, 1, or 0 (for before, after, or equal).

The current locale is based on the language settings of the browser.

Syntax

string.localeCompare(compareString)

 

Example

let text1 = "cd";

let text2 = "ab";

let result = text1.localeCompare(text2);

 

Output: 1

match()

The match() method matches a string against a regular expression **

The match() method returns an array with the matches.

The match() method returns null if no match is found.

Syntax

string.match(match)

 

A seach for "ain" using a string:

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

text.match("ain");

Output: ain

 

A seach for "ain" using a regular expression:

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

text.match(/ain/);

Output: ain

 

A global seach for "ain":

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

text.match(/ain/g);

Output: ain,ain,ain

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.

Syntax

string.repeat(count)

 

Example

let text = "Hello world!";

let result = text.repeat(2);

 

Output: Hello world!Hello world!

replace()

The replace() method searches a string for a value or a regular expression.

The replace() method returns a new string with the value(s) replaced.

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

Syntax

string.replace(searchValue, newValue)

 

Example

let text = "Visit Microsoft!";

let result = text.replace("Microsoft", "W3Schools");

Output: Visit W3Schools!

 

A global replacement:

let text = "Mr Blue has a blue house and a blue car";

let result = text.replace(/blue/g, "red");

Output: Mr Blue has a red house and a red car.

slice()

The slice() method extracts a part of a string.

The slice() method returns the extracted part in a new string.

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

The start and end parameters specifies the part of the string to extract.

The first position is 0, the second is 1, ...

A negative number selects from the end of the string.

Syntax

string.slice(start, end)

 

Example

let text = "Hello world!";

let result = text.slice(0, 5);

 

Output: Hello

split()

The split() method splits a string into an array of substrings.

The split() method returns the new array.

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

If (" ") is used as separator, the string is split between words.

Syntax

string.split(separator, limit)

 

Example

let text = "How are you doing today?";

const myArray = text.split(" ");

Output: How,are,you,doing,today?

 

Split the words, and return the second word:

let text = "How are you doing today?";

const myArray = text.split(" ");

let word = myArray[1];

Output: are

 

Split the characters, including spaces:

const myArray = text.split("");

Output: H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?

 

Use the limit parameter:

const myArray = text.split(" ", 3);

Output: How,are,you

substr()

The substr() method extracts a part of a string.

The substr() method begins at a specified position, and returns a specified number of characters.

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

Syntax

string.substr(start, length)

 

Example

let text = "Hello world!";

let result = text.substr(1, 4);

 

Output: ello

substring()

The substring() method extracts characters, between two indices (positions), from a string, and returns the substring.

The substring() method extracts characters from start to end (exclusive).

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

If start is greater than end, arguments are swapped: (4, 1) = (1, 4).

Syntax

string.substring(start, end)

 

Example

let text = "Hello world!";

let result = text.substring(1, 4);

 

Output: ell

toLowerCase()

The toLowerCase() method converts a string to lowercase letters.

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

Syntax

string.toLowerCase()

 

Example

let text = "Hello World!";

let result = text.toLowerCase();

 

Output: hello world!

 

toLocaleLowerCase()The toLocaleLowerCase() returns the same result as toLowerCase(), except for locales that conflict with the regular Unicode case mappings (such as Turkish).
toUpperCase()

The toUpperCase() method converts a string to uppercase letters.

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

Syntax

string.toUpperCase()

 

Example

let text = "Hello World!";

let result = text.toUpperCase();

 

Output: HELLO WORLD!

 

toLocaleUpperCase()The toLocaleUpperCase() returns the same result as toUpperCase(), except for locales that conflict with the regular Unicode case mappings (such as Turkish).
trim()

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

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

Syntax

string.trim()

 

Example

let text = "    Hello World!    ";

let result = text.trim();

 

Output: Hello World!

Numbers

JavaScript has only one type of number.

Numbers can be written with, or without, decimals:

let x = 3.14; // A number with decimals

let y = 34; // A number without decimals

 

Extra large or extra small numbers can be written with scientific (exponent) notation:

let x = 123e5; // 12300000

let y = 123e-5; // 0.00123

Number Properties

MAX_VALUE

Returns the largest number possible in JavaScript

Number.MAX_VALUE returns the largest number possible in JavaScript.

Number.MAX_VALUE has the value of 1.7976931348623157e+308.

Numbers larger than MAX_VALUE are represented as Infinity.

Note: MAX_VALUE is a property of the JavaScript Number object. You can only use it as Number.MAX_VALUE. Using x.MAX_VALUE, where x is a variable, will return undefined.

Syntax

Number.MAX_VALUE

 

Example

let x = Number.MAX_VALUE;

Output: 1.7976931348623157e+308

MIN_VALUE

Returns the smallest number possible in JavaScript

Number.MIN_VALUE returns the smallest number possible in JavaScript.

Number.MIN_VALUE has a value of 5e-324.

Note: MIN_VALUE is the value closest to 0. Numbers smaller than this are converted to 0. The most negative number is the negative MAX_NUMBER.

Note: MIN_VALUE is a property of the JavaScript Number object. You can only use it as Number.MIN_VALUE. Using x.MIN_VALUE, where x is a variable, will return undefined.

Syntax

Number.MIN_VALUE

 

Example

let x = Number.MIN_VALUE;

Output: 5e-324

POSITIVE_INFINITY

POSITIVE_INFINITY returns positive infinity.

POSITIVE_INFINITY is "something higher than any other number".

You can only use it as Number.POSITIVE_INFINITY.

Syntax

Number.POSITIVE_INFINITY

 

Example

let x = Number.POSITIVE_INFINITY;

Output: Infinity

NEGATIVE_INFINITY

Number.NEGATIVE_INFINITY returns negative infinity.

Number.NEGATIVE_INFINITY is "a number lower than any other number".

You can only use it as Number.NEGATIVE_INFINITY.

Syntax

Number.NEGATIVE_INFINITY

 

Example

let x = 100;

x.NEGATIVE_INFINITY;

Output: -Infinity

NaN

In JavaScript, NaN is short for "Not-a-Number".

In JavaScript, NaN is a number that is not a legal number.

The Global NaN property is the same as the Number.Nan property.

Syntax

Number.NaN

 

Example

let x = Number.NaN;

let x = NaN;

Output: NaN; Nan

Number Methods

isFinite()

The Number.isFinite() method returns true if a number is a finite number.

Infinite (not finite) numbers are Infinity, -Infinity, or NaN

Otherwise it returns false.

Syntax

Number.isFinite(value)

 

Example

Number.isFinite(123)

Output: true

 

Number.isFinite("123")

Output: false

isInteger()

The Number.isInteger() method returns true if a value is an integer of the datatype Number.

Otherwise it returns false.

Syntax

Number.isInteger(value)

 

Example

Number.isInteger(5-2);

Output: true

 

Number.isInteger(5/2);

Output: false

isNaN()

In JavaScript, NaN is short for "Not-a-Number".

In JavaScript, NaN is a number that is not a legal number.

The Number.isNaN() method returns true if the value is NaN, and the type is a Number.

Syntax

Number.isNaN(value)

 

Example

Number.isNaN(123);

Output: false

 

Number.isNaN(-1.23);

Output: false

 

Number.isNaN('123');

Output: false

 

Number.isNaN(0/0);

Output: false

isSafeInteger()

The Number.isSafeInteger() method returns trueif a number is a safe integer.

Otherwise it returns false.

A safe integer is an integer that can be exactly represented as an IEEE-754 double precision number: all integers from (253 - 1) to -(253 - 1).

Syntax

Number.isSafeInteger(value)

 

Example

Number.isSafeInteger(5e100);

Output: false

 

Number.isSafeInteger(-123);

Output: true

 

Number.isSafeInteger('123');

Output: false

toExponential(x)

The toExponential() method converts a number into an exponential notation.

Syntax

number.toExponential(x)

 

Example

let num = 5.56789;

let n = num.toExponential();

Output: 5.56789e+0

 

let num = 5.56789;

let n = num.toExponential(3);

Output: 5.568e+0

toFixed(x)

The toFixed() method converts a number to a string.

The toFixed() method rounds the string to a specified number of decimals.

Syntax

number.toFixed(x)

 

Example

let num = 5.56789;

let n = num.toFixed();

Output: 6

 

let num = 5.56789;

let n = num.toFixed(2);

Output: 5.57

toLocaleString()

The toLocaleString() returns a number as a string, using local language format.

The language format depends on the locale setup on your computer.

Syntax

number.toLocaleString(locales, options)

 

Example

let num = 1000000;

let text = num.toLocaleString();

Output: 1,000,000

 

Format a number into a string, using the locale specific of FINLAND:

let num = 1000000;

let text = num.toLocaleString("fi-FI");

Output: 1 000 000

 

Format a number into a currency string, using the locale specific of USA:

let num = 1000000;

let text = num.toLocaleString("en-US", {style:"currency", currency:"USD"});

Output: $1,000,000.00

toPrecision(x)

The toPrecision() method formats a number to a specified length.

A decimal point and nulls are added (if needed), to create the specified length.

Syntax

number.toPrecision(x)

 

Example

let num = 0.001658853;

num.toPrecision(2);

num.toPrecision(3);

num.toPrecision(10);

 

Output: 0.0017; 0.00166; 0.001658853000

Math Object

The Math object allows you to perform mathematical tasks.

Math is not a constructor. All properties/methods of Math can be called by using Math as an object, without creating it:

let x = Math.PI;

let y = Math.sqrt(16);

Math Object Properties

PropertyDescription
EMath.E returns Euler's number, base of natural logarithms, approximately 2.718.
LN2Math.LN2 returns the natural logarithm of 2, approximately 0.693.
LN10Math.LN10 returns the natural logarithm of 10, approximately 2.302.
LOG2EMath.LOG2E returns the base-2 logarithm of E, approximately 1.442.
LOG10EMath.LOG10E returns the base-10 logarithm of E, approximately 0.434.
PIMath.PI returns PI (the ratio of a circle's area to the square of its radius, approximately 3.14)
SQRT1_2Math.SQRT1_2 returns the square root of 1/2, approximately 0.707.
SQRT2Math.SQRT2 returns the square root of 2, approximately 1.414.

Math Object Methods

MethodDescription
abs(x)The Math.abs() method returns the absolute value of a number.
max(x, y, z, ..., n)Returns the number with the highest value
min(x, y, z, ..., n)Returns the number with the lowest value
sign(x)Returns the sign of a number (checks whether it is positive, negative or zero)
random()Returns a random number between 0 and 1
clz32(x)Returns the number of leading zeros in a 32-bit binary representation of x
fround(x)Returns the nearest (32-bit single precision) float representation of a number
round(x)Rounds x to the nearest integer
ceil(x) Returns x, rounded upwards to the nearest integer
floor(x)Returns x, rounded downwards to the nearest integer
sqrt(x)Returns the square root of x
cbrt(x)Returns the cubic root of x
pow(x, y)Returns the value of x to the power of y
exp(x)Returns the value of Ex
expm1(x)Returns the value of Ex minus 1
log(x)Returns the natural logarithmof x
log2(x)Returns the base-2 logarithm of x
log10(x)Returns the base-10 logarithm of x
log1p(x)Returns the natural logarithm of 1 + x
trunc(x)Returns the integer part of a number (x)
sin(x)Returns the sine of x (x is in radians)
asin(x)Returns the arcsine of x, in radians
sinh(x)Returns the hyperbolic sine of x
asinh(x)Returns the hyperbolic arcsine of x
cos(x)Returns the cosine of x (x is in radians)
acos(x)Returns the arccosine of x, in radians
cosh(x)Returns the hyperbolic cosine of x
acosh(x)Returns the hyperbolic arccosine of x
tan(x)Returns the tangent of an angle
atan(x)Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y, x)Returns the arctangent of the quotient of its arguments
tanh(x)Returns the hyperbolic tangent of a number
atanh(x)Returns the hyperbolic arctangent of x

Date Object

The Date object is used to work with dates and times.

Date objects are created with new Date().

There are four ways of instantiating a date:

new Date();

new Date(milliseconds);

new Date(dateString);

new Date(year, month, day, hours, minutes, seconds, milliseconds);

Date Methods

MethodDescription
getFullYear()Returns the year
getMonth()Returns the month (from 0-11)
getDate()Returns the day of the month (from 1-31)
getDay()Returns the day of the week (from 0-6)
getHours()Returns the hour (from 0-23)
getMinutes()Returns the minutes (from 0-59)
getSeconds()Returns the seconds (from 0-59)
getMilliseconds()Returns the milliseconds (from 0-999)
getTime()Returns the number of milliseconds since midnight Jan 1 1970, and a specified date
now()Returns the number of milliseconds since midnight Jan 1, 1970
parse()Parses a date string and returns the number of milliseconds since January 1, 1970
getUTCFullYear()Returns the year, according to universal time
getUTCMonth()Returns the month, according to universal time (from 0-11)
getUTCDate()Returns the day of the month, according to universal time (from 1-31)
getUTCDay()Returns the day of the week, according to universal time (from 0-6)
getUTCHours()Returns the hour, according to universal time (from 0-23)
getUTCMinutes()Returns the minutes, according to universal time (from 0-59)
getUTCSeconds()Returns the seconds, according to universal time (from 0-59)
getUTCMilliseconds()Returns the milliseconds, according to universal time (from 0-999)
UTC()Returns the number of milliseconds in a date since midnight of January 1, 1970, according to UTC time
getTimezoneOffset()Returns the time difference between UTC time and local time, in minutes
setFullYear()Sets the year of a date object
setMonth()Sets the month of a date object
setDate()Sets the day of the month of a date object
setHours()Sets the hour of a date object
setMinutes()Set the minutes of a date object
setSeconds()Sets the seconds of a date object
setMilliseconds()Sets the milliseconds of a date object
setTime()Sets a date to a specified number of milliseconds after/before January 1, 1970
setUTCFullYear()Sets the year of a date object, according to universal time
setUTCMonth()Sets the month of a date object, according to universal time
setUTCDate()Sets the day of the month of a date object, according to universal time
setUTCHours()Sets the hour of a date object, according to universal time
setUTCMinutes()Set the minutes of a date object, according to universal time
setUTCSeconds()Set the seconds of a date object, according to universal time
setUTCMilliseconds()Sets the milliseconds of a date object, according to universal time
toDateString()Converts the date portion of a Date object into a readable string
toTimeString()Converts the time portion of a Date object to a string
toLocaleDateString()Returns the date portion of a Date object as a string, using locale conventions
toLocaleTimeString()Returns the time portion of a Date object as a string, using locale conventions
toLocaleString()Converts a Date object to a string, using locale conventions
toUTCString()Converts a Date object to a string, according to universal time
toISOString()Returns the date as a string, using the ISO standard
toJSON()Returns the date as a string, formatted as a JSON date
toString()Converts a Date object to a string
valueOf()Returns the primitive value of a Date object

Global Properties & Methods

Global Properties

Infinity

A numeric value that represents positive/negative infinity

NaN

"Not-a-Number" value

undefined

Indicates that a variable has not been assigned a value

constructor

The constructor property returns the function that created the Object prototype.

function Object() { [native code] }

prototype

prototype allows you to add new properties and methods to objects.

Syntax

object.prototype.name = value

 

Example 1

Array.prototype.myUcase = function() {

for (let i = 0; i < this.length; i++) {

this[i] = this[i].toUpperCase();

}

};

 

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

fruits.myUcase();

 

Output: BANANA,ORANGE,APPLE,MANGO

 

Example 2

function Person(first, last, age, eyecolor) {

this.firstName = first;

this.lastName = last;

this.eyeColor = eyecolor;

}

 

const.myFather = new Person("John", "Doe", "Blue", );

 

Person.prototype.nationality = "English";

 

Output: myFather.nationality = "English";

Global Methods

encodeURI()

The encodeURI() method encodes a URI.

The encodeURI() method does not encode characters like: , / ? : @ & = + $ * #

let uri = "my test.asp?name=ståle&car=saab";

let encoded = encodeURI(uri);

 

Encoded URI: my%20test.asp?name=st%C3%A5le&car=saab

decodeURI()

The decodeURI() method decodes a URI.

let uri = "my test.asp?name=ståle&car=saab";

let decoded = decodeURI(encoded);

 

Decoded URI:

encodeURIComponent()

The encodeURIComponent() method encodes a URI component.

The encodeURIComponent() method encodes special characters including: , / ? : @ & = + $ #

let uri = "https://w3schools.com/my test.asp?name=ståle&car=saab";

let encoded = encodeURIComponent(uri);

 

Encoded URI: https%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab

decodeURIComponent()

The decodeURIComponent() method decodes a URI component.

let uri = "https://w3schools.com/my test.asp?name=ståle&car=saab";

let decoded = decodeURIComponent(encoded);

 

Decoded URI: https://w3schools.com/my test.asp?name=ståle&car=saab

isFinite()

The Number.isFinite() method returns true if a number is a finite number.

Infinite (not finite) numbers are Infinity, -Infinity, or NaN

Otherwise it returns false.

Syntax

Number.isFinite(value)

 

Example

Number.isFinite(123)

Output: true

 

Number.isFinite("123")

Output: false

isNaN()

In JavaScript, NaN is short for "Not-a-Number".

In JavaScript, NaN is a number that is not a legal number.

The Number.isNaN() method returns true if the value is NaN, and the type is a Number.

Syntax

Number.isNaN(value)

 

Example

Number.isNaN(123);

Output: false

 

Number.isNaN(-1.23);

Output: false

 

Number.isNaN('123');

Output: false

 

Number.isNaN(0/0);

Output: false

Number()

The Number() method converts a value to a number.

If the value cannot be converted, NaN is returned.

Number(true);

Number(false);

Number(new Date());

 

Output: 1; 0; 1649293650949

parseFloat()

The parseFloat() method parses a value as a string and returns the first number.

Note: If the first character cannot be converted, NaN is returned. Leading and trailing spaces are ignored. Only the first number found is returned.

parseFloat(10);

parseFloat("10");

parseFloat("10.33");

parseFloat("34 45 66");

parseFloat("He was 40");

 

Output: 10;10;10.33;34;NaN

parseInt()

The parseInt method parses a value as a string and returns the first integer.

A radix parameter specifies the number system to use:

2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal.

If radix is omitted, JavaScript assumes radix 10. If the value begins with "0x", JavaScript assumes radix 16.

Syntax

parseInt(string, radix)

 

Example

parseInt("10");

parseInt("10.00");

parseInt("10.33");

parseInt("34 45 66");

parseInt(" 60 ");

parseInt("40 years");

parseInt("He was 40");

 

Output: 10;10;10;34;60;40;NaN

String()

The String() method converts a value to a string.

Note: The String() method returns the same as the toString() method for any value.

String(new Date());

String("12345");

String(12345);

 

Output: Wed Apr 06 2022 21:11:55 GMT-0400 (EDT);12345;12345

toString()

The toString() method returns a string verion of an object

The toString() method does not change the original object.

Syntax

array.toString()

 

Example

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

let text = fruits.toString();

 

Output: Banana,Orange,Apple,Mango

valueOf()

The valueOf() method returns the object itself.

The valueOf() method does not change the original object.

fruits.valueOf() returns the same as fruits.

Syntax

array.valueOf()

 

Example

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

const myArray = fruits.valueOf();

 

Output: Banana,Orange,Apple,Mango; same as const myArray = fruits;

RegExp Object

A regular expression is a pattern of characters.

The pattern is used to do pattern-matching "search-and-replace" functions on text.

In JavaScript, a RegExp Object is a pattern with Properties and Methods.

Syntax

/pattern/modifier(s);

 

Example

let pattern = /w3schools/i;

 

ValueDescription
w3schoolsThe pattern to search for
/w3schools/A regular expression
/w3schools/iA case-insensitive regular expression

Modifiers

Modifiers are used to perform case-insensitive and global searches:

g

Perform a global match (find all matches rather than stopping after the first match)

let pattern = /[1-4]/g;

i

Perform case-insensitive matching

let pattern = /w3schools/i;

m

Perform multiline matching

Brackets

Brackets are used to find a range of characters:

[abc]

Brackets [abc] specifies matches for the characters inside the brackets.

Brackets can define single characters, groups, or character spans:

let text = "Do you know if this is all there is?";

let pattern = /[is]/gi;

Output: i,i,s,i,s,i,s

 

ValueDescription
[abc]Any of the characters a, b, or c
[A-Z]Any character from uppercase A to uppercase Z
[a-z]Any character from lowercase a to lowercase z
[A-z]Any character from uppercase A to lowercase z
[^abc]

Brackets [^abc] specifies matches for any character NOT between the brackets.

Brackets can define single characters, groups, or character spans:

let pattern = /[^h]/g;

 

ValueDescription
[^abc]Not any of the characters a, b, or c
[^A-Z]Not any character from uppercase A to uppercase Z
[^a-z]Not any character from lowercase a to lowercase z
[^A-z]Not any character from uppercase A to lowercase z
[0-9]

The [0-9] expression is used to find any character between the brackets.

The digits inside the brackets can be any numbers or span of numbers from 0 to 9.

let text = "123456789";

let pattern = /[1-4]/g;

 

Output: 1,2,3,4

[^0-9]

Find any character NOT between the brackets (any non-digit)

let text = "123456789";

let pattern = /[^1-4]/g;

 

Output: 5,6,7,8,9

(x|y)

The (x|y) expression is used to find any of the alternatives specified.

The alternatives can be of any characters.

let pattern= /(red|green)/g;

let pattern = /(0|5|7)/g;

Metacharacters

Metacharacters are characters with a special meaning:

.

Find a single character, except newline or line terminator

let text = "That's hot!";

let pattern = /./g;

Output: T,h,a,t,',s, ,h,o,t,!

 

let text = "That's hot!";

let pattern = /h.t/g;

Output: hat,hot

\w

The \w metacharacter matches word characters.

A word character is a character a-z, A-Z, 0-9, including _ (underscore).

let text = "Give 100%!";

let pattern = /\w/g;

 

Output: G,i,v,e,1,0,0

\W

The \W metacharacter matches non-word characters:

let text = "Give 100%!";

let pattern = /\W/g;

 

Output: ,%,!

\d

The \d metacharacter matches digits from 0 to 9.

let text = "Give 100%!";

let pattern= /\d/g;

 

Output: 1,0,0

\D

The \D metacharacter matches non-digit characters.

let text = "Give 100%!";

let pattern = /\D/g;

 

Output: G,i,v,e, ,%,!

\s

The \s metacharacter matches whitespace character.

Whitespace characters can be:

  • A space character

  • A tab character

  • A carriage return character

  • A new line character

  • A vertical tab character

  • A form feed character

let text = "Is this all there is?";

let pattern = /\s/g;

 

Output: , , ,

\S

The \S metacharacter matches non-whitespace characters.

let text = "Is this all there is?";

let pattern = /\S/g;

 

Output: I,s,t,h,i,s,a,l,l,t,h,e,r,e,i,s,?

\b

The \b metacharacter matches at the beginning or end of a word.

Search for the pattern LO at the beginning of a word like this: \bLO

Search for the pattern LO at the end of a word like this: LO\b

let text = "HELLO, LOOK AT YOU";

let pattern = /\bLO/;

Output: 7

 

let text = "HELLO, LOOK AT YOU";

let pattern = /LO\b/;

Output: 3

\B

The \B metacharacter matches NOT at the beginning/end of a word.

let text = "HELLO, LOOK AT YOU";

let pattern = /\BLO/;

Output: 3

 

let text = "HELLO, LOOK AT YOU";

let pattern = /LO\B/;

Output: 7

\0

The \0 metacharacter maches NUL characters (\0).

let text = "Visit W3Schools.\0Learn Javascript.";

let pattern = /\0/;

Output: 16

\n

The \n character matches newline characters (\n).

let text = "Visit W3Schools.\nLearn Javascript.";

let pattern = /\n/;

Output: 16

\f

Find a form feed character

\r

Find a carriage return character

\t

Find a tab character

\v

Find a vertical tab character

\xxx

The \xxx metacharacters matches the Latin character by an octal number (xxx).

let text = "Visit W3Schools. Hello World!";

let pattern = /\127/g;

Output: W,W; octn(127)=W

\xdd

The \xdd metacharacters matches Latin characters specified by a hexadecimal number (dd).

let text = "Visit W3Schools. Hello World!";

let pattern = /\x57/g;

Output: W,W; hex(57)=W

\udddd

The \ udddd metacharacters matches Unicode characters specified by a hexadecimal number (dddd).

let text = "Visit W3Schools. Hello World!";

let pattern = /\u0057/g;

Output: W,W; Uni(u0057)=W

Quantifiers

n+

The n+ quantifier matches any string that contains at least one n.

let text = "Hellooo World! Hello W3Schools!";

let pattern = /o+/g;

 

Output: ooo,o,o,oo

n*

The n* quantifier matches any string that contains zero or more occurrences of n.

let text = "Hellooo World! Hello W3Schools!";

let pattern = /lo*/g;

 

Output: l,looo,l,l,lo,l

n?

The n? quantifier matches any string that contains zero or one occurrences of n.

let text = "1, 100 or 1000?";

let pattern = /10?/g;

 

Output: 1,10,10

n{X}

The n{X} quantifier matches any string that contains a sequence of X n's. X must be a number.

let text = "100, 1000 or 10000?";

let pattern = /d{4}/g;

 

Output: 1000,1000

n{X,Y}

The n{X,Y} quantifier matches any string that contains a sequence of X to Y n's.

let text = "100, 1000 or 10000?";

let pattern = /d{3,4}/g;

 

Output: 100,1000,1000

n{X,}

The n{X,} quantifier matches any string that contains a sequence of at least X n's.

let text = "100, 1000 or 10000?";

let pattern = /\d{3,}/g;

 

Output: 100,1000,10000

n$

The n$ quantifier matches any string with n at the end of it.

let text = "Is this his";

let pattern = /is$/;

 

Output: is

^n

The ^n quantifier matches any string with n at the beginning of it.

let text = "Is this his";

let pattern = /^Is/g;

 

Output: Is

?=n

The ?=n quantifier matches any string that is followed by a specific string n.

let text = "Is this all there is";

let pattern = /is(?= all)/g;

 

Output: is

?!n

The ?!n quantifier matches any string that is not followed by a specific string n.

let text = "Is this all there is";

let pattern = /is(?! all)/gi;

 

Output: Is,is

RegExp Object Properties

global

The global property specifies whether or not the "g" modifier is set.

This property returns true if the "g" modifier is set, otherwise it returns false.

ignoreCase

The ignoreCase property specifies whether or not the "i" modifier is set.

This property returns true if the "i" modifier is set, otherwise it returns false.

lastIndex

The lastIndex property specifies the index at which to start the next match.

Note: This property only works if the "g" modifier is set.

This property returns an integer that specifies the character position immediately after the last match found by exec( ) or test( ) methods.

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

let pattern = /ain/g;

 

let result = "";

while (pattern.test(text)==true) {pattern.lastIndex}

 

Output: 8,17,28,43

multiline

The multiline property specifies whether or not the m modifier is set.

This property returns true if the "m" modifier is set, otherwise it returns false.

source

The source property returns the text of the RegExp pattern.

let text = "Visit W3Schools";

let pattern = /W3S/g;

let result = pattern.source;

 

Output: W3S

RegExp Object Methods

exec()

The exec() method tests for a match in a string.

If it finds a match, it returns a result array, otherwise it returns null.

let text = "The best things in life are free";

let result = /e/.exec(text);

 

Output: e

test()

The test() method tests for a match in a string.

If it finds a match, it returns true, otherwise it returns false.

let text = "The best things in life are free"; let pattern = /e/;

let result = pattern.test(text);

 

Output: true

Classes

A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class, and the properties are assigned inside a constructor() method:

class Car { // Create a class

constructor(brand) { // Class constructor

this.carname = brand; // Class body/properties

}

}

 

mycar = new Car("Ford"); // Create an object of Car class

constructor()

The constructor() method is a special method for creating and initializing objects created within a class.

The constructor() method is called automatically when a class is initiated, and it has to have the exact name "constructor", in fact, if you do not have a constructor method, JavaScript will add an invisible and empty constructor method.

Note: A class cannot have more than one constructor() method. This will throw a SyntaxError.

You can use the super() method to call the constructor of a parent class (see "More Examples" below).

class Car {

constructor(brand) { // Constructor

this.carname = brand;

}

}

 

mycar = new Car("Ford");

extends

The extends keyword is used to create a child class of another class (parent).

The child class inherits all the methods from another class.

Inheritance is useful for code reusability: reuse properties and methods of an existing class when you create a new class.

Note: From the example above; The super() method refers to the parent class. By calling the super() method in the constructor method, we call the parent's constructor method and gets access to the parent's properties and methods.

Syntax

class childClass extends parentClass

 

Example

class Car {

constructor(brand) {

this.carname = brand;

}

present() {

return 'I have a ' + this.carname;

}

}

 

class Model extends Car {

constructor(brand, mod) {

super(brand);

this.model = mod;

}

show() {

return this.present() + ', it is a ' + this.model;

}

}

 

mycar = new Model("Ford", "Mustang");

document.getElementById("demo").innerHTML = mycar.show();

static

The static keyword defines static methods for classes.

Static methods are called directly on the class (Car from the example above) - without creating an instance/object (mycar) of the class.

class Car {

constructor(brand) {

this.carname = brand;

}

static hello() { // static method

return "Hello!!";

}

}

 

mycar = new Car("Ford");

 

//Call 'hello()' on the class Car:

document.getElementById("demo").innerHTML = Car.hello();

 

//and NOT on the 'mycar' object:

//document.getElementById("demo").innerHTML = mycar.hello();

//this would raise an error.

super

The super keyword is used to call the constructor of its parent class to access the parent's properties and methods.

Syntax

super(arguments); // calls the parent constructor (only inside the constructor)

super.parentMethod(arguments); // calls a parent method

 

Example

Create a class named "Model" which will inherit the methods from the "Car" class, by using the extends keyword.

By calling the super() method in the constructor method, we call the parent's constructor method and gets access to the parent's properties and methods:

class Car {

constructor(brand) {

this.carname = brand;

}

present() {

return 'I have a ' + this.carname;

}

}

 

class Model extends Car {

constructor(brand, mod) {

super(brand);

this.model = mod;

}

show() {

return this.present() + ', it is a ' + this.model;

}

}

 

mycar = new Model("Ford", "Mustang");

document.getElementById("demo").innerHTML = mycar.show();

private

A private field is an identifier prefixed with # (the hash symbol). The hash is an integral part of the field's name, which means a private property can never have name clash with a public property. In order to refer to a private field anywhere in the class, you must declare it in the class body (you can't create a private property on the fly). Apart from this, a private field is pretty much equivalent to a normal property.

class Color {

// Declare: every Color instance has a private field called #values.

#values;

constructor(r, g, b) {

this.#values = [r, g, b];

}

getRed() {

return this.#values[0];

}

setRed(value) {

this.#values[0] = value;

}

}

 

const red = new Color(255, 0, 0);

console.log(red.getRed()); // 255

Error Object

The Error object provides error information when an error occurs.

Example

In this example we have written "alert" as "adddlert" to deliberately produce an error.

Return the error name and a description of the error:

try {

adddlert("Welcome");

}

catch(err) {

document.getElementById("demo").innerHTML =

err.name + "<br>" + err.message;

}

name

The name property sets or returns the name of an error.

Six different values can be returned by the error name property:

Syntax

errorObj.name

 

Example

try {

adddlert("Welcome guest!");

}

catch(err) {

document.getElementById("demo").innerHTML = err.name;

}

 

ValueDescription
EvalErrorDeprecated - use SyntaxError instead
RangeErrorA number "out of range" has occurred
ReferenceErrorAn illegal reference has occurred
SyntaxErrorA syntax error has occurred
TypeErrorA type error has occurred
URIErrorAn error in encodeURI() has occurred
message

The message property sets or returns an error message.

Syntax

errorObj.message

 

Example

try {

adddlert("Welcome guest!");

}

catch(err) {

document.getElementById("demo").innerHTML = err.message;

}

Operators

Booleans

You can use the Boolean() function to find out if an expression is true:

Boolean(10 > 9)

Or even easier:

(10 > 9) 10 > 9

Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values.

Given that y = 5, the table below explains the arithmetic operators:

OperatorDescriptionExample
 +Additionx = y + 2
 -Subtractionx = y - 2
 *Multiplicationx = y * 2
 /Divisionx = y / 2
 %Modulus (division remainder)x = y % 2
 ++Incrementx = ++y
x = y++
 --Decrementx = --y
x = y--

Assignment Operators

Assignment operators are used to assign values to JavaScript variables.

Given that x = 10 and y = 5, the table below explains the assignment operators:

OperatorExampleSame As
=x = yx = y
+=x += yx = x + y
-=x -= yx = x - y
*=x *= yx = x * y
/=x /= yx = x / y
%=x %= yx = x % y

String Operators

The + operator, and the += operator can also be used to concatenate (add) strings.

Given that text1 = "Good ", text2 = "Morning", and text3 = "", the table below explains the operators:

OperatorExampleVariables
+text3 = text1 + text2 text1 = "Good "
text2 = "Morning"
text3 = "Good Morning"
+=text1 += text2 text1 = "Good Morning"
text2 = "Morning"
text3 = ""

Comparison Operators

OperatorDescriptionExample
==equal tox == 8 is false
x == 5 is true
===equal value and equal typex === "5" is false
x === 5 is true
!=not equalx != 8 is true
!==not equal value or not equal typex !== "5" is true
x !== 5 is false
>greater thanx > 8 is false
<less thanx < 8 is true
>=greater than or equal tox >= 8 is false
<=less than or equal tox <= 8 is true

Conditional Operator

The conditional operator assigns a value to a variable based on a condition.

Syntax

variablename = (condition) ? value1:value2

 

Example

voteable = (age < 18) ? "Too young":"Old enough";

If the variable "age" is a value below 18, the value of the variable "voteable" will be "Too young", otherwise the value of voteable will be "Old enough".

Logical Operators

OperatorDescriptionExample
&&and(x < 10 && y > 1) is true
||or(x === 5 || y === 5) is false
!not!(x === y) is true

typeof Operator

The typeof operator returns the type of a variable, object, function or expression:

typeof "John" // Returns string

typeof 3.14 // Returns number

typeof NaN // Returns number

typeof false // Returns boolean

typeof [1, 2, 3, 4] // Returns object

typeof {name:'John', age:34} // Returns object

typeof new Date() // Returns object

typeof function () {} // Returns function

typeof myCar // Returns undefined (if myCar is not declared)

typeof null // Returns object

  • NaN is number

  • array is object

  • date is object

  • null is object

  • undefined variable is undefined

Note: You cannot use typeof to define if a JavaScript object is an array (or a date).

delete Operator

The delete operator deletes a property from an object:

const person = {

firstName:"John",

lastName:"Doe",

age:50,

eyeColor:"blue"

};

 

delete person.age; // or delete person["age"];

The delete operator deletes both the value of the property and the property itself.

After deletion, the property cannot be used before it is added back again.

The delete operator is designed to be used on object properties. It has no effect on variables or functions.

Note: The delete operator should not be used on predefined JavaScript object properties. It can crash your application.

in Operator

The in operator returns true if the specified property is in the specified object, otherwise false:

// Arrays

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

"Saab" in cars // Returns false (specify the index number instead of value)

0 in cars // Returns true

1 in cars // Returns true

4 in cars // Returns false (does not exist)

"length" in cars // Returns true (length is an Array property)

 

// Objects

const person = {firstName:"John", lastName:"Doe", age:50};

"firstName" in person // Returns true

"age" in person // Returns true

 

// Predefined objects

"PI" in Math // Returns true

"NaN" in Number // Returns true

"length" in String // Returns true

instanceof Operator

The instanceof operator returns true if the specified object is an instance of the specified object:

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

 

(cars instanceof Array) // Returns true

(cars instanceof Object) // Returns true

(cars instanceof String) // Returns false

(cars instanceof Number) // Returns false

void Operator

The void operator evaluates an expression and returns undefined. This operator is often used to obtain the undefined primitive value, using "void(0)" (useful when evaluating an expression without using the return value).

<a href="javascript:void(0);">

Useless link

</a>

 

<a href="javascript:void(document.body.style.backgroundColor='red');">

Click me to change the background color of body to red

</a>

Statements

In HTML, JavaScript statements are "instructions" to be "executed" by the web browser.

This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo":

document.getElementById("demo").innerHTML = "Hello Dolly.";

Statement Identifiers

JavaScript statements often start with a statement identifier to identify the JavaScript action to be performed.

Statement identifiers are reserved words and cannot be used as variable names (or any other things).

var

The var statement declares a variable.

Variables are containers for storing information.

Creating a variable in JavaScript is called "declaring" a variable:

var carName;

let

The let statement declares a variable.

Variables are containers for storing information.

Creating a variable in JavaScript is called "declaring" a variable:

let carName;

 

After the declaration, the variable is empty (it has no value).

To assign a value to the variable, use the equal sign:

carName = "Volvo";

 

You can also assign a value to the variable when you declare it:

let carName = "Volvo";

const

The const statement declares a variable.

Variables are containers for storing information.

Creating a variable in JavaScript is called "declaring" a variable:

Note: A const variable must be assigned when it is declared. As a general rule, always declare a variable with const unless you know that the value will change.

Use const when you declare:

  • A new Array

  • A new Object

  • A new Function

  • A new RegExp

const name = "Volvo";

 

// Create an object:

const car = {type:"Fiat", model:"500", color:"white"};

 

// Change a property:

car.color = "red";

 

// Add a property:

car.owner = "Johnson";

function

The function statement declares a function.

A declared function is "saved for later use", and will be executed later, when it is invoked (called).

In JavaScript, functions are objects, and they have both properties and methods.

A function can also be defined using an expression

Syntax

function functionName(parameters) {

code to be executed

}

 

Example

// Declare a function

function myFunction() {

document.getElementById("demo").innerHTML = "Hello World!";

}

 

// Call the function

myFunction();

 

// Calling a function without delaration

argument) => {Code w/argument}

(argument) => function(argument

 

functionNameRequired.
The name of the function.
Naming rules: same as JavaScript variables.
parametersOptional.
A set of arguments (parameter names), separated by commas.

The arguments are real values received by the function from the outside.

Inside the function, the arguments are used as local variables.

If a function is called with a missing argument, the value of the missing argument is set to undefined.
return

The return statement stops the execution of a function and returns a value.

Syntax

return value;

 

Example

document.getElementById("demo").innerHTML = myFunction("John");

 

function myFunction(name) {

return "Hello " + name;

}

class

A class is a type of object template.

The class statement initiates a JavaScript class.

Properties and methods are assigned in the constructor() method.

The constructor() method is called each time a class object is initialized.

Syntax

class className {

// class body

}

 

Example

// Create a Car class

class Car {

constructor(brand) {

this.carname = brand;

}

}

 

// Create a Car Object

myCar = new Car("Ford");

if ... else ... else if

The if/else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed.

The if/else statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions.

In JavaScript we have the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true

  • Use else to specify a block of code to be executed, if the same condition is false

  • Use else if to specify a new condition to test, if the first condition is false

  • Use switch to select one of many blocks of code to be executed

Syntax

The if statement specifies a block of code to be executed if a condition is true:

if (condition) {

// block of code to be executed if the condition is true

}

 

The else statement specifies a block of code to be executed if the condition is false:

if (condition) {

// block of code to be executed if the condition is true

} else {

// block of code to be executed if the condition is false

}

 

The else if statement specifies a new condition if the first condition is false:

if (condition1) {

// block of code to be executed if condition1 is true

} else if (condition2) {

// block of code to be executed if the condition1 is false and condition2 is true

} else {

// block of code to be executed if the condition1 is false and condition2 is false

}

switch

The switch statement executes a block of code depending on different cases.

The switch statement is a part of JavaScript's "Conditional" Statements, which are used to perform different actions based on different conditions. Use switch to select one of many blocks of code to be executed. This is the perfect solution for long, nested if/else statements.

The switch statement evaluates an expression. The value of the expression is then compared with the values of each case in the structure. If there is a match, the associated block of code is executed.

The switch statement is often used together with a break or a default keyword (or both). These are both optional:

  • The break keyword breaks out of the switch block. This will stop the execution of more execution of code and/or case testing inside the block. If break is omitted, the next code block in the switch statement is executed.

  • The default keyword specifies some code to run if there is no case match. There can only be one default keyword in a switch. Although this is optional, it is recommended that you use it, as it takes care of unexpected cases.

Syntax

switch(expression) {

case n:

code block

break;

case n:

code block

break;

default:

default code block

}

break

The break statement breaks out of a switch or a loop.

In a switch, it breaks out of the switch block. This stops the execution of more code inside the switch.

In in a loop, it breaks out of the loop and continues executing the code after the loop (if any).

let text = "";

for (let i = 0; i < 5; i++) {

if (i === 3) break;

text += i + "<br>";

}

 

let text = "";i = 0;

while (i < 5) {

text += i + "<br>";

i++;

if (i === 3) break;

}

for

The for statement defines a code block that is executed as long as a condition is true.

Note: If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser.

Syntax

for (statement 1; statement 2; statement 3) {

code block to be executed

}

 

Example

for (let i = 0; i < 5; i++) {

text += i + "<br>";

}

 

Loop (iterate over) an array to collect car names:

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

for (let i = 0; i < cars.length; i++) {

text += cars[i] + "<br>";

}

 

statement 1Optional.
Executed before the code block starts.
Normally used to initialize a counter variable.
To initiate multiple values, separate each value with a comma.

This parameter can be omitted, but not the semicolon ";"
statement 2Optional.
The condition for running the code block.
If it returns true the loop will start over again, otherwise the loop will end.

This parameter can be omitted, but not the semicolon ";"
statement 3Optional.
Executed after the code block.
Normally used to increment the counter variable.

This parameter can be omitted (e.g. to increase/decrease values inside the loop)
for ... in

The for...in statements combo iterates (loops) over the properties of an object.

The code block inside the loop is executed once for each property.

Note: Do not use for...in to iterate an array if the index order is important. Use a for loop instead.

Syntax

for (x in object) {

code block to be executed

}

 

Iterate (loop) over the properties of an object:

constperson = {fname:"John", lname:"Doe", age:25};

let text = "";

for (let x in person) {

text += person[x] + " ";

}

 

Iterate (loop) over the values of an array:

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

let text = "";

for (let x in cars) {

text += cars[x] + " ";

}

for ... of

The for...of statements combo iterates (loops) over the values of any iterable.

The code block inside the loop is executed once for each value.

Syntax

for (x of iterable) {

code block to be executed

}

 

Iterate (loop) over the values of an array:

let text = "";

const cars = ['BMW', 'Volvo', 'Mini'];

for (let x of cars) {

text += x + " ";

}

 

Iterate (loop) over the values of a string:

let text = "JavaScript";

for (let x of text) {

text += x + " ";

}

do ... while

The do...while statements combo defines a code block to be executed once, and repeated as long as a condition is true.

The do...while is used when you want to run a code block at least one time.

Note: If you use a variable in the condition, you must initialize it before the loop, and increment it within the loop. Otherwise the loop will never end. This will crash your browser.

Note: If the condition is always true, the loop will never end. This will also crash your browser.

Syntax

do {

code block to be executed

}

while (condition);

 

Example

let text = "";

let i = 0;

do {

text += i + "<br>";

i++;

}

while (i < 5);

while

The while statement creates a loop (araund a code block) that is executed while a condition is true.

The loop runs while the condition is true. Otherwise it stops.

Syntax

while (condition) {

code block to be executed

}

 

Loop a code block as long as a i is less than 5:

let text = "";

let i = 0;

while (i < 5) {

text += i + "<br>";

i++;

}

 

Loop (iterate over) an array to collect car names:

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

let text = "";

let i = 0;

while (i < cars.length) {

text += cars[i] + "<br>";

i++;

}

continue

The continue statement breaks one iteration (in the loop) if a specified condition occurs, and continues with the next iteration in the loop.

The difference between continue and the break statement, is instead of "jumping out" of a loop, the continue statement "jumps over" one iteration in the loop.

However, when the continue statement is executed, it behaves differently for different types of loops:

  • In a while loop, the condition is tested, and if it is true, the loop is executed again

  • In a for loop, the increment expression (e.g. i++) is first evaluated, and then the condition is tested to find out if another iteration should be done

The continue statement can also be used with an optional label reference.

Note: The continue statement (with or without a label reference) can only be used inside a loop.

Loop through a block of code, but skip the value of 3:

let text = "";

for (let i = 0; i < 5; i++) {

if (i === 3) continue;

text += i + "<br>";

}

 

let text = "";

let i = 0;

while (i < 5) {

i++;

if (i === 3) continue;

text += i + "<br>";

}

throw

The throw statement allows you to create a custom error.

The throw statement throws (generates) an error.

The throw statement throws an exception.

The exception can be a JavaScript String, a Number, a Boolean or an Object:

Note: Using throw with try and catch, lets you control program flow and generate custom error messages.

function myFunction() {

const message = document.getElementById("message");

message.innerHTML = "";

let x = document.getElementById("demo").value;

try {

if(x == "") throw "is Empty";

if(isNaN(x)) throw "not a number";

if(x > 10) throw "too high";

if(x < 5) throw "too low";

}

catch(err) {

message.innerHTML = "Input " + err;

}

}

try ... catch ... finally

The try...catch...finally statements combo handles errors without stopping JavaScript.

The try statement defines the code block to run (to try).

The catch statement defines a code block to handle any error.

The finally statement defines a code block to run regardless of the result.

The throw statement defines a custom error.

Both catch and finally are optional, but you must use one of them

Syntax

try {

tryCode - Code block to run

}

catch(err) {

catchCode - Code block to handle errors

}

finally {

finallyCode - Code block to be executed regardless of the try result

}

 

Example

function myFunction()

const message = document.getElementById("message");

message.innerHTML = "";

let x = document.getElementById("demo").value;

try {

if(x == "") throw "Empty";

if(isNaN(x)) throw "Not a number";

if(x > 10) throw "Too high";

if(x < 5) throw "Too low";

}

catch(err) {

message.innerHTML = "Error: " + err + ".";

}

finally {

document.getElementById("demo").value = "";

}

}

debugger

The debugger statement stops the execution of JavaScript, and calls the debugger.

Note: If no debugging is available, the debugger statement has no effect. Normally, you activate debugging in your browser with the F12 key, and select "Console" in the debugger menu.

let x = 15 * 5;

debugger;

document.getElementbyId("demo").innerHTML = x;

JSON

JSON is a format for storing and transporting data.

JSON is text, and text can be transported anywhere, and read by any programming language.

JavaScript Objects can be converted into JSON, and JSON can be converted back into JavaScript Objects.

This way we can work with the data as JavaScript objects, with no complicated parsing or translations.

// a JavaScript object...:

var myObj = { "name":"John", "age":31, "city":"New York" };

 

// ...converted into JSON:

var myJSON = JSON.stringify(myObj);

 

// send JSON:

window.location = "demo_json.php?x=" + myJSON;

parse()

The JSON.parse() method parses a string and returns a JavaScript object.

The string has to be written in JSON format.

The JSON.parse() method can optionally transform the result with a function.

Syntax

JSON.parse(string, function)

 

Example

var obj = JSON.parse('{"firstName":"John", "lastName":"Doe"}');

stringify()

The JSON.stringify() method converts JavaScript objects into strings.

When sending data to a web server the data has to be a string.

Syntax

JSON.stringify(obj, replacer, space)

 

Example

var obj = { "name":"John", "age":30, "city":"New York"};

var myJSON = JSON.stringify(obj);

document.getElementById("demo").innerHTML = myJSON;

Valid Data Types

In JSON, values must be one of the following data types:

  • a string

  • a number

  • an object (containing valid JSON values)

  • an array

  • a boolean

  • null

JSON values cannot be one of the following data types:

  • a function

  • a date

  • undefined