In JavaScript, the template literals are introduced in ES6 to customize the string dynamically. The template literals allow you to add variables or expressions into the string, and the string changes according to the variables and expression value changes.
There are multiple synonyms words used for the template literal words. For example, template string, string templates, back-tics syntax, etc.
Syntax
Follow the syntax below to use the template literals in JavaScript.
let str =Hi ${name};
You need to write a string between back-tics (“). For using the dynamic variable or expression with a string, you need to place it between the ${}.
Furthermore, using the template literals, you dont need escape characters to add single or double quotes in the string.
Examples
Example: Creating Strings with Template Literals
In the example below, we used the template literals to create a string with special characters.
The str1 string is the same as the regular string we create using single or double quotes. The str2 string contains the single quotes with the string. Here, you can see that we havent used the escape characters to add a single quote in the string.
<html><body><div id ="output1"></div><div id ="output2"></div><script>let str1 =Hello Users!;let str2 ='Tutorialspoint' is a good website;
The below code demonstrates to use the dynamic values in the string by passing the variables into the template literal string.
Here, we have defined the variables related to cars. After that, we create a string using the template literals and add the variables.
In the output, you can see that variables are replaced with their value in the string.
<html><body><p id ="output"></p><script>let car ="BMW";let model ="X5";const price =5000000;const carStr =The price of the ${car} ${model} is ${price}.;
You can also add the expressions to the string using the template literals.
In the str1 string, we added the expression to perform the summation of two numbers in the template literals string.
In str2, we invoke the function invocation as an expression. It replaces the expression with a returned value from the function.
<html><body><div id ="output1"></div><div id ="output2"></div><script>functionfunc(){return10;}const str1 =The sum of 2 and 3 is ${2 + 3}.;const str2 =The return value from the function is ${func()};
The sum of 2 and 3 is 5.
The return value from the function is 10
JavaScript Nested Template Literals
JavaScript allows you to use the template literals inside other template literals, and it is called the nested template literals.
Example
In the example below, we added the expression in the outer template literal. The expression contains the ternary operator. It checks whether the 2 is less than 3. Based on the returned boolean value, it executes the first or second nested expression and prints the result.
<html><head><title>Nested Template Literals</title></head><body><p id ="output"></p><script>const nested =The subtraction result is: ${2 < 3 ? ${3 - 2} : ${2 - 3}};
A JavaScript TypedArray is an array-like object used to store binary data. Unlike the array, the size of the TypedArray can’t be dynamic and can’t hold the values of the different data types, improving the performance of the TypedArray.
A TypedArray is used in audio processing, graphics rendering, networking, etc.
Why TypedArray?
In other programming languages like C++, an array can contain data of only one data type, but a JavaScript array is a bit different. It can contain elements of multiple data types. So, JavaScript arrays are less efficient in dealing with binary data and when higher performance is needed.
It is one of the reasons that TypedArray is introduced in JavaScript, and it is also called the array buffer. A TypedArray is the best way to handle binary data while maintaining the memory.
TypedArray Objects
Here are the types of TypedArray objects available to store the data of the 8, 16, 32, or 64-bit data. You can choose any object to create a TypedArray according to the data you need to store.
Sr. No.
TypedArray
Data Type
Range
Example
1
Int8Array
8-bit two’s complement Signed integer (byte)
-28 to 127
new Int8Array([92, 17, -100])
2
Uint8Array
8-bit Unsigned integer
0 to 255
new Uint8Array([132, 210, 0])
3
Uint8ClampedArray
8-bit Unsigned integer
0 to 255
new Uint8ClampedArray([90, 17, 70])
4
Int16Array
Short integer
-32768 to 32767
new Int16Array([1000, -2000, 150])
5
Uint16Array
Unsigned short int
0 to 65535
new Uint16Array([50, -6535, 12000])
6
Int32Array
Signed long integer
-2147483648 to 2147483647
new Int32Array([1000000, -2000000, 9876])
7
Uint32Array
Unsigned long integer
0 to 4294967295
new Uint32Array([100, 42967295, 0])
8
Float32Array
Float (7 significant digits)
±1.2×10^-38 to ±3.4×10^38
new Float32Array([3.134, 1.618, -0.5])
9
Float64Array
Double (16 significant digits)
±5.0×10^-324 to ±1.8×10^308
new Float64Array([2.78, -12.35, 99.9])
10
BigInt64Array
Big signed integer
-2^63 to 2^63 − 1
new BigInt64Array([-9071954740991n, 9719925474991n])
11
BigUint64Array
Big unsigned integer
0 to 2^64 – 1
new BigUint64Array([0n, 18446744709551615n])
A TypedArray doesn’t support the methods like push(), pop, etc., but supported properties and methods are listed below.
TypedArray Properties
Here is a list of the properties of the TypedArray object along with their description −
Sr.No.
Property & Description
1
ConstructorIt returns an array buffer constructor.
2
byteLengthIt returns the byte length of the TypedArray.
3
maxByteLengthIt returns the maximum byte length to expand the size of the TypedArray.
4
resizableTo check whether the TypedArray is resizable.
TypedArray Static Methods
Here is a list of the static methods of the TypedArray object along with their description −
Sr.No.
Methods
Description
1
from()
It returns a new Array instance.
2
of()
It returns a new Array instance.
TypedArray Instance Methods
Here is a list of the instance methods of the TypedArray object along with their description −
TypedArray instance methods
Sr.No.
Methods
Description
1
at()
It returns an element in the typed array that matches the given index.
2
copyWithin()
It returns a modified TypedArray without changing the length of the original TypedArray.
3
entries()
It returns a new array iterable object.
4
every()
It returns true if all elements in the typed array pass the test implemented by the callback function, and false otherwise.
5
fill()
It returns the modified typed array, that is filled with the specified value.
6
filter()
It returns a new copy of a typed array that includes only the elements that pass the test.
7
find()
It returns the first element is TypedArray that satisfied the provided test function, ‘undefined’ otherwise.
8
findIndex()
It returns an index of the first element is TypedArray that satisfied the provided test function, ‘-1’ otherwise.
9
findLast()
It returns the last element in the typed array that satisfies the provided testing function, ‘undefined’ if not found.
10
findLastIndex()
It returns the last element in the typed array that passes the test, -1 if not found.
11
forEach()
It returns none(undefined).
12
includes()
It returns ‘true’ if searchElement is found in the typed array; ‘false’ otherwise.
13
indexof()
It returns the first index of the searchElement.
14
join()
It returns a string by joining all the elements of a typed array.
15
Keys()
It returns a new iterable iterator object.
16
lastIndexof()
It returns the last index of the searchElement in a typed array. If the search element is not present, it returns -1.
17
map()
It returns a new typed array by executing the callback function on each element.
18
reduce()
It returns a value that outputs from running the “reducer” callback function to completion over the entire typed array.
19
reduceRight()
It returns a value that results from the reduction.
20
reverse()
It returns the reference of the original typed array in reversed order.
21
set()
It returns none(undefined).
22
slice()
It returns a new typed array containing the extracted elements of the original typed array.
23
some()
It returns true, if atlesat one element in typed array pass the test implemented by provided function; false otherwise.
24
sort()
It returns the reference of the same typed array in sorted order.
25
subarray()
It returns a new TypedArray object.
26
toLocaleString()
It returns a string that represents the elements of the typed array.
27
toReversed()
It returns a new typed array containing the elements in reversed order.
28
toSorted()
It returns a new typed array with the elements sorted in ascending order.
29
toString()
It returns a string that represents the elements of the typed array.
30
values()
It returns a new array iterable object.
31
with()
It returns a new typed array with the element at the index replaced with the specified value.
Examples
Example 1
We used the Int8Array to create a TypedArray in the example below. We passed the array containing the multiple elements as an object constructor.
In the output, you can see that if any input element is greater than the 8-bit number, the constructor function automatically enforces it to the 8-bit number.
<html><body><p id ="output"></p><script>const array =newInt8Array([1000,200,30,40]);
document.getElementById("output").innerHTML ="The array is: "+ array;</script></body></html></pre>
Output
The array is: -24,-56,30,40
Example 2
In the example below, we used the Float32Array() constructor function to create a TypedArray. It is used to store the 32-bit floating point numbers.
Also, you can access or update TypedArray elements as the normal array.
<html><body><p id ="output"></p><script>const array =newFloat32Array([100.212,907.54,90,14562547356342.3454]);
array[2]=23.65;// Updating the 3rd element of the array
document.getElementById("output").innerHTML ="The array is: "+ array;</script></body></html></pre>
Output
The array is:
100.21199798583984,907.5399780273438,23.649999618530273,14562546941952
In JavaScript, Reflect is a global object and was introduced in ECMAScript 6 (ES6). It contains static methods, providing a better way to interact with the object at runtime.
Unlike most global objects, Reflect is not a constructor. You cannot use it with the new operator or invoke the Reflect object as a function. All methods of Reflect are static just like the Math object.
It contains various methods to access, update, delete, etc. properties from the object at run time.
Key Features of the Reflect Object
Object construction − The Reflect API allows to create objects at run time using the Reflect.construct() method.
Function invocation − The apply() method of the Reflect API is used to invoke a function or object method by passing the context and argument.
Object property manipulation − A Reflect API has different methods to set, update, or delete the object properties. Also, it can handle the extension of the object by preventing it.
Syntax
Following is the syntax to use the method of the Reflect API −
Reflect.method();
In the above syntax, the ‘method’ is the generalization. It can be any method of the Reflect API, such as get, set, apply, construct, has, etc.
Reflect Methods
In the following table, we have listed all the methods of Reflect −
Sr.No.
Name & Description
1
apply()To invoke a function.
2
construct()Allows to specify the different prototypes.
3
defineProperty()Allows to insert or edit object property.
4
deleteProperty()Allows to delete the object property.
5
get()To get a value of the property.
6
getOwnPropertyDescriptor()Allows to get the descriptor of the object.
7
getPrototypeOf()To get the prototype of the object.
8
has()To check whether the property exists in the object.
9
isExtensible()Allows to check whether the object is extensible.
10
ownKeys()Returns the own keys of the targeted object and ignores the inherited keys.
11
preventExtensions()To prevent the extension of the object.
12
set()To set the value to the object property.
13
setPrototypeOf()Allows to set the prototype of the object as null or another object.
Examples
Example 1
In the example below, we have defined a car object. The ‘prop’ variable contains the property name in the string format.
We use the get() method of the Reflect object to access the ‘model’ property from the car object. We passed the object name as a first parameter of the get() method and the property name as a second parameter.
In the output, you can see the value of the ‘model’ property.
<html><body><div id="output">The model of the car is:</div><script>const car ={
In the example below, we used the set() method to set the property into the object. The set() method takes an object, property name, and value as a parameter.
The output shows the 'doors' property value. In this way, you can set the property into the object at run time using the set() method of the Reflect API.
<html><body><div id="output">The total doors in the Audi Q6 is:</div><script>const car ={
name:"Audi",
model:"Q6",
price:7000000,}const model = Reflect.set(car,"doors",4);
document.getElementById("output").innerHTML += car.doors;</script></body></html></pre>
Output
The total doors in the Audi Q6 is: 4
On executing the above script, the output window will pop up, displaying the text on the webpage.
Example 3
In the example below, we used the has() method to check whether the particular property exists in the object dynamically.
Both symbols look similar but are different, which you can see in the output.
<html><body><p id="output"></p><script>const car ={
name:"Audi",
model:"Q6",
price:7000000,}const isName = Reflect.has(car,"name");if(isName){
document.getElementById("output").innerHTML ="The Car object contains the name.";}</script></body></html></pre>
In JavaScript, iterables are objects that can be iterated through using the for…of loop. They can also be iterated over using other methods like forEach(), map(), etc.
Basically, you can traverse through each element of the iterable in JavaScript.
Here are some examples of the common iterables.
Array
String
Map
Set
Arguments
NodeList
TypedArrays
Generators
Iterate using the for…of loop
In this section, we will iterate through the array elements, string characters, set elements, and key-value pairs of the map using the for…of loop.
Example: Iterate over an array
In the below code, we have defined an array and used the for…of loop to iterate through the array.
The code prints each element of the array in the output.
<html><body><div>Iterating the array:</div><div id ="demo"></div><script>const output = document.getElementById("demo");const array =["Hello","Hi",10,20,30];// Iterating arrayfor(let ele of array){
output.innerHTML += ele +", ";}</script></body></html></pre>
Output
Iterating the array:
Hello, Hi, 10, 20, 30,
Example: Iterate over a string
In the below code, we used the for...of loop to iterate through each string character.
The code prints the comma seprated string characters in the output.
<html><body><div id ="demo">Iterating a string:</div><script>const output = document.getElementById("demo");let str ="Hello";// Iterating a stringfor(let char of str){
In this example, we have created a set containing multiple elements. After that, we traverse through each element of the set and print in the output.
<html><body><p id ="demo">Iterating the Set:</p><script>const output = document.getElementById("demo");const set =newSet([10,20,30,40,40,50,50]);// Iterating a Setfor(let ele of set){
output.innerHTML += ele +", ";}</script></body></html></pre>
Output
Iterating the Set: 10, 20, 30, 40, 50,
Example: Iterate over a map
In the example below, we have defined the map containing 3 key-value pairs. In each iteration of the for...of loop, we get a single key-value pair from the map.
<html><body><div id ="demo">Iterating the Map:<br></div><script>const output = document.getElementById("demo");const map =newMap([["1","one"],["2","two"],["3","three"],]);// Iterating arrayfor(let ele of map){
output.innerHTML += ele +"<br>";}</script></body></html></pre>
Output
Iterating the Map:
1,one
2,two
3,three
Iterate using the forEach() method
In this section, we have used the forEach() method to iterate through the iterable.
Example
In the example below, we used the forEach() method with an array to iterate the array and print each element of the array in the output.
<html><body><div> Using the forEach() method:</div><div id="demo"></div><script>const output = document.getElementById("demo");const array =[true,false,50,40,"Hi"];// Iterating array
array.forEach((ele)=>{
output.innerHTML += ele +", ";})</script></body></html></pre>
Output
Using the forEach() method:
true, false, 50, 40, Hi,
Iterate using the map() method
In this section, we have used the map() method to iterate through the iterable.
Example
In the example below, the map() method is used with the array. In the callback function of the map() method, we print the array elements.
<html><body><p id ="demo">Using the map() method:</p><script>const output = document.getElementById("demo");const array =[true,false,50,40,"Hi"];// Iterating array
array.map((ele)=>{
output.innerHTML += ele +", ";})</script></body></html></pre>
Output
Using the map() method: true, false, 50, 40, Hi,
However, you can traverse the array, string, etc., using the loops like a for loop, while loop, etc. JavaScript also allows us to define custom iterators to traverse the iterable.
A WeakMap object in JavaScript is a collection of key-value pairs where the keys are weakly referenced. The WeakMap keys must be objects or non-registered symbols, and values are of any arbitrary JavaScript type.
The WeakMap is similar to the JavaScript Map. The main difference between the WeakMap and Map data structure is that the WeakMap data structure uses the objects as a key only, but Map can use other data types also as a key.
If you use the value of another data type as a key of a WeakMap except the object, it gives the Types error.
Syntax
You can follow the syntax below to use the WeakMap in JavaScript −
const weak_map =newWeakMap();
In the above syntax, we used the ‘new’ keyword with a WeakMap() function to create a new instance of the WeakMap.
The WeakMap provides methods to set, get, and delete the key-value pairs from the WeakMap. Here, we have listed the properties and methods of the WeakMap.
WeakMap Properties
Here is a list of the properties of WeakMap and their description −
Sr.No.
Name & Description
1
constructorTo get a constructor function of a WeakMap.
WeakMap Methods
Here is a list of the methods associated with WeakMap object and their description −
Sr.No.
Name & Description
1
delete()To delete a single key-value pair from the WeakMap.
2
get()To get values related to the specific object.
3
has()Check whether a particular object exists as a key exists in the WeakMap.
4
set()To insert the key-value pair in the WeakMap.
WeakMap Constructor()
Following is the WeakMap constructor in JavaScript −
In the example below, we have defined the WeakMap using the constructor function. After that, we used the set() method to set the laptop object as a key and its price as a value.
At last, we used the get() method to get the value related to the ‘laptop’ key.
<html><body><p id ="output">The laptop price is:</p><script>const wm =newWeakMap();const laptop ={
If we execute the program, it returns the value related to the "laptop" key, i.e. "10000".
Example: Deleting key-value pair from the WeakMap
In the example below, we have inserted the key-value pair in the WeakMap using the set() method.
After that, we used the delete() method to delete the key-value pair from the WeakMap. After deleting the key-value pair when you access it, the WeakMap returns undefined, as you can see in the output.
Note − WeakMaps are not iterable in JavaScript.
<html><body><div id ="output1">The laptop price is:</div><div id ="output2">The laptop price after deletion is:</div><script>const wm =newWeakMap();const laptop ={
A Map object in JavaScript is a collection of key-value pairs where the keys can be of any type, including objects or functions. The order of the map elements is the same as the insertion order of the key-value pairs.
To create a new Map object, you can use the new Map() constructor. You can then add key-value pairs to the map using the set() method. To get the value for a particular key, you can use the get() method. To remove a key-value pair from the map, you can use the delete() method.
Syntax
Following is the syntax to use the Map data structure in JavaScript −
const map =newMap([iterable]);
In the above syntax, we used the ‘new’ keyword with a Map() constructor to define an instance of the Map.
Parameters
iterable − It is an iterable containing the key-value pairs to initialize the map with elements of the iterable. Also, it is an optional parameter.
The Map class in JavaScript contains a set of built-in methods that allow us to work with Map objects. Here, we have listed the properties and methods of the Map.
Map Properties
Following are the properties of Map object −
Sr.No.
Name & Description
1
sizeThis property returns the number of elements in this map.
Map Methods
In the following table, we have listed all the methods of Map object and their description −
Sr.No.
Name & Description
1
clear()This method removes all elements from a Map object.
2
delete()This method removes a specified element from a Map object by key.
3
entries()This method returns a new map iterator object that contains the [key, value] pairs.
4
forEach()This method executes a callback function once per each key/value pair in a Map object.
5
get()This method is used to return a specified element from a Map object.
6
has()This method indicates whether an element with the specified key exists or not.
7
keys()This method returns a new Iterator object that contains the keys for each element in the Map object.
8
set()This method insert the key-value pair to a Map object.
9
values()This method returns a new Iterator object that containing values of the Map object.
JavaScript Map Constructor()
Following is the constructor of Map in JavaScript −
In the example below, we have passed the 2D array containing the key-value pairs as an argument of the Map() constructor.
After that, we traverse the map to get each value of the map and show in the output.
<html><body><div> Map elements are:</div><div id ="output"></div><script>const map =newMap([["Apple",100],["Banana",20],["Orange",50]]);for(let[key, value]of map){
After executing the above program, it returns each value of the map.
Map elements are:
Apple : 100
Banana : 20
Orange : 50
Example: Inserting key-value pair in the Map
In the example below, we use the set() method to insert the key-value pair in the map. The set() method takes the key as the first argument and the value as the second argument.
<html><body><div>After inserting 2 key-value pairs in the map:</div><div id ="output"></div><script>const map =newMap();
After executing, it returns all the elements present in the Map object.
Name: John
Roll Id: 123
Example: Removing a Map Element
In the example below, we use the delete() method to delete the key-value pair having a key 20.
However, you can also use the clear() method to remove all elements from the map.
<html><body><div>Map after deleting the [20,30] key-value pair:</div><div id ="demo"></div><script>const output = document.getElementById("demo");const map =newMap([[10,20],[20,30],[30,40]]);
map.delete(20);// Deleting a [20,30] key-value pair from the mapfor(let[key, value]of map)
output.innerHTML +="Key: "+ key +" Value: "+ value +"<br/>";</script></body></html></pre>
Output
Map after deleting the [20,30] key-value pair:
Key: 10 Value: 20
Key: 30 Value: 40
Example: Size of the Map
In the below code, we used the 'size' property of the Map class to get the total number of key-value pairs in the map.
<html><body><p id ="output">Size of the map object is:</p><script>const map =newMap();
The JavaScript WeakSet object is a collection of objects. The WeakSet is very similar to the Set. The main difference between the WeakSet and Set is that the WeakSet contains only objects, and the Set can also contain the values like numbers, Boolean, string, etc.
WeakSet objects are weak, meaning that references to objects in a WeakSet are held weakly. If no other references to a value stored in the WeakSet exist, those values can be garbage collected.
WeakSet objects are useful for keeping track of objects without preventing them from being garbage collected. An example of this would be keeping track of DOM nodes without having to remove them from the DOM manually.
Syntax
Follow the syntax below to define a new instance of the WeakSet class in JavaScript.
const weakest =newWeakSet([iterable]);
We used the WeakSet() constructor function with a ‘new’ keyword in the above syntax.
Parameters
iterable − It is an iterable containing multiple objects to initialize the WeakSet.
In JavaScript, if two objects contain the same properties and value, they are still different as their references are different.
Here, we have listed the methods and properties of the WeakSet.
WeakSet Properties
Here is a list of all the properties of WeakSet and their description.
Sr.No.
Property & Description
1
constructorIt returns the WeakSet constructor function.
WeakSet Methods
Here is a list of the methods associated with WeakSet object and their description.
Sr.No.
Methods & Description
1
add()To insert the object into the WeakSet.
2
delete()To delete a single object from the WeakSet.
3
has()Check whether a particular object exists in the WeakSet.
Examples
Example: Similar Objects with WeakSet
In the example below, we have defined the obj1 and obj2 empty objects and added them to the WeakSet.
Also, we used the has() method to check whether the set contains the obj1 and obj2 objects. Both objects look similar but have different references in the memory. So, the WeakSet contains both objects.
output.innerHTML +="The weak_set contains the obj1 object! <br>";}if(weak_set.has(obj2)){
output.innerHTML +="The weak_set contains the obj2 object! <br>";}</script></body></html></pre>
Output
The weak_set contains the obj1 object!
The weak_set contains the obj2 object!
Example: Add Object in WeakSet
In the example below, we have defined the WeakSet containing 0 elements. Also, we have defined the car object and used the add() method to add the object in the set.
After that, we use the has() method to check whether the object has been added into the WeakSet.
<html><body><p id ="output"></p><script>const output = document.getElementById("output");const weak_set =newWeakSet();const car ={
brand:"Audi",
model:"Q5",}
weak_set.add(car);if(weak_set.has(car)){
output.innerHTML ="The car object is added successfully to the weak_set.";}</script></body></html></pre>
Output
The car object is added successfully to the weak_set.
Example: Delete Object from the WeakSet
In the example below, we have initialized the WeakSet with the car object. After that, we use the delete() method to delete the object from the WeakSet.
<html><body><p id ="output"></p><script>const output = document.getElementById("output");const car ={
brand:"Audi",
model:"Q5",}const carWeakSet =newWeakSet([car]);const flag = carWeakSet.delete(car);// returns true if deleted successfully
output.innerHTML ="The car object is deleted successfully from the carWeakSet? "+ flag;</script></body></html></pre>
Output
The car object is deleted successfully from the carWeakSet? true
WeakSet is not iterable. So, you can't traverse through its elements.
A JavaScript Set object is a collection of unique values. Each value can only occur once in a Set. A Set can hold any value of any data type. The sets are introduced to JavaScript in ECMAScript 6 (ES6).
JavaScript Sets are similar to Arrays, but there are some key differences:
Sets can only hold unique values, while Arrays can hold duplicate values.
Sets are not ordered, while Arrays are ordered.
Sets are faster to add and remove items from than Arrays.
JavaScript Sets are often used to store unique values, such as the unique users who have visited a website. They can also be used to remove duplicate values from an Array.
Syntax
Users can follow the syntax below to define a set in JavaScript −
let set1 =newSet([iterable]);
In the above syntax, we used the Set() constructor function with a new keyword to define a set.
Parameters
Iterable− It is an optional parameter. The Set() constructor function traverses through the elements of the iterable and creates a new set using those elements.
Examples
Example (Access set elements)
In the example below, we have passed the array containing the duplicate elements as an argument of the Set() constructor function. The num_set contains only unique values.
We used the values() method to get the iterator of the set values. To traverse the iterator, we use the for…of loop. In the loop, we access the element and print it. You can observe that set contains unique values even if the input array contains duplicate elements.
<html><body><p>The set elements are:</p><p id ="output"></p><script>const num_set =newSet([10,20,20,20]);for(let value of num_set.values()){
document.getElementById("output").innerHTML += value +"<br> ";}</script></body></html></pre>
Output
The set elements are:
10
20
Example (Insert elements into the sets)
Users can use the add() method to insert the element into the set. Here, we have created the empty set. After that, we used the add() method 3 times to add the 60, 50, 50 elements into the set.
We inserted the 50 for 2 times, but the set contains only once as it contains unique values.
<html><body><p>Set elements after adding element/s to it:</p><div id ="output"></div><script>const num_set =newSet();
num_set.add(60);
num_set.add(50);
num_set.add(50);for(let value of num_set.values()){
document.getElementById("output").innerHTML += value +"<br> ";}</script></body></html></pre>
Output
Set elements after adding element/s to it:
60
50
Example (Remove set elements)
The delete() method of the set allows you to delete the element from the set. Here, we created the set containing the various numbers and used the delete() method to delete the 200 and 400 from the set.
<html><body><p> After deleting elements from the set:</p><div id ="output"></div><script>let num_set =newSet([100,200,300,400,500]);
num_set.delete(200);
num_set.delete(400);for(let value of num_set.values()){
document.getElementById("output").innerHTML += value +"<br> ";}</script></body></html></pre>
Output
The set contains 100?: true
Example (Check if the set contains a specific value)
The example below demonstrates of using the has() method to check whether the set contains the specific value.
Here, we check whether the set contains 100 and print the message in the output accordingly.
<html><body><p id ="output">The set contains 100?:</p><script>const num_set =newSet([100,200,300,400,500]);
It returns "true" because the element 100 is present in the set.
The set contains 100?: true
Mathematical set operations
The Set class doesnt contain the built-in methods to perform the mathematical set operations like union, intersection, or set difference. So, you need to write the custom JavaScript code to perform the mathematical operations as shown below.
Example (Union of two sets)
The union of two sets contains all unique elements of set1 and set2.
In the example below, set1 and set2 contain the car names. We have defined the union set and passed the array as an argument. We used the spread operator to create an array containing the elements of set1 and set2.
<html><body><p>The Union of set1 and set2 is:</p><div id ="output"></div><script>const set1 =newSet(["BMW","Audi","TATA"]);const set2 =newSet(["BMW","TaTa","Honda","Suzuki"]);const union =newSet([...set1,...set2]);// Taking unionfor(let value of union.values()){
document.getElementById("output").innerHTML += value +"<br> ";}</script></body></html></pre>
Output
If we execute the program, it returns all unique elements of set1 and set2.
The Union of set1 and set2 is:
BMW
Audi
TATA
TaTa
Honda
Suzuki
Example (Intersection of two sets)
The intersection of two sets contains the unique elements which exist in set1 and set2 both.
Here, we have two sets containing the car names and defined the inter set to store the set elements which exist in both sets.
We traverse through the elements of set1, and inside the loop we use the has() method to check whether the element of the set1 exists in the set2. If yes, we add an element into the inter set.
<html><body><p> The intersection of set1 and set2 is:</p><p id ="output"></p><script>const set1 =newSet(["BMW","Audi","TATA"]);const set2 =newSet(["BMW","TATA","Honda","Suzuki"]);const inter =newSet();for(let car of set1){if(set2.has(car)){
inter.add(car);}}for(let value of inter.values()){
document.getElementById("output").innerHTML += value +"<br> ";}</script></body></html></pre>
Output
The intersection of set1 and set2 is:
BMW
TATA
Example (Difference of two sets)
The difference between set1 and set2 contains all elements in the set1 but not in the set2.
We have created the new set named diff and initialized it with the set1 elements. After that, we traverse the set2 elements. If any element of the set2 exists in the diff set, we delete it.
<html><body><p>The difference of set1 and set2 is:</p><div id ="output"></div><script>const set1 =newSet(["BMW","Audi","TATA"]);const set2 =newSet(["BMW","TATA","Honda","Suzuki"]);const diff =newSet(set1);for(let car of set2){
diff.delete(car);}for(let value of diff.values()){
document.getElementById("output").innerHTML += value +"<br> ";}</script></body></html></pre>
Output
The difference of set1 and set2 is:
Audi
JavaScript Set Reference
In JavaScript, a Set is a collection of unique values. In other words, each value can occur only once within a set. It provides methods to add, remove, and check for the presence of elements in the set. Here, we have listed the properties and methods of the Set class.
JavaScript Set Constructor()
Following is the constructor of Set in JavaScript −
Sr.No.
Name & Description
1
Set()Creates and returns the set of unique values from values passed as an argument.
In JavaScript, Symbol is a primitive data type and it was introduced in ECMAScript 6 (ES6). It can be created using the ‘Symbol’ constructor.
Symbols are immutable and unique, unlike to other primitive data types like strings or numbers. They are especially helpful in situations where a unique identifier is required since they offer a way to create private object properties and avoid naming conflicts. Here, we have listed the properties and methods related to the symbol.
The points given below you should keep in mind while using the symbol.
Each symbol contains unique values.
The symbol is immutable. It means you can’t update the value of the symbol.
Symbols are used to define unique object properties.
The type of the symbol can’t be changed.
Syntax
You can follow the syntax below to create a new symbol using the Symbol() function. −
const sym =Symbol([description]);
Here description is an optional parameter. It specifies the symbol description, which you can access using the ‘description’ property.
Symbol Properties
In the following table, we have listed all the properties of Symbol −
Sr.No.
Name & Description
1
descriptionTo get an optional description of the symbol object.
2
asyncIteratorIt changes the object to async iterable.
3
hasInstanceTo check whether the constructor object counts the object as its instance.
4
isConcatSpreadableIt determines that while using the array.concat() method array should be concatenated as an object or flattened array.
5
iteratorReturns an iterator of the symbol.
6
matchMatches the regular expression with the string.
7
matchAllReturns all matches of the regular expression with the string.
8
replaceTo replace a substring.
9
searchTo get an index of the matches value.
10
speciesTo create a derived object.
11
splitIt specifies the method that splits string from the indices where regular expression matches.
12
toStringTagTo create a default string description for the object.
Symbol Methods
In the following table, we have listed all the methods of Symbol −
document.getElementById("output").innerHTML ="The sym1 is: "+ sym1.toString()+"<br>"+"The type of sym1 is: "+typeof sym1 +"<br>";const sym2 =Symbol("description");
document.getElementById("output").innerHTML +="The sym2 is: "+ sym2.toString();</script></body></html></pre>
Output
When we execute the above script, it will generate an output consisting of the text displayed on the webpage.
The sym1 is: Symbol()
The type of sym1 is: symbol
The sym2 is: Symbol(description)
Example: Accessing Symbol Description
Let's look at the following example, where we are going to use the .description to get the description of the symbol.
<html><body><p id="output"></p><script>const sym =Symbol("Welcome to Tutorials Point...");
document.getElementById("output").innerHTML ="The sym description of the symbol is : "+ sym.description;</script></body></html></pre>
Output
On executing the above script, the output window will pop up, displaying the text on the webpage.
The sym description of the symbol is : Welcome to Tutorials Point...
Example: Each Symbol is Unique
In the example below, we have defined the sym1 and sym2 symbols. After that, we compare both variables and print the message accordingly.
Both symbols look similar but are different, which you can see in the output.
document.getElementById("output").innerHTML +="Sym1 and Sym2 are equal.";}else{
document.getElementById("output").innerHTML +="Sym1 and Sym2 are not equal.";}</script></body></html></pre>
Output
After executing, it returns a text indicating that the both the symbols are not equal.
Sym1 and Sym2 are not equal.
Example: Using Symbol as an Object Key
The main purpose of the symbol is to use it as an object key. Here, we have used the 'objId' symbol as a key.
When we print the object by converting it to string or traversing the object properties, it won't print the symbol. So, the symbol can help developers to make object properties private.
<html><body><p id="output">The object is:</p><script>const objId =Symbol();const person ={
If we execute the above program, it will generate an output consisting of the text displayed on the webpage.
The object is: {"name":"John Doe","age":30}
Benefits of using Symbols
Here, we have explained the benefits of using symbols in real-time development.
Unique property keys − Each symbol is unique, even if its description is different. So, you can use the symbol as a key to avoid accidental collision between the keys with the same name. Mainly, it is useful when you need to use the same instance of the object in two different code snippets and need to insert the same properties.
Non-iterable properties − When you add the symbol as a key in JavaScript and traverse the object properties using the for...in loop, the loop doesn't traverse through the symbol keys.
Private Members − You can use the symbol to define the private properties in JavaScript classes.
Avoid overWriting − The symbol is unique, so it avoids overwriting similar properties.
A regular expression (RegExp) in JavaScript is an object that describes a pattern of characters. It can contain the alphabetical, numeric, and special characters. Also, the regular expression pattern can have single or multiple characters.
The JavaScript RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on text.
The regular expression is used to search for the particular pattern in the string or replace the pattern with a new string.
There are two ways to construct the regular expression in JavaScript.
Using the RegExp() constructor.
Using the regular expression literal.
Syntax
A regular expression could be defined with the RegExp () constructor, as follows −
var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /pattern/attributes;
Parameters
Here is the description of the parameters −
pattern − A string that specifies the pattern of the regular expression or another regular expression.
attributes − An optional string containing any of the “g”, “i”, and “m” attributes that specify global, case-insensitive, and multi-line matches, respectively.
Before we learn examples of regular expression, let’s learn about regular expression modifiers, Quantifiers, literal characters, etc.
Modifiers
Several modifiers are available that can simplify the way you work with regexps, like case sensitivity, searching in multiple lines, etc.
Sr.No.
Modifier & Description
1
iPerform case-insensitive matching.
2
mSpecifies that if the string has newline or carriage return characters, the ^ and $ operators will now match against a newline boundary, instead of a string boundary
3
gPerforms a global matchthat is, find all matches rather than stopping after the first match.
Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range of characters.
Sr.No.
Expression & Description
1
[…]Any one character between the brackets.
2
[^…]Any one character not between the brackets.
3
[0-9]It matches any decimal digit from 0 through 9.
4
[a-z]It matches any character from lowercase a through lowercase z.
5
[A-Z]It matches any character from uppercase A through uppercase Z.
6
[a-Z]It matches any character from lowercase a through uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.
Quantifiers
The frequency or position of bracketed character sequences and single characters can be denoted by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags all follow a character sequence.
Sr.No.
Expression & Description
1
p+It matches any string containing one or more p’s.
2
p*It matches any string containing zero or more p’s.
3
p?It matches any string containing at most one p.
4
p{N}It matches any string containing a sequence of N p’s
5
p{2,3}It matches any string containing a sequence of two or three p’s.
6
p{2, }It matches any string containing a sequence of at least two p’s.
7
p$It matches any string with p at the end of it.
8
^pIt matches any string with p at the beginning of it.
9
?!pIt matches any string which is not followed by a string p.
Examples
Following examples explain more about matching characters.
Sr.No.
Expression & Description
1
[^a-zA-Z]It matches any string not containing any of the characters ranging from a through z and A through Z.
2
p.pIt matches any string containing p, followed by any character, in turn followed by another p.
3
^.{2}$It matches any string containing exactly two characters.
4
<b>(.*)</b>It matches any string enclosed within <b> and </b>.
5
p(hp)*It matches any string containing a p followed by zero or more instances of the sequence hp.
Literal characters
The literal characters can be used with a backslash (\) in the regular expression. They are used to insert special characters, such as tab, null, Unicode, etc., in the regular expression.
Sr.No.
Character & Description
1
AlphanumericItself
2
\0The NUL character (\u0000)
3
\tTab (\u0009
4
\nNewline (\u000A)
5
\vVertical tab (\u000B)
6
\fForm feed (\u000C)
7
\rCarriage return (\u000D)
8
\xnnThe Latin character specified by the hexadecimal number nn; for example, \x0A is the same as \n
9
\uxxxxThe Unicode character specified by the hexadecimal number xxxx; for example, \u0009 is the same as \t
10
\cXThe control character ^X; for example, \cJ is equivalent to the newline character \n
Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the combination a special meaning.
For instance, you can search for a large sum of money using the ‘\d’ metacharacter: /([\d]+)000/, Here \d will search for any string of numerical character.
The following table lists a set of metacharacters which can be used in PERL Style Regular Expressions.
Sr.No.
Character & Description
1
.a single character
2
\sa whitespace character (space, tab, newline)
3
\Snon-whitespace character
4
\da digit (0-9)
5
\Da non-digit
6
\wa word character (a-z, A-Z, 0-9, _)
7
\Wa non-word character
8
[\b]a literal backspace (special case).
9
[aeiou]matches a single character in the given set
10
[^aeiou]matches a single character outside the given set
11
(foo|bar|baz)matches any of the alternatives specified
Let’s learn to create regular expressions below.
let exp =/tutorialspoint/i
/tutorialspoint/ It finds a match for the ‘tutorialspoint’ string.
i It ignores the case of the characters while matching the pattern with the string. So, it matches with ‘TutoiralsPoint’, or ‘TUTORIALSpoint’, etc.
let exp =/\d+/
\d It matches 0 to 9 digits.
+ It matches one or more numeric digits.
let exp =/^Hi/
^ – It matches the start of the text.
Hi It checks whether the text contains ‘Hi’ at the start.
Let exp =/^[a-zA-Z0-9]+@[a-zA-Z]+\.[a-zA-Z]{2,3}$/
The above regular expression validates the email. It looks complex, but it is very easy to understand.
^ – Start of the email address.
[a-zA-Z0-9] It should contain the alphanumeric characters in the start.
+ – It should contain at least one alphanumeric character.
@ – It must have the ‘@’ character after the alphanumeric characters.
[a-zA-Z]+ – After the ‘@’ character, it must contain at least 1 alphanumeric character.
\. It must contain a dot after that.
[a-zA-Z] After the dot, the email should contain alphabetical characters.
{2, 3} After the dot, it should contain only 2 or 3 alphabetical characters. It specifies the length.
$ – It represents the end of the pattern.
Now, the question is whether we can use the search() or replace() method to search or replace text in the string by passing the string as an argument; then what is the need for the regular expression?
The question is obvious. Let’s understand it via the example below.
Example
In the below example, we used the regular expression literal to define the regular expression. The pattern matches the ‘tutorialspoint’ string without comparing the case of characters.
In the first case, the string search() method searches for the ‘tutorialspoint’ string, which performs the case-sensitive match. So, it returns -1.
In the second case, we passed the regular expression as an argument of the search() method. It performs the case-insensitive match. So, it returns 11, the index of the required pattern.
<html><head><title> JavaScript - Regular Expression </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");let pattern =/tutorialspoint/i;let str ="Welcome to TuTorialsPoint! It is a good website!";let res = str.search('tutorialspoint');
output.innerHTML +="Searching using the string : "+ res +"<br>";
res = str.search(pattern);
output.innerHTML +="Searching using the regular expression : "+ res;</script></body></html></pre>
Execute the program to see the desired results.
Example
In the example below, we used the replace() method to match the pattern and replace it with the '100' string.
Here, the pattern matches the pair of digits. The output shows that each number is replaced with '100' in the string. You may also add alphabetical characters in the string.
<html><head><title> JavaScript - Regular expression </title></head><body><p id ="output"></p><script>let pattern =/\d+/g;// Matches pair of digitslet str ="10, 20, 30, 40, 50";let res = str.replace(pattern,"100");
document.getElementById("output").innerHTML ="String after replacement : "+ res;</script></body></html></pre>
Execute the program to see the desired results.
Example (Email validation)
In the example below, we used the RegExp() constructor function with a 'new' keyword to create a regular expression. Also, we have passed the pattern in the string format as an argument of the constructor.
Here, we validate the email using the regular expression. In the first case, email is valid. In the second case, the email doesn't contain the @ character, so the test() method returns false.
<html><body><p id ="output"></p><script>const pattern =newRegExp('^[a-zA-Z0-9]+@[a-zA-Z]+\.[a-zA-Z]{2,3}$');
document.getElementById("output").innerHTML ="[email protected] is valid? : "+ pattern.test('[email protected]')+"<br>"+"abcdgmail.com is valid? : "+ pattern.test('abcdgmail.com');</script></body></html></pre>
So, the regular expression can be used to find a particular pattern in the text and perform operations like replace.
RegExp Properties
Here is a list of the properties associated with RegExp and their description.
Sr.No.
Property & Description
1
constructorSpecifies the function that creates an object's prototype.
2
globalSpecifies if the "g" modifier is set.
3
ignoreCaseSpecifies if the "i" modifier is set.
4
lastIndexThe index at which to start the next match.
5
multilineSpecifies if the "m" modifier is set.
6
sourceThe text of the pattern.
In the following sections, we will have a few examples to demonstrate the usage of RegExp properties.
RegExp Methods
Here is a list of the methods associated with RegExp along with their description.
Sr.No.
Method & Description
1
exec()Executes a search for a match in its string parameter.
2
test()Tests for a match in its string parameter.
3
toSource()Returns an object literal representing the specified object; you can use this value to create a new object.
4
toString()Returns a string representing the specified object.
In the following sections, we will have a few examples to demonstrate the usage of RegExp methods.