JavaScript – IndexedDB

JavaScript – IndexedDB ”; Previous Next What is IndexedDB? IndexedDB, or Indexed Database, represents a low-level JavaScript API. Its function involves the storage and retrieval of voluminous structured data – this includes files and blobs. With its capabilities to work with client-side databases: it enables web applications to locally store, query, and modify data on the user”s device. This functionality proves particularly advantageous when constructing web applications that confront significant data volumes; operate without an internet connection, working offline and deliver responsive user experiences through local data caching. Key concepts and features of IndexedDB: Asynchronous API − Relying on event-driven programming, IndexedDB utilizes an asynchronous API to prevent main-thread blocking and enhance user experience. Database − IndexedDB databases, functioning as containers for object stores, facilitate the organization, retrieval and deletion of data. Object Store − An object store akin to a table in a relational database, encapsulates collections of JavaScript objects; it provides support for CRUD operations. Index − Indexes in object stores can enhance the efficiency of data querying, as they are able to improve search and sort performance based on specific fields. Transactions − Transactions in IndexedDB perform all operations, guaranteeing consistency and integrity through their ability to make multiple actions either succeed or fail as a unit. Why use IndexedDB? Web developers, in their search for efficient client-side storage solutions, find IndexedDB indispensable. Its asynchronous nature guarantees a responsive user experience: it thwarts main-thread blocking; moreover, its support for transactions by maintaining data integrity is commendable. IndexedDB is capable of managing significant volumes of structured data locally; this capability significantly enhances offline functionality a reduction on the need for relentless server communication. With its flexible key structure, indexing support for optimized queries, and the ability to upgrade schema; it stands as a robust choice for constructing web applications. These applications often require local storage, offline support and most importantly effective data management. CRUD Operations Let us now see the CRUD operation codes with IndexedDB. Create/Insert Operation To insert a new record into an object store, you utilize the add() method in IndexedDB. This method accepts a JavaScript object or value as its parameter and subsequently incorporates it within the designated object store. However, if there already exists an entry with identical key parameters; this operation will fail, thus rendering it ideal for guaranteeing uniqueness. const request = objectStore.add(data); request.onsuccess = () => { // Handle success event }; request.onerror = () => { // Handle error }; Read (Retrieve) Opeation The get() Method Utilize the get() method: it retrieves a singular record from an object store, this action is contingent upon your possession of knowledge regarding the specific key for your intended entry. The openCursor() Method Initiating an active cursor that iterates through records within an object store, the openCursor() method enhances efficiency and control by allowing for processing each individual entry; this proves useful in traversing all entries present in the said object store. const request = objectStore.openCursor(); request.onsuccess = (event) => { const cursor = event.target.result; if (cursor) { const data = cursor.value; // Process data cursor.continue(); } }; request.onerror = () => { // Handle error }; Update Operation The put() method updates an existing record or adds a new one when the key doesn”t exist. Its versatility renders it suitable for data manipulation, specifically updating and inserting. const request = objectStore.put(data); Delete Operation To remove a specific record from an object store based on its key, one must employ the delete() method; this method offers a direct approach for deleting entries. const request = objectStore.delete(key); Implementation Example All the important methods of the above CRUD operation are implemented in this code. It presents database data as a table, each record accompanied by delete and update buttons. When you click on the create button, it displays an element for form creation on screen; thereby allowing entry of name and email to be inserted into the database. By default, this form remains hidden; it only appears upon button click and subsequently vanishes when its task is complete. The ”prompt()” method populates the details update form, a feature that provides convenience for users as alerts also appear in this same location. Moreover: pertinent alerts serve to signal either successful events or errors to the user. <!DOCTYPE html> <html> <head> <style> body { font-family: Arial, sans-serif; margin: 20px; } h2 { color: #333; } button { padding: 8px; margin: 5px; } #createForm, #updateForm { display: none; border: 1px solid #ddd; padding: 10px; margin-bottom: 10px; } table { border-collapse: collapse; width: 100%; margin-top: 20px; width: auto; } th, td { border: 1px solid #dddddd; text-align: left; padding: 8px; } th { background-color: #f2f2f2; } </style> </head> <body> <h2>IndexedDB CRUD Operations</h2> <button onclick=”showCreateForm()”>Create Data</button> <div id=”createForm” style=”display: none;”> // hidden by default, displayed on create button click <h3>Create Data</h3> <label for=”name”>Name:</label> <input type=”text” id=”name” required><br><br> <label for=”email”>Email:</label> <input type=”email” id=”email” required><br> <button onclick=”createData()”>Save</button> <button onclick=”cancelCreate()”>Cancel</button> </div> <table id=”data-table”> <thead> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th>Actions</th> </tr> </thead> <tbody></tbody> </table> <script> const dbName = “myDatabase”; let db; // Open/create indexedDB named myDatabase with version 11 const request = window.indexedDB.open(dbName, 11); request.onerror = (event) => { alert(“Database error: ” + event.target.errorCode); }; request.onsuccess = (event) => { db = event.target.result; showData(); }; request.onupgradeneeded = (event) => { db = event.target.result; const objectStore = db.createObjectStore(“myObjectStore”, { keyPath: “id”, autoIncrement: true }); objectStore.createIndex(“name”, “name”, { unique: false }); objectStore.createIndex(“email”, “email”, { unique: true }); }; function showData() { //populates the table from the db const transaction = db.transaction([“myObjectStore”], “readonly”); const objectStore = transaction.objectStore(“myObjectStore”); const tableBody = document.querySelector(“#data-table tbody”); tableBody.innerHTML = “”; const request = objectStore.openCursor(); request.onsuccess = (event) => { const cursor = event.target.result; if (cursor) { const row = tableBody.insertRow(); row.insertCell(0).textContent =

JavaScript – Debugging

JavaScript – Debugging ”; Previous Next What is Debugging? Debugging in JavaScript is a process of examining JavaScript code and finding erros and fixing them. Every now and then, developers commit mistakes while coding. This error can be logical, syntax, or runtime errors. An error in a program or a script is referred to as a bug. The process of finding and fixing bugs is called debugging and is a normal part of the development process. This section covers tools and techniques that can help you with debugging tasks. Let”s look at the different methods of debugging. Use a JavaScript Debugger A debugger is an application that places all aspects of script execution under the control of the programmer. Debuggers provide fine-grained control over the state of the script through an interface that allows you to examine and set values as well as control the flow of execution. Once a script has been loaded into a debugger, it can be run one line at a time or instructed to halt at certain breakpoints. Once execution is halted, the programmer can examine the state of the script and its variables in order to determine if something is amiss. You can also watch variables for changes in their values. Nowadays, all modern browser comes with built-in debuggers. You can use the console of the browser to debug the JavaScript code. How to Open Console in the Browser? In this section, you will learn to open the console in different browsers. Open Console in Chrome Press the Below keys. Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J macOs − Cmd + Option + I or Cmd + Option + J OR Step 1 − Open Chrome web browser and open the web page in a new window. Step 2 − Right-click anywhere on the web page. Step 3 − It will pop up menu. Select the last option, which is ”inspect”. Step 4 − It will open a Chrome developer tool. Step 5 − Go to the console tab. Open Console in Firefox Press the Below keys. Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J macOs − Cmd + Option + I or Cmd + Option + J OR Step 1 − Open Firefox web browser and open the web page in a new window. Step 2 − Right-click anywhere on the web page. Step 3 − Select the last option from the popup menu, which is ”inspect(Q)”. Step 4 − It will open a developer tool. Step 5 − You can move from the ”inspector” tab to the ”console” tab. Open Console in Microsoft Edge Press the Below keys. Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J macOs − Cmd + Option + I or Cmd + Option + J OR Step 1 − Open the Microsoft Edge browser. Step 2 − Right-click anywhere on the web page. Step 3 − Click on ”inspect” in the popup menu. Step 4 − You will see the developer tool is opened. Step 5 − Next, you can change the ”Elements” tab to the ”Console” tab in the developer tool. Open Console in Safari Press the Below keys. Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J macOs − Cmd + Option + I or Cmd + Option + J OR Step 1 − Open the Safari web browser. Step 2 − Open the Safari main menu from the top menu bar. Step 3 − Choose ”preferences” in the dropdown menu. Next, choose the ”advanced” option. Step 4 − Check the checkbox named ”Enable Show Develop menu in menu bar” to enable the developer tool. Next, close the preference window. Step 5 − Next, reopen the main menu and select ”Develop’. After that, select the ”Show Error Console’. Open Console in Opera Press the Below keys. Windows/Linux − Ctrl + Shift + I or Ctrl + Shift + J macOs − Cmd + Option + I or Cmd + Option + J OR Step 1 − Open the Opera browser. Step 2 − Open the main menu from the top corner. Step 3 − In the main menu, select the ”Developer’. It will open the sub-menu. Step 4 − In the submenu, select the ”developer tools’. Step 5 − Next, select the ”console’. It will open a console. Using the console.log() method The console.log() method prints the message in the web browser”s console. It can print primitive values, objects, variable values, etc. You can print the variable”s value in the console you want to debug. Syntax Users can follow the syntax below to use the console.log() method. Console.log(val1, val2, …); The console.log() method takes the comma-separated arguments to print in the web browser”s console. Example In the code below, we add the value of the num1 and num2 variables. In the browser, you can see that the sum is 32 rather than 5. So, you are required to debug the code. When you print the type of the num1 and num2 into the console, it shows that the type of the num1 is a string. So, it converts the value of the num2 variable into the string and appends it with the value of the num1. <html> <body> <div id = “output”> </div> <p>Note: To see the resullt in console, please open it before you run

JavaScript – Ajax

JavaScript – Ajax ”; Previous Next Asynchronous JavaScript and XML (Ajax) represents a web development technique: it enables dynamic, interactive communication between server and webpage without necessitating complete page reload. The descriptor “asynchronous” underlines that data exchanges can occur in the background, independent of user experience disruption. Rather than idly awaiting full-page refreshment; Ajax empowers real-time updates on specific sections of a webpage, thus yielding an interface that is more seamless and responsive. How Ajax works? The central role in enabling dynamic updates, without the necessity of a full page reload, belongs to the XMLHttpRequest object within JavaScript”s Ajax functionality. This particular process allows for asynchronous communication between server and web page. The server responds with data, usually in JSON or XML format when receiving a request sent by this object. Processing this data is the task of JavaScript; it updates specific portions of the webpage in real-time. The asynchronous nature which is a critical feature for modern web development ensures these operations occur unobtrusively in background, thereby enhancing interactivity by allowing data to be fetched and sent asynchronously. Here, we will to explore Ajax to get a deeper understanding of it. There are 4 approaches to make Ajax calls or to implement Ajax in JavaScript and they are: XMLHttpRequest (Older Approach) Fetch API (Modern Approach) Axios (Library for HTTP Requests) jQuery Ajax We will be using JSONPlaceholder in all the examples for understanding purposes. JSONPlaceholder is an open-source and simulated REST API provider which lets developers test their prototype applications. It returns fake/dummy data for various resources like users, posts, comments etc. The API endpoints of JSONPlaceholder can be made using HTTP requests and they will be mimicking the nature of real APIs without any need for authentication. Our goal here is to use these APIs/endpoints to under Javascript-Ajax. Using XMLHttpRequest The Native JavaScript approach using XMLHttpRequest represents the oldest method for asynchronous requests. It relies on the XMLHttpRequest object to create and send HTTP requests. This method involves setting up callback functions to handle various states of the request, making it suitable for simpler scenarios. However, it has some limitations compared to more modern approaches. Example <!DOCTYPE html> <html lang=”en”> <body> <p>Native XMLHttpRequest Example</p> <button onclick=”nativeAjax()”>Make Request</button> <pre id=”result”></pre> <script> function nativeAjax() { var xhr = new XMLHttpRequest(); xhr.open(”GET”, ”https://jsonplaceholder.typicode.com/users/2”, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { var responseData = JSON.stringify(JSON.parse(xhr.responseText), null, 2); document.getElementById(”result”).innerText = ”Native XMLHttpRequest:n” + responseData; } }; xhr.send(); } </script> </body> </html> Using Fetch API Presenting a modern alternative to XMLHttpRequest, the Fetch API offers a more straightforward and powerful syntax; it returns Promises thus enhancing the intuitive handling of asynchronous operations. Supporting an extensive array of HTTP methods and headers: this provides developers with a cleaner, concise method for making asynchronous requests. Contemporary JavaScript applications often prefer it for its clarity and ease of use. Example <!DOCTYPE html> <html> <body> <h1>Fetch API Example</h1> <button onclick=”fetchApi()”>Make Request</button> <pre id=”result”></pre> <script> function fetchApi() { fetch(”https://jsonplaceholder.typicode.com/users/3”) .then(response => { if (!response.ok) { throw new Error(”Network response was not ok”); } return response.json(); }) .then(data => { var formattedData = JSON.stringify(data, null, 2); document.getElementById(”result”).innerText = ”Fetch API:n” + formattedData; }) .catch(error => { document.getElementById(”result”).innerText = ”Fetch API Error: ” + error.message; }); } </script> </body> </html> Using Axios Designed for making HTTP requests, Axios emerges as a popular JavaScript library. Its popularity is largely due to its clean and concise syntax: built on Promises; furthermore, it boasts automatic JSON data transformation support features that set it apart from other libraries in the field. Offering more than just basic functionality, Axios presents advanced features such as request and response interceptors, a robust selection for managing AJAX operations within the context of modern web development environment. Example <!DOCTYPE html> <html> <head> <script src=”https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js”></script> </head> <body> <h1>Axios Example</h1> <button onclick=”axiosExample()”>Make Request</button> <pre id=”result3″></pre> <script> function axiosExample() { axios.get(”https://jsonplaceholder.typicode.com/users/5”) .then(response => { var formattedData = JSON.stringify(response.data, null, 2); document.getElementById(”result3”).innerText = ”Axios:n” + formattedData; }) .catch(error => { document.getElementById(”result3”).innerText = ”Axios Error: ” + error.message; }); } </script> </body> </html> Using Ajax jQuery The $.ajax method in jQuery simplifies the AJAX request process: a popular approach previously; however, its usage has waned alongside modern JavaScript”s ascent. Offering an interface that is both consistent and cross-browser compatible, jQuery Ajax remains suitable for projects already using or needing specific features of jQuery due to these advantages it presents. However, for new projects, modern alternatives may be preferred. Example <!DOCTYPE html> <html> <head> <script src=”https://code.jquery.com/jquery-3.6.4.min.js”></script> </head> <body> <h1>jQuery Ajax Example</h1> <button onclick=”jqueryAjax()”>Make Request</button> <pre id=”result4″></pre> <script> function jqueryAjax() { $.ajax({ url: ”https://jsonplaceholder.typicode.com/users/7”, method: ”GET”, dataType: ”json”, success: function (data) { var formattedData = JSON.stringify(data, null, 2); document.getElementById(”result4”).innerText = ”jQuery Ajax:n” + formattedData; }, error: function (xhr, status, error) { document.getElementById(”result4”).innerText = ”jQuery Ajax Error: ” + error; } }); } </script> </body> </html> Ajax Use Cases In real-world scenarios, developers commonly employ Ajax to create web applications that are both responsive and interactive. A pertinent example: a social media platform; here, users have the ability – thanks to Ajax, to add or load new comments in the background without needing an entire page refresh. Dynamic updating ensures a user experience that is smooth and uninterrupted, permitting individuals to engage with content and one another seamlessly. This process yields a platform more responsive and engaging; it amplifies user interaction thus enhancing satisfaction. Prominent companies utilizing Ajax for enhanced user experiences include Google (Gmail, Maps), Facebook, Twitter, Amazon, Netflix, GitHub, LinkedIn, YouTube, Microsoft Office Online, and Uber. Ajax is employed for real-time updates, dynamic content loading, and seamless interactions on their respective platforms. Print Page Previous Next Advertisements ”;

JavaScript – Style Guide

JavaScript – Style Guide ”; Previous Next A JavaScript style guide is a set of general rules that regulate how to write JavaScript code. These rules can include − which quotes to use, how many spaces to indent, the maximum line length, using single-line comments, marked with //, etc. When any company starts developing a real-time JavaScript project, 100”s of developers work on that. If each developer follows a different style of writing code, it becomes very hard to manage complex code. So, it is important to follow the same code style throughout the project. Here, we have covered some essential coding conventions to follow while developing the project. Code Indentation You should always intend your code with fixed spaces (either 2, 3 or 4 spaces) according to the coding convention of your project. Also, the code should not contain trailing white spaces. Example In the code below, we have used the three spaces indentation in the function. <html> <body> <h2> Intendation Conventions </h2> <div id = “output”> </div> <script> const output = document.getElementById(”output”); function func() { output.innerHTML = “Function executed!”; return 10; } func(); </script> </body> </html> Comments You should always use the line comments rather than the block comments, and line comments should start with the left part of the code. Example In the code below, we used the ‘//’ line comments to comment the code. <html> <body> <h2> Comment Conventions </h2> <div id=”output”> </div> <script> const output = document.getElementById(”output”); output.innerHTML = “Hello World!”; // var a = 10; // var b = 20; </script> </body> </html> Variable Declaration Always declare the variable at the top of its scope. If a variable is a global variable, declare it at the top of the file. Similarly, if the variable is in th block or function, declare it at the top of the block or function. Furthermore, variable names must start with the letter. Example In the code below, we have declared the variable at the top of the code, and the name of each variable starts with a letter. <html> <body> <h2> Variable Conventions </h2> <div id=”output”> </div> <script> var a = 10; var b = 20; document.getElementById(”output”).innerHTML = “The sum of 10 and 20 is: ” + (a + b); </script> </body> </html> Identifier Names in camelCase In JavaScript, always use the camelCase convention to define the identifier. In the camelCase convention, the first letter of the identifier should be lowercase, and the first letter of the 2nd word should be in the uppercase. Here, identifiers include function names, variable names, object names, class names, etc. Example In the code below, ”greetMessage” and ”executeGreet” both identifiers are in the camelCase. <html> <body> <h2> camelCase Conventions </h2> <div id=”output”> </div> <script> var greetMessage = “Hello Developers!”; let output = document.getElementById(”output”); // Function name with camelCase function executeGreet() { output.innerHTML = greetMessage; } executeGreet(); </script> </body> </html> Spaces, and Brackets In JavaScript, we should include white space before and after each operator like ‘+’, ”typeof’, etc. Furthermore, it is also vital to include white space around brackets. Example In the code below, we added proper space after the ”if” condition. Also, we added white space before and after ‘+=’ operator. <html> <body> <h2> Space and all brackets Conventions </h2> <div id=”output”> </div> <script> let output = document.getElementById(”output”); if (9 > 10) { output.innerHTML += “9 is greater than 10”; } else { output.innerHTML += “9 is not greater than 10″; } </script> </body> </html> Object Rules In JavaScript, we use the ‘=’ assignment operator and open bracket ‘{‘ after the object identifier. Next, we write the object properties (key-value pairs separated by semicolon), and we write each property in the new line and separate them with a comma (,). Also, we don”t put a comma after the last object property. At the end, we add a semicolon (;) after adding a closing bracket. Example In the code below, we have defined the object according to the object guidelines. Also, we have shown objects on the web page using the JSON.stringify() method. <html> <body> <h2> Object Conventions </h2> <div id=”output”> </div> <script> const obj = { prop1: ”value1”, prop2: ”value2”, prop3: ”value3” }; document.getElementById(“output”).innerHTML = JSON.stringify(obj, null, 2); </script> </body> </html> Statement Rules There are 3 types of statements in JavaScript. Simple one-line statement Compound statement Multi-line statement The simple one-line statement should always end with a semicolon. For the compound statement, we put white space and an open bracket after a statement in the same line. Next, we start adding the statement body from the next line, and in the last line, we add a closing bracket. We don”t put a semicolon after the closing bracket. If the statement is too long and can”t be written in a single line, we can add a line break after the operator. Example In the code below, we have defined single one-line, compound, and multi-line statements. <html> <body> <h2> Statement Guidelines Conventions </h2> <div id=”output”> </div> <script> const output = document.getElementById(”output”); // single line statement const arr = [“one”, “two”, “Three”]; // Compound statement for (let i = 0; i < arr.length; i++) { output.innerHTML += arr[i] + “<br>”; } // Multi-line statement if (10 > 9 && 10 > 5 && 10 > 6) { output.innerHTML += “10 is greater than 9 and 10 is greater than 5 <br>”; } </script> </body> </html> Line Length It is always hard to read long lines of code. So, we should put a maximum 80 characters in a single line. Example In the code below, we have added half a string in a new line as it contains more

JavaScript – Canvas

JavaScript – Canvas ”; Previous Next Handling Canvas with JavaScript The HTML <canvas> element can be used to create and draw graphics on the web page. It can draw various graphics or shapes, like lines, circles, etc., on the web page and animate them. You can define <canvas> element in HTML, and after that, you need to use JavaScript to draw graphics on the web page. Let”s look at the syntaxes to define a canvas element in HTML and manipulate with JavaScript. Syntax Use the following syntax to create an HTML canvas element. <canvas id=”myCanvas” width=”480″ height=”320″> Your browser does not support the HTML canvas tag. </canvas> In the above syntax, we have defined the HTML <canvas> element with id as ”myCanvas”. The message written in between <canvas> tags will be displayed when the browser doesn”t support the <canvas> element. We access the canvas element using the getElementById() method of document object. Look at below syntax − var canvas = document.getElementById(”canvas_id”); var ctx = canvas.getContext(”2d”); In JavaScript, we can use the getContext(”2d”) method to get the context of the 2D canvas. Next, we can use various methods to draw a shape and fill in the color by taking the ”ctx” variable as a reference. Examples Example: Drawing a rectangle In the code below, we have added the <canvas> element in HTML. In JavaScript, we have used the getContext(”2d”) method to access the context of the canvas. After that, we used the fillstyle() method to color the element in the canvas. The fillRect() method is used to draw a rectangle. It takes the coordinates of 4 corners in the canvas. <html> <body> <h2> JavaScript – Canvas </h2> <p> Drawing Rectangle on Canvas using JavaScript</p> <canvas id = “myCanvas” width = “600” height = “300” style = “border:1px solid #000000;”> Your browser does not support the HTML canvas tag. </canvas> <script> var canvas = document.getElementById(“myCanvas”); // Getting the 2D context of the canvas var ctx = canvas.getContext(“2d”); // Drawing rectangle using canvas ctx.fillStyle = “#FF0000”; ctx.fillRect(50,30, 470, 240); </script> </body> </html> Example: Drawing a circle In the code below, we used the arc() method to draw a circle. It takes the coordinates for the circle position as the first 2 parameters and the radius of the circle as a third parameter. <html> <body> <h2> JavaScript – Canvas </h2> <p> Drawing circle on Canvas using JavaScript</p> <canvas id = “myCanvas” width = “600” height = “300” style = “border:1px solid #000000;”> Your browser does not support the HTML canvas tag. </canvas> <script> var c = document.getElementById(“myCanvas”); // Getting the 2D context of the canvas var ctx = c.getContext(“2d”); // Drawing circle using canvas ctx.beginPath(); ctx.arc(300, 150, 100, 0, 2 * Math.PI); ctx.stroke(); ctx.fillStyle = “green”; ctx.fill(); </script> </body> </html> Example: Drawing a lines In the code below, we have drawn the lines using the moveTo() and lineTo() methods. The moveTo() method takes the starting point of the line as a parameter, and the lineTo() method takes the ending point of the line as a parameter. <html> <body> <h2> JavaScript – Canvas </h2> <p> Drawing lines on Canvas using JavaScript</p> <canvas id = “myCanvas” width = “600” height = “300” style = “border:1px solid #000000;”> Your browser does not support the HTML canvas tag. </canvas> <script> var canvas = document.getElementById(“myCanvas”); // Getting the 2D context of the canvas var ctx = canvas.getContext(“2d”); // Drawing lines using canvas ctx.moveTo(0, 0); ctx.lineTo(300, 200); ctx.stroke(); ctx.moveTo(300, 200); ctx.lineTo(400, 0); ctx.stroke(); </script> </body> </html> Example: Drawing a Linear gradient <html> <body> <h2> JavaScript – Canvas </h2> <p> Drawing linear gradient on Canvas using JavaScript</p> <canvas id = “myCanvas” width = “600” height = “300” style = “border:1px solid #000000;”> Your browser does not support the HTML canvas tag. </canvas> <script> var canvas = document.getElementById(“myCanvas”); // Getting the 2D context of the canvas var ctx = canvas.getContext(“2d”); // Drawing a linear gradient ctx.beginPath(); var grd = ctx.createLinearGradient(0, 0, 440, 0); grd.addColorStop(0, “yellow”); grd.addColorStop(1, “white”); ctx.fillStyle = grd; ctx.fillRect(10, 10, 550, 240); ctx.fill(); ctx.closePath(); </script> </body> </html> Example: Text Rendering In the below example, we have rendered a text message “Hello” on the canvas. For this, we have used fillText() method. The fillText() method in HTML Canvas draws a text string on a canvas element. <html> <body> <h2> JavaScript – Canvas </h2> <p> Rendering text on Canvas using JavaScript</p> <canvas id = “myCanvas” width = “600” height = “200” style = “border:1px solid #000000;”> Your browser does not support the HTML canvas tag. </canvas> <script> const canvas = document.getElementById(”myCanvas”); // Getting the 2D context of the canvas const ctx = canvas.getContext(”2d”); ctx.font = ”30px Arial”; ctx.fillStyle = ”red”; ctx.fillText(”Hello, Canvas!”, 150, 100); </script> </body> </html> We have learned to use <canvas> elements in HTML and draw graphics by accessing elements using JavaScript. We can draw various shapes and add colors to shapes. Print Page Previous Next Advertisements ”;

JavaScript – Operator Precedence

JavaScript – Operator Precedence ”; Previous Next In JavaScript, operator precedence ensures the priority of the operators to be executed when a single expression contains multiple operators. So, whatever expressions have higher priority, the compiler executes it first over other operators and then executes the operators with the lower precedence. Whenever you write any JavaScript expression with only 1 or 2 operators, you can easily understand the output of the expression. But when the expression contains multiple operators, you should know the concept of operator precedence to evaluate the expression correctly. The best example of operator precedence is that in traditional mathematics, the multiplication operator has higher precedence over the addition or subtraction operator. So, if any mathematical expression contains the multiplication and addition of both operators, you need to perform the multiplication first. Associativity The term associativity refers to the direction compiler should follow while evaluating the expression. In many situations, operators have the same precedence. In such cases, ambiguity occurs that which operation the compiler should perform first. So, the compiler takes the help of associativity. It can be from left to right or right to left. For example, we need to execute the below expression. let res = 50/5*2; Considering the above expression as (50/5) * 2 gives 20 as an output. Evaluating the expression like 50/ (5*2) gives the 5 as a resultant value. To resolve the above ambiguity, the compiler uses the associativity rule. The associativity for the division and multiplication operator is from left to right. So, it evaluates the expression as (50 / 5) * 2. The assignment operator has right-to-left associativity. Consider the below assignment expression. P = q = 90; In the above expression, 90 is assigned to the q, and the value of the q variable is assigned to the p. In short, the JavaScript compiler evaluates the expression based on the operator precedence, and when multiple operators have the same precedence, it uses the associativity rule. Operator Precedence Table The below table contains the operator, its description, associativity direction, and a short example. Operator Precedence Operator Description Associativity Example 1 () Grouping L -> R (expression) 2 . Member of object L -> R Object_name.property 2 () Function call L -> R Demo() 2 new To create objects R -> L New test() 2 [] Member of object L -> R Object[“property”] 3 — Postfix decrement – p–; 3 ++ Postfix increment – p++ 4 — Prefix decrement R -> L –p; 4 ++ Prefix increment R -> L ++p; 4 typeof To get the variable type R -> L typeof a; 4 ! Logical not R -> L !a; 4 ~ Bitwise not R -> L ~p 4 – Unary minus R -> L -p 4 + Unary plus R -> L +p 4 delete To delete object property R -> L Delete arr[0] 4 void Evaluates void R -> L Void(1) 5 ** Exponentiation operator R -> L p ** q 6 * Multiplication L -> R p * q 6 / Division L -> R p / q 6 % modulo L -> R p % q 7 + Addition or plus operator L -> R p + q 7 – Subtraction operator L -> R p – q 8 << Left shift L -> R p << 2 8 >> Signed right shift L -> R p >> 2 8 >>> Unsigned right shift L -> R p >>> 2 9 in Property in object L -> R x in y 9 instanceof Instance of object L -> R p instanceof Object 9 < Less than L -> R p < q 9 <= Less than or equal to L -> R p <= q 9 > Greater than L -> R p > q 9 >= Greater than or equal to L -> R p >= q 10 == Equality L -> R p == q 10 != Inequality L -> R p != q 10 === Strict equality L -> R p === q 10 !== Strict inequality L -> R p !== q 11 & Bitwise AND L -> R p & q 12 ^ Bitwise XOR L -> R p ^ q 13 | Bitwise OR L -> R p | q 14 && Logical AND L -> R p && q 15 || Logical OR L -> R p || q 16 ?? Nullish Coalescing R -> L p ?? q 17 = Assignment R -> L p = q 17 : Colon assignment R -> L p : q 17 += Addition assignment R -> L p += q 17 -= Subtraction assignment R -> L p -= q 17 *= Multiplication assignment R -> L p *= q 17 /= Division assignment R -> L p /= q 17 %= Modulo assignment R -> L p %= q 17 **= Exponentiation assignment R -> L p **= q 17 <<= Left shift assignement R -> L p <<= q 17 >>= Right shift assignment R -> L p >>= q 17 >>>= Unsigned right shift assignment R -> L p >>>= q 17 &= Bitwise AND assignment R -> L p &= q 17 ^= Bitwise XOR assignment R -> L p ^= q 17 |= Bitwise OR assignment R -> L p |= q 17 &&= Logical AND assignment R -> L p &&= q 17 ||= Logical OR assignement R -> L p ||= q 17 => Arrow operator – (a, b )=> { // function code} 17 … Spread operator – [… arr] 18 yield Pause / Resume R -> L yield p; 19 , Comma operator L -> R (10, 20, 30) Examples Let”s understand the operator precedence via simple examples. Example In the example below, the first expression contains the division, modulo, and multiplication operators with the same precedence. So, the compiler will use the associativity rule, which is left to right for multiplication, division, and modulo operator. So,

JavaScript – Graphics

JavaScript – Graphics ”; Previous Next In JavaScript, graphics can be created using the Canvas API. However, developers can also use some other libraries, like p5.js, chart.js, pllotly.js, Google charts, etc., to draw various graphics and charts. Here, we will explore some of these libraries and learn about them with help of some examples WebGL WebGL allows developers to create graphics from scratch using the code, and integrate it in the web pages. It operates directly with the HTML <canvas> element, allowing for GPU-accelerated usage of physics and image processing and effects as part of the web page canvas. WebGL allows to development of a wide range of applications from 2D games to complex 3D visualization applications. Also, it is supported by most modern browsers, which makes it a go-to choice for developers to develop graphics. Example In the code below, we have used the <canvas> element to create a canvas and accessed it in the JavaScript using the id. Next, we used the getCContext() method to get the context of the WebGL. If it is not supported by the browser, the getContext() method returns undefined value. In the initiateShader() function, we compile the shader source code into shaders, attach those shaders to a program, and then link the program so it can be used in a WebGL context. The loadShader() function loads and compiles the shader code. In the drawScene() function, we use the useProgram() method by passing the graphics info as a parameter to draw a triangle on the canvas. In the output, you can observe the red triangle on the black canvas. <html> <body> <h2> JavaScript – Graphics (WebGL) </h2> <canvas id=”webgl-canvas” width=”600″ height=”400″></canvas> <div id=”error”> </div> <script> // Get the canvas element and its WebGL context var canvas = document.getElementById(”webgl-canvas”); let errorDiv = document.getElementById(”error”); // Get context of webgl var gl = canvas.getContext(”webgl”); if (!gl) { console.error(”Your browser may not support WebGL.”); } // Vertex shader program var vsSource = ` attribute vec4 aVertexPosition; void main(void) { gl_Position = aVertexPosition; } `; // Fragment shader program var fsSource = ` void main(void) { gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); // Red color } `; function initShaderProgram(gl, vsSource, fsSource) { const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource); const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource); // Create the shader program const shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); // If creating the shader program failed, alert if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { alert(”Unable to initialize the shader program: ” + gl.getProgramInfoLog(shaderProgram)); return null; } return shaderProgram; } function loadShader(gl, type, source) { const shader = gl.createShader(type); // Send the source to the shader object gl.shaderSource(shader, source); // Compile the shader program gl.compileShader(shader); // See if it compiled successfully if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { error.innerHTML = ”An error occurred compiling the shaders: ” + gl.getShaderInfoLog(shader); gl.deleteShader(shader); return null; } return shader; } // Initialize a shader program; this is where all the lighting // for the vertices and subsequently the creation of the // geometry and colors will be established. var shaderProgram = initShaderProgram(gl, vsSource, fsSource); // Collect all the info needed to use the shader program. // Look up which attribute our shader program is using // for aVertexPosition and look up uniform locations. var programInfo = { program: shaderProgram, attribLocations: { vertexPosition: gl.getAttribLocation(shaderProgram, ”aVertexPosition”), }, }; // Vertices of the triangle var positions = [ 0.0, 1.0, // Vertex 1 (X, Y) -1.0, -1.0, // Vertex 2 (X, Y) 1.0, -1.0, // Vertex 3 (X, Y) ]; var positionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW); // Draw the scene function drawScene(gl, programInfo, buffers) { gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque gl.clear(gl.COLOR_BUFFER_BIT); gl.useProgram(programInfo.program); // Tell WebGL how to pull out the positions from the position // buffer into the vertexPosition attribute. { const numComponents = 2; // pull out 2 values per iteration const type = gl.FLOAT; // the data in the buffer is 32bit floats const normalize = false; // don”t normalize const stride = 0; // how many bytes to get from one set to the next const offset = 0; // how many bytes inside the buffer to start from gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.vertexAttribPointer( programInfo.attribLocations.vertexPosition, numComponents, type, normalize, stride, offset); gl.enableVertexAttribArray( programInfo.attribLocations.vertexPosition); } // Draw the triangle. gl.drawArrays(gl.TRIANGLES, 0, 3); } drawScene(gl, programInfo, positionBuffer); </script> </body> </html> P5.js P5.js is also a very popular graphics library used to create various shapes by writing the code. It also allows us to animate the shapes and make them visually more appealing. However, it is not limited to shape but it also allows to interact with audio, video, etc. Let’s understand the usage of P5.js with the example below. Example In the code below, the program starts with two main functions: setup() and draw(). The setup() function is run once when the program starts, and it”s used for initial setup tasks. The draw() function continuously executes the lines of code contained inside its block until the program is stopped or noLoop() is called, making it ideal for animations. In the setup() function, we create a canvas and draw the circle on that. In the draw() function, we continuously change the position of the circles by redrawing them. The output of the below code shows the moving circle. <html> <head> <title>p5.js Example</title> <script src=”https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js”></script> </head> <body> <script> // Define variables for the circle”s properties let x, y; // Position let dx = 2; // Speed and direction on x-axis let dy = -2; // Speed and direction on y-axis let radius = 50; // Circle”s radius function setup() { // Create a canvas that fills the window createCanvas(windowWidth, windowHeight); // Initialize circle”s position to center of the canvas x = width / 2; y = height / 2; } function draw()

JavaScript – Atomics Objects

JavaScript – Atomics Objects ”; Previous Next The Atomics object in JavaScript provides a set of static methods for performing atomic operations on SharedArrayBuffer objects. Atomic operations are operations that are guaranteed to be completed in a single step, without being interrupted by other threads. This makes them useful for implementing concurrent data structures and algorithms. The Atomics object in JavaScript, as part of the ECMAScript standard, serves as a crucial tool for managing shared memory in a multi-threaded environment. Let”s understand the basic concept of atomic operations in more detail: Atomics Object The Atomics object is a built-in JavaScript object that provides atomic operations on shared memory. It is designed to be used in a multi-threaded environment, where multiple threads or Web Workers may be concurrently accessing and modifying shared data. The Essence of “Atomic” In the context of the Atomics object, “atomic” signifies a crucial characteristic: it performs operations that are inherently indivisible. When we declare an operation as atomic; we imply its execution occurs continuously and uninterruptedly like a single unit. This quality is indispensable in preventing race conditions; these arise when concurrent operations” outcomes depend on their timing and sequence of execution. Atomic Operations Atomic operations are low-level operations on shared memory that are guaranteed to be executed as a single, uninterruptible unit. These operations include additions, subtractions, bitwise operations, exchanges, and more. The Atomics object provides methods like add, sub, and, or, xor, load, store, exchange, and others, each corresponding to a specific atomic operation. Sr.No. Method & Description 1 Atomics.add() Adds a specified value to the element at the specified index in the typed array. Returns the original value atomically. 2 Atomics.sub() Subtracts a specified value from the element at the specified index in the typed array. Returns the original value atomically. 3 Atomics.and() Performs an atomic bitwise AND operation on the element at the specified index in the typed array with the given value. Returns the original value atomically. 4 Atomics.or() Performs an atomic bitwise OR operation on the element at the specified index in the typed array with the given value. Returns the original value atomically. 5 Atomics.xor() Performs an atomic bitwise XOR operation on the element at the specified index in the typed array with the given value. Returns the original value atomically. 6 Atomics.load() Retrieves the value at the specified index in the typed array atomically. 7 Atomics.store() Stores the given value at the specified index in the typed array atomically. 8 Atomics.exchange() Swaps the value at the specified index in the typed array with a specified value. Returns the original value atomically. 9 Atomics. compareExchange() Compares the value at the specified index in the typed array with a provided expected value, and if they match, updates the value with a new value. Returns the original value atomically. 10 Atomics.wait() Atomically waits for a value at the specified index in the typed array to be a specific value and then returns. Allows for efficient coordination between threads. 11 Atomics.notify() Atomically notifies the wait queue associated with the specified index in the typed array. Examples Example 1: Basic Usage of Atomics Operations In this example, the Atomics object is demonstrated for its fundamental atomic operations on shared memory. These operations include addition, subtraction, bitwise AND, OR, XOR, loading, storing, exchanging, and compare-exchanging values. Each operation ensures the indivisibility of the executed unit, crucial for preventing race conditions in a multi-threaded environment. Atomics.add() // Shared memory setup const sharedBuffer = new SharedArrayBuffer(4); const sharedArray = new Int32Array(sharedBuffer); // Atomics.add() const originalAddValue = Atomics.add(sharedArray, 0, 10); console.log(`Atomics.add: Original value: ${originalAddValue}, New value: ${sharedArray[0]}`); Output Atomics.add: Original value: 0, New value: 10 Atomics.add() // Shared memory setup const sharedBuffer = new SharedArrayBuffer(4); const sharedArray = new Int32Array(sharedBuffer); // Atomics.sub() const originalSubValue = Atomics.sub(sharedArray, 0, 5); console.log(`Atomics.sub: Original value: ${originalSubValue}, New value: ${sharedArray[0]}`); Output Atomics.sub: Original value: 10, New value: 5 Atomics.add() // Shared memory setup const sharedBuffer = new SharedArrayBuffer(4); const sharedArray = new Int32Array(sharedBuffer); // Atomics.and() const originalAndValue = Atomics.and(sharedArray, 0, 0b1010); console.log(`Atomics.and: Original value: ${originalAndValue}, New value: ${sharedArray[0].toString(2)}`); Output Atomics.and: Original value: 5, New value: 0 Atomics.or() // Shared memory setup const sharedBuffer = new SharedArrayBuffer(4); const sharedArray = new Int32Array(sharedBuffer); // Atomics.or() const originalOrValue = Atomics.or(sharedArray, 0, 0b1100); console.log(`Atomics.or: Original value: ${originalOrValue}, New value: ${sharedArray[0].toString(2)}`); Output Atomics.or: Original value: 0, New value: 1100 Atomics.xor() // Shared memory setup const sharedBuffer = new SharedArrayBuffer(4); const sharedArray = new Int32Array(sharedBuffer); // Atomics.xor() const originalXorValue = Atomics.xor(sharedArray, 0, 0b0110); console.log(`Atomics.xor: Original value: ${originalXorValue}, New value: ${sharedArray[0].toString(2)}`); Output Atomics.xor: Original value: 12, New value: 1010 Atomics.load() // Shared memory setup const sharedBuffer = new SharedArrayBuffer(4); const sharedArray = new Int32Array(sharedBuffer); // Atomics.load() const loadedValue = Atomics.load(sharedArray, 0); console.log(`Atomics.load: Loaded value: ${loadedValue}`); Output Atomics.load: Loaded value: 10 Atomics.store() // Shared memory setup const sharedBuffer = new SharedArrayBuffer(4); const sharedArray = new Int32Array(sharedBuffer); // Atomics.store() Atomics.store(sharedArray, 0, 42); console.log(`Atomics.store: New value: ${sharedArray[0]}`); Output Atomics.store: New value: 42 Atomics.exchange() // Shared memory setup const sharedBuffer = new SharedArrayBuffer(4); const sharedArray = new Int32Array(sharedBuffer); // Atomics.exchange() const originalExchangeValue = Atomics.exchange(sharedArray, 0, 99); console.log(`Atomics.exchange: Original value: ${originalExchangeValue}, New value: ${sharedArray[0]}`); Output Atomics.exchange: Original value: 42, New value: 99 Atomics.compareExchange() // Shared memory setup const sharedBuffer = new SharedArrayBuffer(4); const sharedArray = new Int32Array(sharedBuffer); // Atomics.compareExchange() const expectedValue = 99; const newValue

JavaScript – DOM Events

JavaScript – DOM Events ”; Previous Next The DOM events are actions that can be performed on HTML elements. When an event occurs, it triggers a JavaScript function. This function can then be used to change the HTML element or perform other actions. Here are some examples of DOM events: Click − This event occurs when a user clicks on an HTML element. Load − This event occurs when an HTML element is loaded. Change − This event occurs when the value of an HTML element is changed. Submit − This event occurs when an HTML form is submitted. You can use the event handlers or addEventListener() method to listen to and react to the DOM events. The addEventListener() method takes two arguments: the name of the event and the function that you want to be called when the event occurs. The DOM events are also referred as Document Object Model events. It is used to interact with the DOM elements and manipulate the DOM elements from JavaScript when any event occurs. Let”s look at the below examples of DOM events. The onclick Event Type This is the most frequently used event type which occurs when a user clicks the left button of his mouse. You can put your validation, warning etc., against this event type. Example Try the following example. <html> <head> <script> function sayHello() { alert(“Hello World”) } </script> </head> <body> <p>Click the following button and see result</p> <form> <input type = “button” onclick = “sayHello()” value = “Say Hello” /> </form> </body> </html> The ondblclick Event Type We use the ”ondblclick” event handler in the code below with the element. When users double click the button, it calls the changeColor() function. In the changeColor() function, we change the color of the text. So, the code will change the text”s color when the user double-clicks the button. Example <html> <body> <h2 id = “text”> Hi Users! </h2> <button ondblclick=”changeColor()”> Double click me! </button> <script> function changeColor() { document.getElementById(“text”).style.color = “red”; } </script> </body> </html> The onkeydown Event Type We used the ”keydown” event in the code below with the <input> element. Whenever the user will press any key, it will call the customizeInput() function. In the customizeInput() function, we change the background color of the input and the input text to red. Example <html> <body> <p> Enter charater/s by pressing any key </p> <input type = “text” onkeydown = “customizeInput()”> <script> function customizeInput() { var ele = document.getElementsByTagName(“INPUT”)[0]; ele.style.backgroundColor = “yellow”; ele.style.color = “red”; } </script> </body>

JavaScript – DOM Node Lists

JavaScript – DOM Node Lists ”; Previous Next DOM Node Lists The Node lists are similar to an array or HTML collection containing the HTML elements. However, it is not the same as the array or HTML collection. All modern browsers return the node list when you use querySelectorAll() method and childNodes properties. You can traverse the NodeList as an array but can”t use other array methods like map(), filter(), etc. with node lists. Example Using the forEach() method to traverse the node list elements In the below program, we have defined four <p> elements containing the various languages. After that, we use the querySelectorAll() method to get all elements having a class name equal to ”lang” in the node list. After that, we traverse the node list using the forEach() method and print the HTML of each element. <DOCTYPE html> <html> <body> <p class = “lang”> English </p> <p class = “lang”> German </p> <p class = “lang”> Arabic </p> <p class = “lang”> Hindi </p> <br> <div id = “output”> </div> <script> const output = document.getElementById(”output”); output.innerHTML += “All languages are: <br>”; const langs = document.querySelectorAll(”.lang”); langs.forEach((language) => { output.innerHTML += language.innerHTML + ”<br>”; }) </script> </body> </html> Example: Getting the length of the node list In the below code, we have used the ”length” property of the node list to count the number of nodes in the node list. <DOCTYPE html> <html> <body> <div class = “fruit”> Apple </div> <div class = “fruit”> Orange </div> <div class = “fruit”> Banana </div> <div class = “fruit”> Mango </div> <div id = “output”>Total number of fruits are : </div> <script> const fruits = document.querySelectorAll(”.fruit”); document.getElementById(”output”).innerHTML += fruits.length; </script> </body> </html> Difference between HTMLCollection and NodeList The HTML collection and Node list look similar, but there is a minor difference between them, which we have explained in the table below. Feature HTMLCollection NodeList Return by Generally, getElementByClassName(), getElementByTagName methods, and children properties return the HTML collection. Generally, the querySelectorAll() method and childNodes property return the Node list. Array methods It supports limited array methods. It also supports limited array methods like forEach(). Live collection Some browser supports live collection with HTML collection. It updates if you update the DOM element. Print Page Previous Next Advertisements ”;