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.
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.
<html><body><p id ="output"></p><script>const output = document.getElementById("output");const obj1 ={};const obj2 ={};const weak_set =newWeakSet([obj1, obj2]);if(weak_set.has(obj1)){
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>
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>
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>
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>
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>
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>
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]);
document.getElementById("output").innerHTML += num_set.has(100);</script></body></html>
Output
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>
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>
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>
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.
valueOf()To get the primitive value of the symbol object.
Examples
Example: Creating a Symbol
In the example below, We used the Symbol() function to create a new symbol. Also, we have passed the string argument while defining the sym2 symbol.
You can observe the type of the ‘sym1’, which is ‘symbol’, a primitive value.
<html><body><p id="output"></p><script>const sym1 =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>
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>
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.
<html><body><p id="output"></p><script>const sym1 =Symbol();const sym2 =Symbol();if(sym1 == sym2){
document.getElementById("output").innerHTML +="Sym1 and Sym2 are equal.";}else{
document.getElementById("output").innerHTML +="Sym1 and Sym2 are not equal.";}</script></body></html>
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.
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>
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>
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>
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.
The JavaScript math object provides properties and methods for mathematical constants and functions. Unlike other global objects, Math is not a constructor. All the properties and methods of Math are static and can be called by using Math as an object without creating it.
Thus, you refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method’s argument.
Syntax
The syntax to call the properties and methods of Math are as follows −
var pi_val = Math.PI;// Propertyvar sine_val = Math.sin(30);// Method
Lets learn more about the Math objects properties and method via the examples below.
JavaScript Math Properties
Following is the list of properties of Math class in JavaScript −
Sr.No.
Name & Description
1
EEuler’s constant and the base of natural logarithms, approximately 2.718.
After executing the above program, it returns the values of the provided Math properties.
Example (Math ceil() method)
Here, we are computing the JavaScript ceil() method to return the smallest larger integer value than the number passed as an argument. Here, the method returns 6 for the 5.9 value.
<html><head><title> JavaScript - Math.ceil() method </title></head><body><p id ="output"></p><script>let ans = Math.ceil(5.9);
document.getElementById("output").innerHTML ="Math.ceil(5.9) = "+ ans;</script></body></html>
Output
After executing the above program, it returns the result as 6.
Example (Math max() method)
The Math.max() method is used to get the maximum value among the arguments passed as an array.
Here, we have passed six arguments to the Math.max() object, and the method returns the maximum value from them.
<html><head><title> JavaScript - Math.max() method </title></head><body><p id ="output"></p><script>let ans = Math.max(100,10,-5,89,201,300);
document.getElementById("output").innerHTML ="Math.max(100, 10, -5, 89, 201, 300) = "+ ans +"<br>";</script></body></html>
Output
After executing the above program, it returns 300 as maximum value.
Example (Math.cos() method)
The Math.cos() method returns the cosine value of the number passed as an argument. The cosine value of 0 is 1, which you can see in the output of the example below.
<html><head><title> JavaScript - Math.cos() method </title></head><body><p id ="output"></p><script>let ans = Math.cos(0);
document.getElementById("output").innerHTML ="Math.cos(0) = "+ ans;</script></body></html>
Output
If we execute the above program, it returns “1” as result.
The JavaScript Proxy Handlers are used to define custom behavior for fundamental operations performed on objects. By defining handlers, you can override the default behavior of fundamental operations. Following are the common proxy handler methods: apply(), construct(), get(), has(), etc.
JavaScript Handlers
Following are the methods of JavaScript Handler −
Sr.No.
Name & Description
1
apply()Allows you call a function with particular arguments and context.
2
construct()Allows you to define custom behavior for fundamental operations on an object.
3
defineproperty()It is used to define new properties or modify existing ones on an object.
TheDataViewis an object in JavaScript that allows you to work with the binary data stored in theArrayBuffer. It provides a low-level interface for reading and writing number types in a binary ArrayBuffer.
The DataView object provides built-in methods for reading and writing 1, 2, and 4-byte signed and unsigned integers, as well as 4 and 8-byte floating-point numbers from the buffer.
An ArrayBuffer is an array of bytes, usually referred to in other languages as a “byte array”. You cannot directly manipulate the data of an ArrayBuffer like a regular array. Using the ArrayBuffer you can create DataView object, which represents the buffer in a specific format. You can use the DataView object to read from and write to the contents of the buffer.
Syntax
Following is the syntax to create a DataView object in JavaScript −
newDataView(buffer, byteOffset, byteLength)
Here, the buffer is an existing ArrayBuffer used for storage. The byteOffset parameter (optional) represents the offset in bytes to the first byte in the buffer, and the byteLength parameter (also optional) represents the number of elements in the byte array.
Example : Creating a DataView Object
The following example demonstrates how to create a DataView object in JavaScript.
<html><body><script>const buffer =newArrayBuffer(16);//creating dataview objectconst data_view =newDataView(buffer);
document.write("The type of data_view is: "+typeof(data_view));</script></body></html>
Output
The above program displays the type of the data_view as −
The type of data_view is: object
JavaScript DataView Properties
Here is a list of the properties of DataView object −
buffer − It returns the ArrayBuffer of SharedArrayBuffer.
byteLength − It returns the length (in bytes) of this view.
byteOffset − It returns the offset (in bytes) of this view from the start of itsArrayBufferorSharedArrayBuffer.
JavaScript DataView Methods
Following are the methods of the JavaScript DataView object −
Sr.No.
Methods & Description
1
getBigInt64()It returns a BigInt from the range of -263 to 263-1, included.
2
getBigUint64()It returns a BigInt from the range of 0 to 264-1, included.
3
getFloat32()It returns a floating point number from -3.4e38 to 3.4e38.
The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object using either local time or UTC (universal, or GMT) time.
The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so JavaScript can represent the date and time till the year 275755.
Syntax
You can use any of the following syntaxes to create a Date object using the Date() constructor −
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
Note − Parameters in the brackets are always optional.
Parameters
No Argument − With no arguments, the Date() constructor creates a Date object set to the current date and time.
milliseconds − When one numeric argument is passed, it is taken as the internal numeric representation of the date in milliseconds, as returned by the getTime() method. For example, passing the argument 5000 creates a date that represents five seconds past midnight on 1/1/70.
datestring − When one string argument is passed, it is a string representation of a date in the format accepted by the Date.parse() method.
7 agruments − To use the last form of the constructor shown above. Here is a description of each argument −
year − Integer value representing the year. For compatibility (in order to avoid the Y2K problem), you should always specify the year in full; use 1998 rather than 98.
month − Integer value representing the month, beginning with 0 for January to 11 for December.
date − Integer value representing the day of the month.
hour − Integer value representing the hour of the day (24-hour scale).
minute − Integer value representing the minute segment of a time reading.
second − Integer value representing the second segment of a time reading.
millisecond − Integer value representing the millisecond segment of a time reading.
Return Value
It returns the date string containing day, month, date, year, hours, minutes, seconds, and timezone, as shown below.
Wed Aug 09 2023 09:24:03 GMT+0530 (India Standard Time)
JavaScript Date Reference
In JavaScript, the Date object provides methods for creating, manipulating, and formatting dates and times. Here, we have listed all the methods present in Date class −
JavaScript Date Methods
Here is a list of the methods used with Date and their description.
Date Static Methods
These methods are invoked using the Date object −
Sr.No.
Name & Description
1
Date.parse()Parses a string representation of a date and time and returns the internal millisecond representation of that date.
2
Date.UTC()Returns the millisecond representation of the specified UTC date and time.
Date Methods
These methods are invoked using the instance of the Date object −
Sr.No.
Name & Description
1
getDate()Returns the day of the month for the specified date according to local time.
2
getDay()Returns the day of the week for the specified date according to local time.
3
getFullYear()Returns the year of the specified date according to local time.
4
getHours()Returns the hour in the specified date according to local time.
5
getMilliseconds()Returns the milliseconds in the specified date according to local time.
6
getMinutes()Returns the minutes in the specified date according to local time.
7
getMonth()Returns the month in the specified date according to local time.
8
getSeconds()Returns the seconds in the specified date according to local time.
9
getTime()Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC.
10
getTimezoneOffset()Returns the time-zone offset in minutes for the current locale.
11
getUTCDate()Returns the day (date) of the month in the specified date according to universal time.
12
getUTCDay()Returns the day of the week in the specified date according to universal time.
13
getUTCFullYear()Returns the year in the specified date according to universal time.
14
getUTCHours()Returns the hours in the specified date according to universal time.
15
getUTCMilliseconds()Returns the milliseconds in the specified date according to universal time.
16
getUTCMinutes()Returns the minutes in the specified date according to universal time.
17
getUTCMonth()Returns the month in the specified date according to universal time.
18
getUTCSeconds()Returns the seconds in the specified date according to universal time.
19
setDate()Sets the day of the month for a specified date according to local time.
20
setFullYear()Sets the full year for a specified date according to local time.
21
setHours()Sets the hours for a specified date according to local time.
22
setMilliseconds()Sets the milliseconds for a specified date according to local time.
23
setMinutes()Sets the minutes for a specified date according to local time.
24
setMonth()Sets the month for a specified date according to local time.
25
setSeconds()Sets the seconds for a specified date according to local time.
26
setTime()Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC.
27
setUTCDate()Sets the day of the month for a specified date according to universal time.
28
setUTCFullYear()Sets the full year for a specified date according to universal time.
29
setUTCHours()Sets the hour for a specified date according to universal time.
30
setUTCMilliseconds()Sets the milliseconds for a specified date according to universal time.
31
setUTCMinutes()Sets the minutes for a specified date according to universal time.
32
setUTCMonth()Sets the month for a specified date according to universal time.
33
setUTCSeconds()Sets the seconds for a specified date according to universal time.
34
toDateString()Returns the “date” portion of the Date as a human-readable string.
In the example below, we create a new instance of the date object. In the output, you can observe that it returns the current time.
<html><head><title> JavaScript - Date object </title></head><body><p id = "output"></p><script>
const date = new Date();
document.getElementById("output").innerHTML =
"Today's date is : " + date;
</script></body></html>
Output
If we execute the above program, it returns the current time.
Example: Setting up custom date
In the example below, We have passed the custom date string as a parameter of the Date() constructor to create a custom date.
The Date() constructor returns the standard date string, which you can see in the output.
<html><head><title> JavaScript - Date object </title></head><body><p id = "output"></p><script>
const date = new Date("August 19, 2024 09:30:54");
document.getElementById("output").innerHTML =
"The custom date is : " + date;
</script></body></html>
Output
If we execute the above program, it returns the custom time as provided.
Example
In the example below, we have passed milliseconds as an argument of the Date() constructor. If you pass the positive milliseconds as an argument, the object returns the date according to the 1st January 1970 00:00:00 + milliseconds.
Otherwise, it returns the date according to the 1st January 1970 00:00:00 milliseconds if negative milliseconds passed as an argument.
<html><head><title> JavaScript - Date object </title></head><body><p id = "output"></p><script>
const output = document.getElementById("output");
let date = new Date(999999999999);
output.innerHTML += "The Date after 1st January, 1970 is - " + date + "<br>";
date = new Date(-999999999999);
output.innerHTML += "The Date before 1st January, 1970 is - " + date;
</script></body></html>
Output
It returns the date after 1st January, 1970 and before 1st January, 1970 as result.
Example: Constructing a date from 7 arguments
In the example below, we have passed the year, month, date, hour, minute, second, and millisecond as a Date() constructor argument. The Date() constructor returns the full date string, which you can see in the output.
<html><head><title> JavaScript - Date object </title></head><body><p id = "output"></p><script>
const date = new Date(2001, 5, 14, 6, 43, 58, 342);
document.getElementById("output").innerHTML =
"The custom date is : " + date;
</script></body></html>
Output
If we execute the above program, it returns the custom time as provided.
However, you can use the different methods of the Date object to format the date string. Lets look at the example below.
Example: Formatting a date string
In the example below, three different methods are used to format the date string.
The toDateString() method extracts the date only from the date string and removes the time part.
The toISOString() method converts the date string into the ISO format.
The toUTCString() method converts the date string into the UTC time format.
<html><head><title> JavaScript - Formatting the date </title></head><body><p id = "output"></p><script>
const date = new Date(999999999999);
document.getElementById("output").innerHTML +=
"The Date after 1st January, 1970 is: " + date.toDateString() + "<br>"+
"The Date after 1st January, 1970 is: " + date.toISOString() + "<br>"+
"The Date after 1st January, 1970 is: " + date.toUTCString();
</script></body></html>
Output
It will return the ouptut of the above provided methods, respectively.
The JavaScript Array object lets you store multiple values in a single variable. An array is used to store a sequential collection of multiple elements of same or different data types. In JavaScript, arrays are dynamic, so you dont need to specify the length of the array while defining the array. The size of a JavaScript array may decrease or increase after its creation.
Syntax
Use the following syntax to create an array object in JavaScript −
const arr =newArray(val1, val2, val3,..., valN)
Parameters
val1, val2, val3, …, valN − It takes multiple values as an argument to initialize an array with them.
Return value
It returns an array object.
Note − When you pass the single numeric argument to the Array() constructor, it defines the array of argument length containing the undefined values. The maximum length allowed for an array is 4,294,967,295.
You can add multiple comma separated elements inside square brackets to create an array using the array literal −
const fruits = [ "apple", "orange", "mango" ];
You will use ordinal numbers to access and to set values inside an array as follows.
fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element
JavaScript Array Reference
In JavaScript, the Array object enables storing collection of multiple elements under a single variable name. It provides various methods and properties to perform operations on an array. Here, we have listed the properties and methods of the Array class.
JavaScript Array Properties
Here is a list of the properties of the Array object along with their description −
Sr.No.
Name & Description
1
constructorReturns a reference to the array function that created the object.
2
lengthReflects the number of elements in an array.
JavaScript Array Methods
Here is a list of the methods of the Array object along with their description −
Array Static methods
These methods are invoked using the Array class itself −
toSpliced()This method returns a new array with some elements removed and/or replaced at a given index.
35
toString()Returns a string representing the array and its elements.
36
unshift()Adds one or more elements to the front of an array and returns the new length of the array.
37
values()To get an iterator containing values of each array index.
38
with()This method returns a new array with the element at the given index replaced with the given value.
Basic Examples of JavaScript Array Object
In the following examples, we have demonstrated the usage of basic methods and properties of JavaScript Array Object −
Example (Creating JavaScript Array Object)
In the example below, the array strs is initialized with the string values passed as an Array() constructors argument.
The cars array contains 20 undefined elements. If you pass multiple numeric values, it defines the array containing those elements but needs to be careful with a single numeric argument to the array() constructor.
Execute the above program to see the desired output.
strs ==> Hello,World!,Tutorials Point
cars ==> ,,,,,,,,,,,,,,,,,,,
Example (Creating Arrays Using Array Literal)
In the example below, we have created different arrays. The arr1 array contains the numbers, the arr2 array contains the strings, and the arr3 array contains the boolean values.
The array index starts from 0. So, you can access the array element using its index.
let number = arr[index]
In the above syntax, arr is an array, and index is a number from where we need to access the array element.
Example
In the example below, we have created the array of numbers and accessed the elements from the 0th and 2nd index of the array. The element at the 0th index is 1, and the element at the 2nd index is 6.
<html><head><title> JavaScript - Accessing array elements </title></head><body><p id ="output"></p><script>const nums =[1,5,6,8,90];
document.getElementById("output").innerHTML ="Element at 0th index is : "+ nums[0]+"<br>"+"Element at 2nd index is : "+ nums[2];</script></body></html>
Output
Element at 0th index is : 1
Element at 2nd index is : 6
JavaScript Array length
The length property of the array is used to find the length of the array.
let len = arr.length;
Example
In the example below, the length property returns 5, as array contains 5 elements.
<html><head><title> JavaScript - Array length </title></head><body><p id ="output"></p><script>const nums =[1,5,6,8,90];
document.getElementById("output").innerHTML ="Array length is : "+ nums.length;</script></body></html>
Output
Array length is : 5
Adding a new element to the array
You can use the push() method to insert the element at the end of the array. Another solution is that you can insert the array at the index equal to the array length.
arr.push(ele)OR
arr[arr.length]= ele;
In the above syntax, ele is a new element to insert into the array. Here, if the array length is N, the array contains elements from 0 to N 1 index. So, we can insert the new element at the Nth index.
Example
In the example below, we insert 6 to the array using the push() method. Also, we used the length property to insert the element at the end.
<html><body><p id ="output"></p><script>const output = document.getElementById("output");const nums =[1,2,3,4,5];
nums.push(6);// Inserting 6 at the end
output.innerHTML +="Updated array is : "+ nums +"<br>";
nums[nums.length]=7;// Inserting 7
output.innerHTML +="Updated array is : "+ nums +"<br>"</script></body></html>
Output
As we can see in the output, provided element has been added.
Updated array is : 1,2,3,4,5,6
Updated array is : 1,2,3,4,5,6,7
Updating JavaScript Array Elements
To update any array element, you can access the array index and change its value.
arr[index]= ele;
In the above syntax, index is an index where we need to update a value with the ele value.
Example
In the example below, we update the element at the first index in the array.
<html><body><p id ="output"></p><script>const nums =[1,2,3,4,5];
nums[0]=100;// Updating first element
document.getElementById("output").innerHTML ="Updated array is : "+ nums;</script></body></html>
Output
Updated array is : 100,2,3,4,5
Traversing a JavaScript Array
You can use the loop to traverse through each array element. However, some built-in methods exist to traverse the array, which we will see in later chapters.
for(let p =0; p < nums.length; p++){// Access array using the nums[p]}
Example
In the below code, the array contains 5 numbers. We used the for loop to traverse the array and print each element.
However, while and do-while loops can also be used to traverse the array.
<html><body><p id ="demo"></p><script>const output = document.getElementById("demo");const nums =[1,2,3,4,5];for(let p =0; p < nums.length; p++){
output.innerHTML +="nums["+ p +"] ==> "+ nums[p]+"<br>";}</script></body></html>
The String object in JavaScript lets you work with a series of characters; it wraps JavaScript’s string primitive data type with a number of helper methods.
As JavaScript automatically converts between string primitives and String objects, you can call any of the helper methods of the String object on a string primitive.
The string is a sequence of characters containing 0 or more characters. For example, ‘Hello’ is a string.
Syntax
JavaScript strings can be created as objects using the String() constructor or as primitives using string literals.
Use the following syntax to create a String object −
var val =newString(value);
The String parameter, value is a series of characters that has been properly encoded.
We can create string primitives using string literals and the String() function as follows −
str1 ='Hello World!';// using single quote
str2 ="Hello World!";// using double quote
str3 ='Hello World';// using back ticks
str4 =String('Hello World!');// using String() function
JavaScript String Object Properties
Here is a list of the properties of String object and their description.
You can access the string characters using its index. The string index starts from 0.
Example
In the example below, we access the character from the 0th and 4th index of the string.
<html><body><p id ="output"></p><script>const output = document.getElementById("output");let str1 =newString("Welcome!");let str2 ="Welcome!";
output.innerHTML +="0th character is - "+ str1[0]+"<br>";
output.innerHTML +="4th character is - "+ str2[4]+"<br>";</script></body></html>
Output
0th character is - W
4th character is - o
JavaScript string is case-sensitive
In JavaScript, strings are case-sensitive. It means lowercase and uppercase characters are different.
Example
In the example below, char1 contains the uppercase ‘S’, and char2 contains the lowercase ‘s’ characters. When you compare char1 and char2, it returns false as strings are case-sensitive.
<html><head><title> JavaScript - String case-sensitivity </title></head><body><p id ="output"><script>let char1 ='S';let char2 ='s'let ans = char1 == char2;
document.getElementById("output").innerHTML +="s == S "+ ans;</script></body></html>
Output
s == S false
JavaScript Strings Are Immutable
In JavaScript, you can’t change the characters of the string. However, you can update the whole string.
Example
In the example below, we try to update the first character of the string, but it doesn’t get updated, which you can see in the output.
After that, we update the whole string, and you can observe the changes in the string.
<html><head><title> JavaScript − Immutable String </title></head><body><p id ="output"></p><script>const output = document.getElementById("output");let str ="Animal";
str[0]='j';
output.innerHTML +="The string is: "+ str +"<br>";
str ="Hi!";
output.innerHTML +="The updated string is: "+ str;</script></body></html>
Output
The string is: Animal
The updated string is: Hi!
Escape Characters
You can use the special characters with the string using the backslash (\) characters. Here is the list of special characters.
Escape character
Description
\”
Double quote
\’
Single quote
\\
Backslash
\n
New line
\t
Tab
\b
backspace
\f
Form feed
\v
Verticle tab
\r
Carriage return
\uXXXX
Unicode escape
Example
In the example below, we added a single quote between the characters of the str1 string and a backslash between the characters of the str2 string.