JavaScript – ES5 ”; Previous Next JavaScript ES5, also known as ECMAScript 5, was released in 2009. It was the first major revision of JavaScript. It introduced many new features, including getters and setters, and ”use strict” directive. ES5 has provided significant improvement over the previous versions of JavaScript. The new features introduced in ES5 make code more powerful, concise and easier to maintain. New Added Features in JavaScript ES5 Here are the new methods, features, etc., added to the ES5 version of JavaScript. Array every() Array filter() Array forEach() Array isArray() Array indexOf() Array lastIndexOf() Array map() Array reduce() Array reduceRight() Array some() Date now() Date toJSON() Date toISOString() Function bind() JSON parse() JSON stringify() Multiline strings Object methods Object defineProperty() Property getters and setters Reserved words as property names “use strict” String[number] access String trim() Trailing commas Here, we have explained each feature in detail. JavaScript Array every() The array.every() method checks whether each element of the array follows a particular condition. Example In the below code, we use the array.every() method to check whether each element of the array is even. <html> <body> <div id = “output”> All elements of the array are even? </div> <script> const arr = [10, 20, 30, 40, 2, 6]; function even(element) { return element % 2 == 0; } document.getElementById(“output”).innerHTML += arr.every(even); </script> </body> </html> Output All elements of the array are even? true JavaScript Array filter() The array.filter() filters array elements and gets filtered elements in the new array. Example In the below code, we filter the array elements which are divisible by 10. <html> <body> <div id = “output”> Elements divisible by 10 are </div> <script> const arr = [10, 20, 8, 30, 40, 2, 6]; function divide(element) { return element % 10 == 0; } document.getElementById(“output”).innerHTML += arr.filter(divide); </script> </body> </html> Output Elements divisible by 10 are 10,20,30,40 JavaScript Array forEach() The array.forEach() traverses the array elements. It is similar to loops in JavaScript. Example The below code uses the array.forEach() method to traverse the array and print each array element in the new line. <html> <body> <div id=”output”> </div> <script> const arr = [“TATA”, “Honda”, “Toyota”, “Maruti”]; arr.forEach(traverse); // Using the array.forEach() method function traverse(element) { document.getElementById(“output”).innerHTML += element + “<br>”; } </script> </body> </html> Output TATA Honda Toyota Maruti JavaScript Array isArray() The Array.isArray() method checks whether the object passed as an argument is an array. Example The below code checks whether the arr is an array using the Array.isArray() method. <html> <body> <div id = “output”> </div> <script> const arr = [“TATA”, “Honda”, “Toyota”, “Maruti”]; let bool = Array.isArray(arr); document.getElementById(“output”).innerHTML += “Is arr array? ” + bool; </script> </body> </html> Output Is arr array? true JavaScript Array indexOf() The array.indexOf() method returns the first index of the particular element in the array. Example The below code finds the first index of 23 in the array, which is 0. <html> <body> <div id = “output”> The first index of 23 in the array is </div> <script> const arr = [23, 45, 32, 12, 23, 56]; document.getElementById(“output”).innerHTML += arr.indexOf(23); </script> </body> </html> Output The first index of 23 in the array is 0 JavaScript Array lastIndexOf() The array.lastIndexOf() method returns the last index of the particular element in the array. Example The code below finds the last index of the 45 in the array, which is 4. <html> <body> <div id = “output”> The last index of 45 in the array is </div> <script> const arr = [23, 45, 32, 45, 45, 56]; document.getElementById(“output”).innerHTML += arr.lastIndexOf(45); </script> </body> </html> Output The last index of 45 in the array is 4 JavaScript Array map() The array.map() method returns a new array after mapping current array elements with new ones. Example The below code uses the map() method to create a new array by doubling the array elements. <html> <body> <div id = “output”> The new array is </div> <script> const arr = [1, 2, 3, 4, 5]; function doubleEle(element) { return element * 2; } document.getElementById(“output”).innerHTML += arr.map(doubleEle); </script> </body> </html> Output The new array is 2,4,6,8,10 JavaScript Array reduce() The array.reduce() method reduces the array to a single value. Example The below code multiples all elements of the array using the array.reduce() method. <html> <body> <div id = “output”>The multiplication result of the array elements is </div> <script> const arr = [1, 2, 3, 4, 5]; function multiplier(multiplication, element) { return multiplication * 2; } document.getElementById(“output”).innerHTML += arr.reduce(multiplier); </script> </body> </html> Output The multiplication result of the array elements is 16 JavaScript Array reduceRight() The array.reduceRight() method reduces the array from right to left instead of left to right. Example <html> <body> <div id = “output”>The merged array elements in the reverse order is: </div> <script> const arr = [“How”, “are”, “you”, “doing?”]; function merge(res, element) { return res += element + ” “; } document.getElementById(“output”).innerHTML += arr.reduceRight(merge); </script> </body> </html> Output The merged array elements in the reverse order is: doing?you are How JavaScript Array some() The array.some() method is used to check whether some elements of the array follow the particular condition. Example The code below checks whether the array contains 1 or more strings with lengths greater than 3. <html> <body> <div id = “output”>Array contains one or more strings with lengths greater than 3? </div> <script> const arr = [“How”, “are”, “you”, “doing?”]; function func_len(element) { return element.length > 3; } document.getElementById(“output”).innerHTML += arr.some(func_len); </script> </body> </html> Output Array contains one or more strings with lengths greater than 3? true JavaScript Date now() The Date.now() method is used to get the total number of milliseconds since 1st January 1970. Example The below code finds the total milliseconds from 1st January 1970. <html> <body> <div id = “output”>Total milliseconds since 1st January, 1970 is: </div> <script> document.getElementById(“output”).innerHTML += Date.now(); </script> </body> </html> Output Total milliseconds since 1st January, 1970 is: 1702540225136 JavaScript Date toJSON() The date.toJSON() method converts the date into the JSON date format. The JSON date format is
Category: javascript
JavaScript – Object Methods
JavaScript – Object Methods ”; Previous Next JavaScript Object Methods JavaScript object methods are object properties that contains function definitions. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property”s value can be a function; in that case the property is known as a method. You can either directly add a method to the object or add it as a property value. The method can also take the parameters and return the value. Object methods are a powerful way to add functionality to objects. They allow you to encapsulate code and make it reusable. Syntax Follow the syntax below to add a method to the object. const obj = { sum: function () { // Method body } } obj.sum(); In the above syntax, ”sum” is a method defined inside the ”obj” object. You can access the method as you access the object property and add the pair of parenthesis to invoke the method. Example We added the getInfo() method in the ”company” object in the example below. The getInfo() method returns the string containing the object properties. Here, we used the ”this” keyword to access the object properties inside the object. The ”this” keyword represents the object itself. After that, we used the object as a reference to invoke the method. <html> <body> <p>Company Information</p> <p id = “output”> </p> <script> const company = { companyName: “Tutorials Point”, companyWebsite: “www.tutorialspoint.com”, getInfo: function () { return “Comapny Name: ” + this.companyName +”<br>Website: ” + this.companyWebsite; }, } document.getElementById(“output”).innerHTML = company.getInfo(); </script> </body> </html> Output Company Information Comapny Name: Tutorials Point Website: www.tutorialspoint.com Object Method Shorthand The ES6 provides the shortest way to define a method into the object. Syntax Follow the syntax below to add a method to the object. const Obj = { sum() { // Method body } } Obj.sum(); Like the previous one, you can access and invoke the method in the above syntax. Example In the example below, we defined the getInfo() method as the previous example. <html> <body> <p id = “output”> </p> <script> const employee = { name: “John Doe”, age: 32, getInfo() { return “The employee name is ” + this.name + ” and his age is ” + this.age + ” Years.”; }, } document.getElementById(“output”).innerHTML = employee.getInfo(); </script> </body> </html> Output The employee name is John Doe and his age is 32 Years. Example The example below defines the getSum() method inside the ”nums” object. The getSum() method takes the two parameters and returns their sum. We passed the number arguments to the method while invoking it. <html> <body> <p id = “output”>The sum of 2 and 3 is </p> <script> const nums = { getSum(a, b) { return a + b; } } document.getElementById(“output”).innerHTML += nums.getSum(2, 3); </script> </body> </html> Output The sum of 2 and 3 is 5 Updating or Adding a Method to the Object In JavaScript, updating or adding a new method to the object is same as updating or adding new proeprties to the object. You can either use the dot or square bracket notation to update or add method to the object. Example The example below defines the getSum() method inside the ”nums” object. After that, we add the getMul() method inside the nums object. We invoke the getMul() method by passing two arguments to get the multiplication of them. <html> <body> <p id = “output”>The multiplication of 2 and 3 is </p> <script> const nums = { getSum(a, b) { return a + b; } } nums.getMul = function (a, b) { return a * b; } document.getElementById(“output”).innerHTML += nums.getMul(2, 3); </script> </body> </html> Output The multiplication of 2 and 3 is 6 Using Built-in Methods JavaScript objects like string, number, boolean, etc., also contain built-in methods. You can execute them by taking the object as a reference. Example In the example below, we have defined the ”num” variable containing the numeric value. After that, we used the toString() method to convert the number to a string. <html> <body> <p id = “demo”> </p> <script> const output = document.getElementById(“demo”); const num = new Number(20); let str = num.toString(); output.innerHTML += “After converting the number to string: ” + str + “<br>”; output.innerHTML += “Data type of after conversion: ” + typeof str; </script> </body> </html> Output After converting the number to string: 20 Data type of after conversion: string Print Page Previous Next Advertisements ”;
ECMAScript 2016
JavaScript – ECMAScript 2016 ”; Previous Next The ECMAScript 2016 version of JavaScript was released in 2016. Previously the old versions of JavaScript are named by numbers for example ES5 and ES6. Since 2016 the versions are named by the year they are released for example ECMAScript 2016, ECMAScript 17, etc. Lets discuss the featues added in ECMAScript 2016. New Features Added in ECMAScript 2016 Here are the new methods, features, etc., added to the ECMAScript 2016 version of JavaScript. Array includes() method Exponentiation Operator (**) Exponentiation Assignment Operator (**=) Here, we have explained each feature in detail. JavaScript Array includes() Method The JavaScript array includes() methods is used to check whether the array contains a particular element. Syntax The syntax of Array includes() method in JavaScript is as follows − arr.include(searchElement, fromIndex); Here arr is the original array, the searchElement is to be search from. The fromIndex is an optional argument if passed, the searching will start from the fromIndex index. Example In the below code, we use the array includes() method to check whether the watches array contains the ”Noise” brand. <html> <body> <div id = “output”>Does watches array include Noise?</div> <script> const watches = [“Titan”, “Rolex”, “Noise”, “Fastrack”, “Casio”]; document.getElementById(“output”).innerHTML += watches.includes(“Noise”); </script> </body> </html> Output Does watches array include Noise? true Example In the below code, we use the array includes() method to check whether the subjects array contains the ”Python” subject searching from index 1. <html> <body> <div id = “output”>Does subjects array include Python fromIndex 1? </div> <script> const subjects = [“Java”, “JavaScript”, “Python”, “C”, “C++”]; document.getElementById(“output”).innerHTML += subjects.includes(“Python”, 1); </script> </body> </html> Output Does subjects array include Python fromIndex 1? true JavaScript Exponentiation Operator The JavaScript exponentiation operator is used to find the power of the first operand raised to the second operand. Syntax The syntax of expponentiation operator is as follow − x ** y; It returns the result of raising the first operand (x) to the power of the second operand (y). Example In the below code, we find the 22 using the exponentiation operator and store the resultant value in the ”res” variable. <html> <body> <div id = “output”>The resultant value for 2 ** 2 is: </div> <script> document.getElementById(“output”).innerHTML += 2 ** 2; </script> </body> </html> Output The resultant value for 2 ** 2 is: 4 Exponentiation Assignment Operator The JavaScript exponentiation assignment operator raises the power of the first operand by the second operand and assigns it to the first operand. Syntax The syntax of exponentiation assignment operator is as follows − x **= y; It assigns the result of raising the first operand (x) to the power of the second operand (y) to x. Example In the below code, we find the 102 and assign the resultant value to the ”num” variable using the exponentiation assignment operator. <html> <body> <div id = “output”>The resultant value for 10 ** 2 is: </div> <script> let num = 10; num **= 2; // exponentiation assignment operation document.getElementById(“output”).innerHTML += num; </script> </body> </html> Output The resultant value for 10 ** 2 is: 100 ECMAScript 2016 Browser Support Most modern browsers support the ECMAScript 2016 version of JavaScript Chrome Firefox Microsoft Edge Opera Safari Firefox Android Yes Yes Yes Yes Yes Yes Print Page Previous Next Advertisements ”;
JavaScript – Native Prototypes ”; Previous Next Native Prototypes The native prototypes in JavaScript are property of Object.prototype object. The prototypes are the mechanism by which the objects inherit features from one another. In JavaScript, each object contains the prototype property. The prototype of each object contains the methods and properties related to the object. So, it is also called the native prototype. However, you can update or add new methods and properties to the native prototype object, but you can”t delete any already existing. The JavaScript object and object constructor are the main prerequisites to understand JavaScript native prototypes. Syntax You can follow the syntax below to access the native prototype of the object. Object.prototype; In the above syntax, the object can be any JavaScript object. Example: Accessing the array”s prototype Whenever you execute the below code in the browser, it will print the prototype of the array in the browser console. In the same way, you can check the prototype of the other objects. In the console, you can see that the prototype object contains the methods which you can use with array methods. <html> <body> <script> console.log(Array.prototype); </script> <p>Please open the web console before executing the above program.</p> </body> </html> Output On running the above program, you will see the result in web console similar to the following screenshot − Updating the Native Prototype You can update the existing method or property of the native prototype object or add a new method or property to the native prototype object. Syntax You can follow the syntax below to update or add new properties or methods to the prototype object. objName.prototype.name = value In the above syntax, objName is an object whose prototype you need to update. The ”name” is a method or property name. You can assign new values or function expressions to the ”name’. Example: Updating the toLowerCase() method of the string object”s prototype The prototype of the String object contains the toLowerCase() method. Here, we update the toLowerCase() method. The updated toLowerCase() method returns the string in the uppercase. In the output, you can observe the string, which is in uppercase. In this way, you can update the functionality of the built-in methods of the object. <html> <body> <p id = “output”>After updating the string.toLowerCase() method: </p> <script> String.prototype.toLowerCase = function () { return this.toUpperCase(); } let str = “Hello World”; document.getElementById(“output”).innerHTML += str.toLowerCase(); </script> </body> </html> Output After updating the string.toLowerCase() method: HELLO WORLD You shouldn”t update the methods and properties of the native prototype object. However, you can add new as shown in the example below. Example: Adding a new method to the prototype object You can also add a new method to the Object prototype. Here, we added the firstCase() method in the object prototype. The firstCase() method returns a string after converting the string”s first character to the uppercase. <html> <body> <p id = “output”>After executing the string.firstCase() method: </p> <script> String.prototype.firstCase = function () { // First character in uppercase. Other characters in lowercase. return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase(); } let str = “hello world”; document.getElementById(“output”).innerHTML += str.firstCase(); </script> </body> </html> Output After executing the string.firstCase() method: Hello world Adding a method to the constructor function Whenever you define an object using the constructor function, you can”t add a method or property to the constructor function using its instance. So, you need to add the method to the constructor function prototype. So it can be accessible through all instances of the object. Example In the example below, the Person() is a constructor function that initializes object properties. After that, we added the display() method to the prototype of the person() function. Next, we created two instances of the Person() function and used the display() method with them. So, methods and properties added in the prototype of the object constructor can be accessed through all instances of the constructor function. <html> <body> <p id = “demo”> </p> <script> const output = document.getElementById(“demo”); function Person(id, name) { this.id = id; this.name = name; } Person.prototype.display = function () { output.innerHTML += this.id + “, ” + this.name + “<br>”; } const p1 = new Person(1, “James”); const p2 = new Person(2, “Nayan”); p1.display(); p2.display(); </script> </body> </html> Output 1, James 2, Nayan All instances of the object inherit the properties and methods from their parent”s prototype. JavaScript Prototype Chaining Simply, you can say that the prototype stores the default values of the properties. The code overrides the prototype property value if the object constructor and its prototype contain the same properties. Example In the below code, the Person() function contains the name property. We have added the name and age property in the function”s prototype. We have created the p1 object using the Person() constructor function. The value of the name property of the p1 object is ”Nayan” as the name already exists in the constructor. The value of the age property is 20, which is the same as the age property value in the prototype. <html> <body> <p id = “output”> </p> <script> function Person(id, name) { this.id = id; this.name = name; } Person.prototype.name = “John”; Person.prototype.age = 20; const p1 = new Person(1, “Adam”); document.getElementById(“output”).innerHTML = “Id: ” + p1.id + “, Name: ” + p1.name + “, Age: ” + p1.age; </script> </body> </html> Output Id: 1, Name: Adam, Age: 20 Print Page Previous Next Advertisements ”;
JavaScript – Encapsulation
JavaScript – Encapsulation ”; Previous Next What is Encapsulation? Encapsulation in JavaScript is a way to keep the related properties and methods under a single namespace by bundling them. It can be a function, a class or an object. In JavaScript, the encapsulation can be implemented using closures, classes and getters and setters. Encapsulation is a fundamental concept in Object-oriented programming languages, along with inheritance and polymorphism. JavaScript is an object oriented programming language. It is used to hide the data from the outside world and give access to required data only to improve the integrity and security of the data. What is the need for encapsulation? Let”s discuss the need for encapsulation in JavaScript via the following example. For example, you have defined the below object in your code. const car = { Brand: “Honda city”, model: “sx”, year: 2016, } Anyone can access the properties of the car object, as shown below. car.Brand Also, anyone can change the value of any property of the car object, as shown below. car.Brand = true; Here, the value of the Brand property is changed to the boolean from the string. So, it is required to secure the original data of the object and give limited access to the data to the outside world. In this situation, the concept of encapsulation comes into the picture. Different Ways to Achieve Encapsulation in JavaScript There are three different ways to achieve encapsulation. Using the function closures Using the ES6 classes Using the Getters and Setters Here, we will learn each approach for achieving encapsulation one by one. Achieving Encapsulation Using the Function Closures A JavaScript function closure is a concept allowing the inner function to access the variable defined in the outer function even after the outer function is executed. The variables defined in the outer function can”t be accessed outside its functional scope but can be accessed using the inner scope. Example In the below code, shoppingCart() function is an outer function that contains the variables and function. The outer function has its private scope. The carItems[] array is used to store the shopping cart”s items. The add() function can access the carItems[] array and add items. The remove() function checks whether the cartItems[] contains the items you need to remove. If yes, it removes the item. Otherwise, it prints the message that you can”t remove the item. The shoppingCart() function returns the object containing the add() and remove() functions. After creating a new instance of the shoppingCart() function, you can use the add() and remove() functions to manipulate the shopping cart data. <html> <body> <p id = “output”> </p> <script> let output = document.getElementById(“output”); function shoppingCart() { const cartItems = []; function add(item) { cartItems.push(item); output.innerHTML += `${item.name} added to the cart. <br>`; } function remove(itemName) { const index = cartItems.findIndex(item => item.name === itemName); if (index !== -1) { const removedItem = cartItems.splice(index, 1)[0]; output.innerHTML += `${removedItem.name} removed from the cart. <br>`; } else { output.innerHTML += `Item ${itemName} not found in the cart. <br>`; } } return { add, remove, }; } // Defining items const item1 = { name: ”Car”, price: 1000000 }; const item2 = { name: ”Bike”, price: 100000 }; // Create a new Shopping cart const cart = shoppingCart(); // Adding items to the cart cart.add(item1); cart.add(item2); // Remove bike from the cart cart.remove(”Bike”); </script> </body> </html> Output Car added to the cart. Bike added to the cart. Bike removed from the cart. In this way, no one can directly access and modify the cartItems[] array. Achieving Encapsulation Using ES6 Classes and Private Variables In JavaScript, you can use classes and private variables to achieve the encapsulation. Private Variables (Fields) in JavaScript To define the private class variables, you can write a variable name followed by the ‘#’ sign. For example, ”name” is a private variable in the below code. class car { #name= “TATA”; } If you try to access the name by the instance of the class, it will give you an error that private fields can”t be accessed outside the class. To achieve encapsulation, you can define the private variables in the class and give them access to the outside world using different methods. Example In the example below, we have defined the car class. The car class contains the ”brand”, ”name”, and ”milage” private variables. The getMilage() method is defined to return the milage of the car, and the setMilage() method is used to set the milage of the method. We created the car class”s object and used the method to access and modify the private fields. If you try to access the private field of the class, the code will throw an error. You can also define more methods in the class to access and modify other private fields. <html> <body> <div id = “output1”>The car mileage is: </div> <div id = “output2”>After updating the car mileage is: </div> <script> class Car { #brand = “TATA”; // Private field #name = “Nexon”; // Private field #milage = 16; // Private field getMilage() { return this.#milage; // Accessing private field } setMilage(milage) { this.#milage = milage; // Modifying private field } } let carobj = new Car(); document.getElementById(“output1”).innerHTML += carobj.getMilage(); carobj.setMilage(20); document.getElementById(“output2”).innerHTML += carobj.getMilage(); // carobj.#milage); will throw an error. </script> </body> </html> Output The car mileage is: 16 After updating the car mileage is: 20 Achieving Encapsulation Using the Getters and Setters The JavaScript getters and setters can be defined using the get and set keywords, respectively. The getters are used to get the class properties, and setters are used to update the class properties. They are very similar to the class methods but defined using the get/set keyword followed by the method name. Example In the example below, we have defined the User class containing the three private fields named username, password, and isLoggedIn. The getters and setters named username are defined to get and set user names. Here, you can observe that name of the
JavaScript – Global Object
JavaScript – Global Object ”; Previous Next Global Objects in JavaScript The JavaScript global object allows you to access the variables, functions, objects, etc., defined in the global scope and available everywhere in the code. In the browser, a global object is named as ”window”, and in Node.js, the global object is named ”global”. However, the global object could have different names in different run-time environments. The ”globalThis” has been introduced in ECMAScript 2020, which works with most browsers and run time environments as a global object. Syntax We can follow the syntax below to use the global object to access the variables available everywhere in the JavaScript code. var a = 10; let b = window.a; // Accessing the global variable in the browser In the above syntax, variable ”a” is a global variable, as it is defined in the global scope using the var keyword. Examples Example: Accessing global variables through the global object In the below example, we have defined the ”name” variable in the global scope using the var keyword. After that, we access the name variable using the window (global) object. <html> <body> <div id = “output”>The company name is: </div> <script> var name = “Tutorialspoint”; let company = window.name; document.getElementById(“output”).innerHTML += company; </script> </body> </html> Output The company name is: Tutorialspoint Similarly, if you define the function in the global scope, you can access it anywhere using the global object. Example: Accessing the global function through the global object In the below example, we have defined the sum() function in the global scope. After that, we have defined the obj object containing the num1, num2, and sum properties. The sum properties are initialized with a value returned by the sum() function. We used the” window” object to invoke a global sum() function. So, you can access the global variable and instances anywhere in the JavaScript code using the global object. <html> <body> <p id = “output”> </p> <script> function sum(a, b) { return a + b; } const obj = { num1: 10, num2: 20, sum: window.sum(10, 20), } document.getElementById(“output”).innerHTML += “The object is: ” + JSON.stringify(obj); </script> </body> </html> Output The object is: {“num1″:10,”num2″:20,”sum”:30} If you want to make value globally accessible from the local scope, you can directly add value to the ”window” object as a property. Let”s look at the example below. Example: Making variable globally accessible from the function scope In the example below, we add the ”addition” property to the window object in the sum() function”s body to make it available everywhere. After that, we access the ”addition” property using the ”window” object. <html> <body> <div id = “output”> </div> <script> function sum(a, b) { window.addition = a + b; } sum(20, 30); document.getElementById(“output”).innerHTML = “The sum is: ” + window.addition; </script> </body> </html> Output The sum is: 50 You can also access the global variables without using the global object like a window, as the script is assigned under the object by the JavaScript scripting engine by default. However, you can use the global object to make a variable or expression global. The JavaScript global object itself contains various methods like isNaN(), decodeURI(), etc. You can access them using the global object-like window in the browser and global in Node.js. Example: Accessing pre-defined methods of the global object The JavaScript isNaN() method of the window object is used to check whether the argument passed is a number or not. If the argument is a number, it returns false. Otherwise, it returns true. <html> <body> <p id = “output”> </p> <script> let isNumer = window.isNaN(“Hello”); document.getElementById(“output”).innerHTML = “Is hello not a number? ” + isNumer; </script> </body> </html> Output Is hello not a number? true Using the JavaScript Global Object for Polyfills You can use the JavaScript global object to check whether your browser supports a particular feature. You can show a related message if the user”s browser does not support a particular feature. Look at the example below to check whether the user”s browser supports the promises. Example In the below code, we check whether the ”promise” property exists in the window object. If yes, promises are supported by the browser, and you can execute the promise. Otherwise, you can print the message that your browser doesn”t support promise. <html> <body> <p id = “output”> </p> <script> const output = document.getElementById(“output”); if (window.Promise) { output.innerHTML += “Your browser supports promises”; } else { output.innerHTML += “Your browser doesn”t support promises”; } </script> </body> </html> Output Your browser supports promises The JavaScript global object only stores the truly global variables. You shouldn”t store the variable in the global object that is not global. Otherwise, it can create conflicts in your project. Print Page Previous Next Advertisements ”;
JavaScript – Array Destructuring ”; Previous Next Array Destructuring JavaScript Array destructuring allows us to unpack the values from array and assign them to the variables. After that, you can use the variables to access their value and use them in the code. We can perform the array structuring using the destructuring assignment. The destructuring assignment is a basically a JavaScript expression. Syntax The syntax of array destructuring assignment in JavaScript is as follows – const array = [10, 20]; const [var1, var2] = array; In the above syntax, the “array” is the original array containing 10 and 20. When you unpack the array elements, var1 contains the 10, and var2 contains the 20. Example: Basic Array Destructuring In the example below, the arr array contains 3 numeric values. After that, we used the array destructuring to unpack array elements and store them in the num1, num2, and num3 variables. <html> <body> <div id = “output1”> </div> <div id = “output2”> </div> <div id = “output3”> </div> <script> const arr = [100, 500, 1000]; const [num1, num2, num3] = arr; document.getElementById(“output1”).innerHTML = “num1: ” + num1; document.getElementById(“output2”).innerHTML = “num2: ” + num2; document.getElementById(“output3”).innerHTML = “num3: ” + num3; </script> </body> </html> Output num1: 100 num2: 500 num3: 1000 Example: Unpacking with initial N elements of the array While destructuring the array, if the left operand has fewer variables than array elements, first, N array elements get stored in the variables. The array contains 6 elements in the below code, but 2 variables exist on the left side. So, the first 2 elements of the array will be stored in the variables, and others will be ignored. <html> <body> <div id = “output1”> </div> <div id = “output2”> </div> <script> const arr = [1, 2, 3, 4, 5, 6]; const [num1, num2] = arr; document.getElementById(“output1”).innerHTML = “num1: ” + num1; document.getElementById(“output2”).innerHTML = “num2: ” + num2; </script> </body> </html> Output num1: 1 num2: 2 Skipping Array Elements While Destructuring an Array While JavaScript array destructuring, you can skip a particular array element without assigning it to a variable. Example In the below code, the arr array contains 6 numbers. We have skipped the 2nd and 4th elements. In the output, num3 is 3, and num5 is 5, as the 2nd and 4th elements are skipped. <html> <body> <div id = “output”> </div> <script> const arr = [1, 2, 3, 4, 5, 6]; const [num1, , num3, , num5] = arr; document.getElementById(“output”).innerHTML = “num1: ” + num1 + “<br>” + “num3: ” + num3 + “<br>” + “num5: ” + num5; </script> </body> </html> Output num1: 1 num3: 3 num5: 5 Array Destructuring and Rest Operator If the left operand of the destructuring assignment operator contains fewer variables than the array elements, JavaScript ignores the last remaining array elements. To solve the problem, you can use the rest operator. You can write the last variable with a rest operator in the left operand. So, the remaining array elements will be stored in the operand of the rest operator in the array format. Example In the code below, the array”s first and second elements are stored in the num1 and num2 variables. We used the rest operator with the num3 variable. So, the remaining array elements will be stored in num3 in the array format. <html> <body> <div id = “demo”> </div> <script> const arr = [1, 2, 3, 4, 5, 6]; const [num1, num2, …nums] = arr; document.getElementById(“demo”).innerHTML = “num1: ” + num1 + “<br>” + “num2: ” + num2 + “<br>” + “nums: ” + nums; </script> </body> </html> Output num1: 1 num2: 2 nums: 3,4,5,6 If you use the rest operator in the middle, all remaining array elements will be stored in the operand of the rest operator, and variables used after the rest operator will be ignored. Array Destructuring and Default Values Sometimes, an array can contain undefined values or fewer elements than the variables. In such cases, while destructuring JavaScript arrays, the variables can be initialized with the default values. Example In the below code, num1, num2, and num3 contain 10, 20, and 30 default values, respectively. The array contains only a single element. So, when we unpack the array, the num1 variable will contain the array element, num2 and num3 will contain the default values. <html> <body> <div id = “demo”> </div> <script> const arr = [1]; const [num1 = 10, num2 = 20, num3 = 30] = arr; document.getElementById(“demo”).innerHTML = “num1: ” + num1 + “<br>” + “num2: ” + num2 + “<br>” + “num3: ” + num3; </script> </body> </html> Output num1: 1 num2: 20 num3: 30 Swapping Variables Using Array Destructuring You can also swap two variables’ values using the JavaScript Array Destructuring. Example In the below code, variables a and b are initialized with 50 and 100, respectively. After that, we added variables a and b in a different order in the left and right operands. In the output, you can see the swapped values of the a and b. <html> <body> <div id = “output”> </div> <script> let a = 50, b = 100; document.getElementById(“output”).innerHTML = “Before Swapping: a = ” + a + “, b = ” + b + “<br>”; [b, a] = [a, b] document.getElementById(“output”).innerHTML += “After Swapping: a = ” + a + “, b = ” + b; </script> </body> </html> Output Before Swapping: a = 50, b = 100 After Swapping: a = 100, b = 50 Destructuring the Returned Array from the Function In real-time development, dynamic arrays are returned from the function. So, you can also destructure the returned array from the function. Example In the example below, getNums() function returns the array of numbers. We execute the getNums() function and unpack array elements in the individual variables. <html> <body> <div id = “output”> </div> <script> function getNums() { return [99, 80, 70]; } const [num1, num2, num3] = getNums(); document.getElementById(“output”).innerHTML = “num1: ” + num1 + “<br>” + “num2:
JavaScript – RegExp
Regular Expressions and RegExp Object ”; Previous Next 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 i Perform case-insensitive matching. 2 m Specifies 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 g Performs 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 ^p It matches any string with p at the beginning of it. 9 ?!p It 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.p It 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 Alphanumeric Itself 2 The NUL character (u0000) 3 t Tab (u0009 4 n Newline (u000A) 5 v Vertical tab (u000B) 6 f Form feed (u000C) 7 r Carriage return (u000D) 8 xnn The Latin character specified by the hexadecimal number nn; for example, x0A is the same as n 9 uxxxx The Unicode character specified by the hexadecimal number xxxx; for example, u0009 is the same as t 10 cX The 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 s a whitespace character (space, tab, newline) 3 S non-whitespace character 4 d a digit (0-9) 5 D a non-digit 6 w a word character (a-z, A-Z, 0-9, _) 7 W a 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
JavaScript – Object Accessors ”; Previous Next The object accessor properties in JavaScript are methods that get or set the value of an object. They are defined using the get and set keywords. Accessor properties are a powerful way to control how your objects are accessed and modified. The JavaScript object can have two kinds of properties. Data properties Accessor properties The below property is called the data properties. const obj = { key: “value”, // Data property } Object Accessor Properties In JavaScript, you can use the getters to get the object properties and setters to set the object properties. There are two keywords to define accessor properties. get − The get keyword is used to define a method to get the object property value. set − The set keyword is used to define a method to update the object property value. JavaScript Getters The getters are used to access the object properties. To define a method as getter, we use get keyword followed by method name. Follow the syntax below to define the getter. get methodName() { // Method body } obj.methodName; In the above syntax, we have defined the getters using the ”get” keyword followed by the method name. You can use the method name as an object property to get its returned value. You don”t need to write the pair of parenthesis followed by the method name to execute the getters. You can access it like the object property. Example In the example below, in the wall object, we have defined the getColor() getters. The getColor() returns the value of the color property. After that, we use the getColor() method to access the color property value of the object. <html> <body> <p id = “output”>The color of the wall is : </p> <script> const wall = { color: “brown”, get getColor() { return this.color; } } document.getElementById(“output”).innerHTML += wall.getColor; </script> </body> </html> Output The color of the wall is : brown JavaScript Setters The setters are used to update the JavaScript object properties. To define a method as setter, we use set keyword followed by method name You can follow the syntax below to define setters in the JavaScript object. set methodName(param) { // Setter method return this.color = color; } wall.methodName = “Red”; In the above syntax, the ”set” keyword is used to define the setter method. The method_name can be any valid identifier. The setter method always takes a single parameter. If you don”t pass a parameter or multiple parameters, it will give you an error. You can assign value to the setter method as you assign value to the property. Example In the example below, we have defined the setter method to set the value of the color property of the wall object. We set the ”red” value to the color property of the object using the ”setColor” setter method. <html> <body> <p id = “output”> </p> <script> const wall = { color: “brown”, set setColor(color) { return this.color = color; } } document.getElementById(“output”).innerHTML += “The color of the wall before update is : ” + wall.color + “<br>”; //updating the color of wall wall.setColor = “Red”; document.getElementById(“output”).innerHTML += “The color of the wall after update is : ” + wall.color; </script> </body> </html> Output The color of the wall before update is : brown The color of the wall after update is : Red JavaScript Object Methods vs. Getters/Setters In JavaScript, whatever you can do using the getters and setters, you can also do by defining the specific object method. The difference is that getters and setters provide simpler syntax. Let”s understand it with the help of some examples. Example In the example below, we have defined the getColor() getters method and colorMethod() object method in the wall object. Both method returns the color value. You can observe that defining and accessing getters is more straightforward than defining and accessing the object method. <html> <body> <p id = “output”> </p> <script> const wall = { color: “brown”, get getColor() { return this.color; }, colorMethod: function () { return this.color; } } document.getElementById(“output”).innerHTML += “Getting the color using the getters : ” + wall.getColor + “<br>”; document.getElementById(“output”).innerHTML += “Getting the color using the object method : ” + wall.colorMethod(); </script> </body> </html> Output Getting the color using the getters : brown Getting the color using the object method : brown Data Quality and Security The getter and setter methods can provide better data quality. Also, they are used for encapsulation to secure the object data. Let”s understand how getter and setter improve data quality and provide security via the example below. Example In the example below, the getColor() is a getter method, returning the value of the color property after converting it to the uppercase. Also, it hides the color property from users, as you can access its value using the getColor() method. <html> <body> <p id = “output”> </p> <script> const wall = { color: “Brown”, get getColor() { return this.color.toUpperCase(); } } document.getElementById(“output”).innerHTML += “Getting the color using the getters : ” + wall.getColor; </script> </body> </html> Output Getting the color using the getters : BROWN Defining getters/setters using the Object.defineProperty() You can also use the Object.defineProperty() method to add getters or setters into the object. Object.defineProperty(object, “methodName”, { keyword: function () { // Method body }, }) Using the above syntax, you can define the getter or setter same as methodName. Parameters object − It is an object where you need to add getters or setters. methodName − It is the name of the method for getters or setters. keyword − It can be ”get” or ”set” according to you want to define the getter or setter method. Example In the example below, we have added the getSize and setSize getter and setter to the object using the object.defineProperty() method. After that, we use the getSize and setSize to get and set the size, respectively. <html> <body> <p id = “demo”> </p> <script> const output =
JavaScript – this Keyword
JavaScript – this Keyword ”; Previous Next What is ”this” keyword? In JavaScript, the ”this” keyword contains the reference to the object. It represents the context of the function or current code. It is used to access the properties and methods of the current object. When this keyword is used inside a function, the this will refer to the object that the function is called with. In JavaScript, functions are also objects. So, you can use the ”this” keyword with functions also. Which object does the ”this” refer to? The object referred by the ”this” keyword depends on how you have used the ”this” keyword. For example, The ”this” keyword refers to the window object in the global scope. When you use the ”this” keyword inside the function, it also represents the ”window” object. The ”this” keyword refers to an undefined in the strict mode in the function. The ”this” keyword refers to the object when you use it in the object method. In the event handler, the ”this” keyword refers to the element on which the event is executed. The ”this” keyword in methods like call(), apply(), and bind() can refer to different objects. Syntax Follow the syntax below to use the ”this” keyword in JavaScript &minus this.property OR this.method(); You can access the properties and execute the object”s methods using the ”this” keyword. JavaScript ”this” in the Global Scope When you use the ”this” keyword in the global scope, it represents the global (window) object. You can access the global variables using the ”this” keyword in the global scope. Example In the below code, we have defined the ”num” variable and printNum() function in the global scope. After that, we used the ”this” keyword to access the global variable and functions. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(”demo”); var num = 10; function printNum() { output.innerHTML += “Inside the function: ” + num + “<br>”; } this.printNum(); output.innerHTML += “Outside the function: ” + this.num + “<br>”; </script> </body> </html> Output Inside the function: 10 Outside the function: 10 JavaScript ”this” in a Function When you use the ”this” keyword in the function, it represents the global scope or ”window” object. Example In the below code, we use the ”this” keyword inside the function. You can observe that we access the global variables using the ”this” keyword inside the function. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(”demo”); var message = “Hello World!”; function printMessage() { var message = “Hi! How are you?”; output.innerHTML = “The messsage is: ” + this.message; } printMessage(); </script> </body> </html> Output The messsage is: Hello World! ”this” in a Function in Strict Mode When you use the ”this” keyword inside the function in the strict mode, it doesn”t refer to any object. The value of the ”this” keyword becomes undefined. Example In the below code, we use the ”this” keyword inside the function in the strict mode. It prints undefined. <html> <body> <div id = “demo”> </div> <script> let output = document.getElementById(”demo”); var message = “Hello World!”; function test() { “use strict”; output.innerHTML = “The value of this in the strict mode is: ” + this; } test(); </script> </body> </html> Output The value of this in the strict mode is: undefined ”this” in a Constructor Function When you use the function as a constructor function to create an object, the ”this” keyword refers to the object. Example We have defined the Animal() constructor function in the code below. We used the ”this” keyword inside the constructor function to initialize the properties of the object. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(”demo”); function Animal() { this.name = ”Lion”; this.age = 3; this.color = ”Brown”; } const newAnimal = new Animal(); output.innerHTML = “Animal Name: ” + newAnimal.name + “<br>”; output.innerHTML += “Animal Age: ” + newAnimal.age + “<br>”; output.innerHTML += “Animal Color: ” + newAnimal.color; </script> </body> </html> Output Animal Name: Lion Animal Age: 3 Animal Color: Brown ”this” in an Arrow Function When you use the ”this” keyword in the arrow function, it refers to the scope of its parent object. For example, when you define the arrow function inside the object method and use the ”this” keyword inside that, it presents the object. The ”this” keyword refers to the global object if you define the arrow function inside another function. Example In the below code, we have defined the arrow function inside the getDetails() method of the object. When we print the value of the ”this” keyword, it prints the object. <html> <body> <div id = “output1″>Value of ”this” inside the getDetails() method: </div> <div id = “output2″>Value of ”this” inside the getInnerDetails() method: </div> <script> const wall = { size: “10”, color: “blue”, getDetails() { document.getElementById(”output1”).innerHTML += JSON.stringify(this); const getInnerDetails = () => { document.getElementById(”output2”).innerHTML += JSON.stringify(this); } getInnerDetails(); } } wall.getDetails(); </script> </body> </html> Output Value of ”this” inside the getDetails() method: {“size”:”10″,”color”:”blue”} Value of ”this” inside the getInnerDetails() method: {“size”:”10″,”color”:”blue”} ”this” in the Object Method When you use the ”this” keyword inside the object method, it represents the object itself. Example In the below code, we have defined the ”fruit; object. The object contains the printFruitDetails() method, and in the method, we used the ”this” keyword to access the properties of the object. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(”demo”); const fruit = { name: “Apple”, color: “red”, printFruitDetails() { output.innerHTML += “Furit Name = ” + this.name + “<br>”; output.innerHTML += “Fruit Color = ” + this.color; } } fruit.printFruitDetails(); </script> </body> </html> Output Furit Name = Apple Fruit Color = red ”this” in a Child Function of an Object Method When you define the function inside the object method and use the ”this” keyword inside the function, it represents the global object rather than an object. Example: In the below code, we have defined the person object. The person object contains the