Javascript – Useful Resources ”; Previous Next The following resources contain additional information on Javascript. Please use them to get more in-depth knowledge on this topic. Useful Video Courses JavaScript Masterclass: ES6 Modern Development 71 Lectures 4.5 hours Frahaan Hussain More Detail JavaScript fundamentals Course for Beginners: JavaScript ES6 37 Lectures 2 hours Laurence Svekis More Detail JavaScript Training Course – Practice building 5 applications 32 Lectures 2 hours Laurence Svekis More Detail JavaScript Objects and OOP Programming with JavaScript 23 Lectures 1.5 hours Laurence Svekis More Detail JavaScript Advanced Course – Useful methods to power up your code 26 Lectures 2 hours Laurence Svekis More Detail JavaScript Course for Beginner to Expert: Data Visualization Best Seller 77 Lectures 6 hours Metla Sudha Sekhar More Detail Print Page Previous Next Advertisements ”;
Category: javascript
JavaScript – DOM Elements
JavaScript – DOM Elements ”; Previous Next The DOM Elements The HTML DOM elements is the acronym for the Document Object Model elements. With JavaScript, we can manipulate the HTM elements. We can access the HTML elements using id, attribute, tag name, class name, etc. When a web page loads in the browser, it creates a DOM tree representing the web page”s structure. The web page contains various HTML elements, which you can manipulate using the properties and methods in JavaScript. Here we will discuss to access, modify, or replace, etc. DOM elements. Accessing DOM elements You can use different methods to access HTML elements, as given below. Get HTML Element using its “id” In the web page, each HTML element can have a unique id value. You can use the getElementById() method to access the HTML element using the id. Syntax Follow the syntax below to use the getElemenetById() method to access the HTML element using its id. document.getElementById(”id”) In the above syntax, you need to replace the ”id” with the actual id of the element. Example In the below code, we access the div element using id and change its inner HTML using the ”innerHTML” property. <html> <body> <div id = “output”> </div> <script> document.getElementById(”output”).innerHTML = “The element is accessed using the id.”; </script> </body> </html> Output The element is accessed using the id. Get an HTML element using the “name” An HTML can have a ”name” attribute. You can use the getElementByName() method to access the HTML element using the ”name” attribute”s value. Syntax Follow the syntax below to use the getElementByName() method. document.getElementsByName(”name”) Here, you need to replace the ”name” with a value of the element”s name attribute. Example In the below code, we access the div element using the name. It returns the array of nodes with the name passed as an argument. <html> <body> <div name = “text”> Hello World! </div> <div id = “output”>The content of the div elment is: </div> <script> const divEle = document.getElementsByName(”text”); document.getElementById(“output”).innerHTML += divEle[0].innerHTML; </script> </body> </html> Output Hello World! The content of the div elment is: Hello World! Get HTML element using the “className” The class attribute of the HTML contains the string value. A single HTML element can also have multiple classes. You can use the getElementByClassName() method to access the HTML element using any single class name among multiples. Syntax Follow the syntax below to use the getElementByClassName() method. document.getElementsByClassName(”className”); In the above syntax, replace the ”className” with the value of the elment”s ”class” attribute. Example In the below code, we access the div element using the class name. <html> <body> <div class = “fruit”> Apple </div> <div id = “output”>The name of the fruit is: </div> <script> const divEle = document.getElementsByClassName(”fruit”); document.getElementById(“output”).innerHTML += divEle[0].innerHTML; </script> </body> </html> Output Apple The name of the fruit is: Apple Get an HTML element using the “tag” name Each HTML element is defined using the HTML tag. You can use the tag getElementByTagName() method to access the HTML elements using the tag name. Syntax Follow the syntax below to use the getElementByTagName() method. document.getElementsByTagName(”tag”); In the above syntax, replace the ”tag” with the HTML tag like ”p”, ”a”, ”img”, etc. Example In the below code, we access the <p> elements using the getElementTagName() method. It returns the Nodelist of <p> elements. <html> <body> <p>This is the first paragraph.</p> <p>This is the second paragrraph.</p> <div id = “output”> </div> <script> const numbers = document.getElementsByTagName(”p”); document.getElementById(“output”).innerHTML = “The first ”p” element is: ” + numbers[0].innerHTML + “<br>” + “The second ”p” element is: ” + numbers[1].innerHTML; </script> </body> </html> Output This is the first paragraph. This is the second paragrraph. The first ”p” element is: This is the first paragraph. The second ”p” element is: This is the second paragrraph. Modifying the DOM Elements JavaScript allows you to modify and replace the HTML DOM elements. In this section, we will cover modifying DOM elements” content and replacing child elements. Modify the Content of the DOM Element You can use the ”textContent” property of the element to modify the text of the HTML element. However, you can use other properties like innerHTML, outerHTML, outerText, etc., to modify the HTML element”s content. Syntax Follow the syntax below to use the textContent property to modify the text content of the HTML element. element.textContent = newText; In the above syntax, we have assigned the ”newText” dynamic value to the ”textContent” property to update the content of the ”element”. Example In the output, when you click the button, it will invoke the updateText() function and uses the textContent property to change the text of the div element. <html> <body> <button onclick = “updateText()”> Update Text </button> <p id = “text”> Hello World! </p> <script> function updateText() { document.getElementById(“text”).textContent = “This is updaetd text!”; } </script> </body> </html> Replace the Child Element In JavaScript, you can use the replaceChild() method to replace the child element of the particular HTML element. Syntax Follow the syntax below to use the replaceChild() method in JavaScript. textDiv.replaceChild(newNode,replacableNode); The replaceChild() method takes a new node as a first parameter and a node that needs to be replaced as a second parameter. Example In the below code, we used the replaceChild() method to replace the second child of the div element with a new node. Here, we have also used the createTextNode() to create a new node with a ”Hello World!” text. <html> <body> <button onclick = “replaceText()”> Replace Child </button> <div id = “text”> <p> Hi Users! </p> </div> <script> function replaceText() { let textDiv = document.getElementById(“text”); let newText = document.createTextNode(“Hello World”); textDiv.replaceChild(newText, textDiv.childNodes[1]); } </script> </body> </html> Adding Events to the DOM Elements You can use addEventListner() method to add events to the DOM elements to interact with the HTML elements. Syntax Follow the syntax below to use the addEventListner() method. element.addEventListener(eventName, callback); The addEventListner() method takes an event name as the first parameter and a callback function as a second parameter. Example We added the
JavaScript – Call Stack
JavaScript – Call Stack ”; Previous Next JavaScript engine uses the call stacks to manage the execution context. It is an important mechanism by which a JavaScript run engine keeps track of the function calls in a JavaScript code. However, the working of the JavaScript call stack is performed internally, but it is important to understand how JavaScript executes the functions. JavaScript call stack keeps track of what function or block of code needs to run currently. It works in the LIFO (Last In, First Out) manner. So, whatever function is added at the top in the call stack it gets executed first. How JavaScript Call Stack Works? Whenever you execute any JavaScript code, it adds the global execution context to the script. When you call any function, the JavaScript engine adds the function to the call stack. After that, when you call any nested function from the outer function, it adds a nested function in the call stack. When the execution of the inner function is complete, it pops the function from the call stack. Next, it executes the outer function and pops it from the call stack. Again, it starts executing the code in the global context. When the call stack becomes empty, the script stops running. Let”s understand the JavaScript call stack via example. function two() { console.log(“this is function two”); } function one() { two(); console.log(“This is function one”); } one(); The above code would be executed like this. 1. When the execution of the code starts, the call stack remains empty until execution reaches the one() function. 2. Add function one() in the call stack. Now, the call stack is [one()]. 3. Execute the first line of function one(), which calls the function two(). 4. Add function two() in the call stack. Now, the call stack is [two(), one()]. 5. Execute all lines of function two(). 6. Move back to execute the remaining lines of code of function one(). 7. Delete the function two() from the call stack. Now, the call stack is [one()]. 8. Start executing the remaining code of the function one(). When the execution of function one() completes, the JavaScript engine starts executing the remaining code. 9. Delete function one() from the call stack. Now, the call stack is empty. 10. Execute the remaining code. Example Whenever we execute the below code, it will add the global execution context in the call stack. Whenever it calls any function from the global execution contest, it will add that function to the call stack, and start executing that function first. When another function is called from the particular function, it gets added to the call stack and gets priority for the execution. When the execution of the particular function is finished, the interpreter removes it from the call stack. Whenever a stack takes more space than its size, it throws the ”stack overflow” error. <html> <body> <h2> JavaScript – Call stack </h2> <div id = “output”></div> <script> const output = document.getElementById(“output”); function two() { output.innerHTML += “two <br>”; } function one() { two(); output.innerHTML += “one <br>”; } one(); </script> </body> </html> JavaScript Call Stack Overflow Whenever the size of the call stack exceeds the defined size, a call stack overflow occurs. Generally, whenever a recursive function doesn”t have an exit point call, a stack overflow occurs. For example, in the code below, the fib() function doesn”t have an exit point. So, it throws a call stack overflow error. function fib() { fib(); } fib(); Javascript is a single-thread programming language. So, it runs the code line-by-line from top to bottom. It means a JavaScript program can have only 1 call stack, and it can execute one line at a time. Print Page Previous Next Advertisements ”;
JavaScript – void Keyword
JavaScript – void Keyword ”; Previous Next The void keyword in JavaScript is used as an operator that evaluates a given expression and returns undefined. The void is an important keyword in JavaScript. The meaning of the void is null or empty. The void keyword can be used as a unary operator that appears before its single operand, which may be of any type. This operator specifies an expression to be evaluated without returning a value or returning the undefined. Syntax The syntax to use the void keyword in JavaScript − void operand; In the above syntax, the operand can be any expression. Return Value It returns the undefined. Example In the below code, we used the 10 with the ”void” keyword. In the output, you can observe that it returns undefined. <html> <body> <div id = “output”>The value of the ans variable is: </div> <script> let ans = void 10; document.getElementById(“output”).innerHTML += ans; </script> </body> </html> Output The value of the ans variable is: undefined Importance of Precedence of void Keyword Generally, the JavaScript ”void” keyword is used to return the primitive undefined value, but if you don”t take precedence in the consideration, it can return a different value. Let”s understand it via the example below. Example In the below code, the void operator takes precedence over the strict equality operator in the first expression. So, it first evaluates ”void 10” to undefined and compares it with 20. So, it returns false. The second expression evaluates ”10 === 20” first to false and evaluates ”void false” to undefined. <html> <body> <div id = “output1”> </div> <div id = “output2”> </div> <script> let res1 = void 10 === 20; let res2 = void (10 === 20); document.getElementById(“output1”).innerHTML += res1; document.getElementById(“output2″).innerHTML += res2; </script> </body> </html> Output false undefined What is javascript:void(0)? Let”s break down the javascript:void(0) into two parts and understand both separately. javascript: You can use the ”javascript:” to create a pseudo URL. Using ”javascript:” you can create the interactive URL. You need to write the expression after ”javascript:”, and when users click the anchor text, it executes the JavaScript code. Let”s understand it via the example below. Example In the below code, we have created the link text and used the JavaScript URL as a href. When you click the anchor text, it writes it in the HTML document. <html> <body> <a href = “javascript:document.write(”Anchor text is clicked!”)”> Click me! </a> </body> </html> In this way, you can use the ”javascript:uri” to create the pseudo URL. void(0) The void(0) evaluates the JavaScript expression, but it returns undefined. So, when you want to execute the expression without performing any action, you can use the void(0). javascript: void(0) When you don”t want to navigate users to another web page when they click on the link, you can use the ”javascript:void(0)” as a href value of the anchor tag. Let”s understand it via the example below. Example It won”t do anything Whenever you click the anchor text in the code below. <html> <body> <a href = “javascript:void(0)”> Click me! </a> </body> </html> You can also use the ”javascript:void(0)” when you want to update the web page using the URI but don”t want to navigate to another web page. Example In the below code, when you click the anchor text, it will change the background color of the body, rather than navigating to another web page. <html> <body> <a href = “javascript:void(0);” onclick = “document.body.style.backgroundColor = ”blue””> Change Background Color </a> </body> </html> The void Keyword with Functions When you use the void keyword with JavaScript functions, it returns undefined. After that, if you try to execute the function, it will throw an error, as the ”void” operator considers the function as its operand and evaluates it as undefined. Example In the below code, we have defined the test() function and used the ”void” keyword with it. Also, used the try…catch block to catch the error. In the try block, we execute the function, and in the output, you can observe that control goes into the catch block. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(”demo”); try { void function test() { output.innerHTML += “The test function is executed!”; } test(); } catch (error) { output.innerHTML += “The test function is undefined!”; } </script> </body> </html> Output The test function is undefined! The void Keyword with Immediately Invoked Function When you use the ”void” keyword with the JavaScript immediately invoked function, it invokes the function expression first and evaluates it as undefined. Example In the below code, we have defined the immediately invoked function with the void keyword. You can observe that it invokes the function first and returns undefined. <html> <body> <div id = “demo”> </div> <script> const output = document.getElementById(“demo”); void function () { output.innerHTML = “Unknown function is executed!”; }(); </script> </body> </html> Output Unknown function is executed! Also, you can use the ”void” keyword with the arrow function to return undefined from the arrow function. The JavaScript:void() URI can also be used to prevent the web page reloading by default, like the preventDefault() method. Print Page Previous Next Advertisements ”;
JavaScript – Get Date Methods ”; Previous Next Get Date Methods JavaScript utilizes the Date object for date and time manipulation. This object offers an array of methods that facilitate retrieval and modification of date-specific information. Here, we will discuss about the get date methods within JavaScript which fetch different components of the date/time. Below is a table of the most commonly used get date methods and their corresponding description. Method Description getFullYear() This method fetches and presents the comprehensive calendar year by retrieving the current year in local time zone; it returns the full four-digit representation of a local date object. getMonth() Returns the month (0-11) of the local date object. This method retrieves the current month, with values ranging from 0 (January) to 11 (December). It”s useful for displaying and manipulating month-related information. getDate() The method: ”returns the day component of the current date”, a value ranging from 1 to 31. This functionality proves particularly useful when one needs this information extracted from a local date object. getHours() The function ”getHours()” extracts and returns the local date object”s hour component (0-23). This allows you to retrieve the current hour in your local time zone for a variety of time-related applications. getMinutes() Returns the minutes (0-59) of the local date object. Retrieves the current minute component, ranging from 0 to 59. Useful for displaying and handling time-related data at the minute level. getSeconds() This returns the seconds ranging from 0 to 59 of the local date object. It provides precision down the seconds for a variety of time-based calculations/displays. getMilliseconds() Returns the milliseconds (0-999) of the local date object. Retrieves the current millisecond component, allowing for high precision in time-related applications and calculations. getDay() Returns the index of day of the week starting from 0 which stands for Sunday, all the way up to 6 for Saturday. getUTCFullYear() Returns the full 4-digit year of the date object in Coordinated Universal Time (UTC). This method retrieves the current year in UTC, providing a standardized representation of the calendar year irrespective of the local time zone. getUTCMonth() Returns the index of the month ranging from 0(Jan) to 11(Dec) but of the date object in Coordinated Universal Time (UTC). getUTCDate() Returns the day of the month (1-31) of the date object in Coordinated Universal Time (UTC). Useful for obtaining the day component of the current date in a UTC context. getUTCHours() Returns the hour (0-23) of the date object in Coordinated Universal Time (UTC). Retrieves the current hour in UTC, allowing for standardized access to the hour component across different time zones. getUTCMinutes() Returns the minutes (0-59) of the date object in Coordinated Universal Time (UTC). Retrieves the current minute component in UTC, providing standardized minute information for various international time-based applications. getUTCSeconds() The function fetches the seconds (ranging from 0 to 59) of a date object in Coordinated Universal Time (UTC). It also acquires the current second component in UTC, thereby enabling standardized second information across various time zones. getUTCMilliseconds() The function returns the milliseconds (0-999) of the date object in Coordinated Universal Time (UTC); it retrieves and offers high precision for standardized time-related calculations and applications: specifically, it provides the current millisecond component in UTC. Examples Example 1: Simple demonstration of get date methods The following example demonstrates the fundamental application of prevalent JavaScript date methods: It instantiates a novel Date object to represent the present date and time; subsequently, it exhibits an array of diverse components – year, month, day; hours, minutes, seconds, milliseconds; along with their corresponding UTC counterparts. The displayed elements encompass not only standard temporal divisions but also supplementary information about weekdays: thus providing comprehensive insight into current temporal dynamics. <!DOCTYPE html> <html> <head> <title> Exxample to demonstrate get date methods in JavaScript</title> </head> <body> <script> // Create a new Date object const currentDate = new Date(); function displayResult(methodName, result) { const resultDiv = document.createElement(”div”); resultDiv.innerHTML = `${methodName}: ${result}`; document.body.appendChild(resultDiv); } displayResult(”getFullYear()”, currentDate.getFullYear()); displayResult(”getMonth()”, currentDate.getMonth()); displayResult(”getDate()”, currentDate.getDate()); displayResult(”getHours()”, currentDate.getHours()); displayResult(”getMinutes()”, currentDate.getMinutes()); displayResult(”getSeconds()”, currentDate.getSeconds()); displayResult(”getMilliseconds()”, currentDate.getMilliseconds()); displayResult(”getDay()”, currentDate.getDay()); displayResult(”getUTCFullYear()”, currentDate.getUTCFullYear()); displayResult(”getUTCMonth()”, currentDate.getUTCMonth()); displayResult(”getUTCDate()”, currentDate.getUTCDate()); displayResult(”getUTCHours()”, currentDate.getUTCHours()); displayResult(”getUTCMinutes()”, currentDate.getUTCMinutes()); displayResult(”getUTCSeconds()”, currentDate.getUTCSeconds()); displayResult(”getUTCMilliseconds()”, currentDate.getUTCMilliseconds()); </script> </body> </html> Example 2: Comparison of two dates In this example, the Date constructor creates two specific dates: date1 and date2. The script subsequently compares these dates; it displays their formatted representations, along with a message indicating if date1 is later, earlier or equal to date2. <!DOCTYPE html> <html> <head> <title>Comparison of two dates in JavaScript</title> </head> <body> <script> const date1 = new Date(2024, 0, 18); const date2 = new Date(2024, 0, 26); function displayComparison() { const date1Div = document.createElement(”div”); date1Div.innerHTML = `Date 1: ${date1.toDateString()}`; document.body.appendChild(date1Div); const date2Div = document.createElement(”div”); date2Div.innerHTML = `Date 2: ${date2.toDateString()}`; document.body.appendChild(date2Div); const resultDiv = document.createElement(”div”); if (date1 > date2) { resultDiv.innerHTML = “date 1 is later than date 2”; } else if (date1 < date2) { resultDiv.innerHTML = “date 1 is earlier than date 2”; } else { resultDiv.innerHTML = “Both dates are equal”; } document.body.appendChild(resultDiv); } displayComparison(); </script> </body> </html> Print Page Previous Next Advertisements ”;
JavaScript – Shallow Copy
JavaScript – Shallow Copy ”; Previous Next Shallow Copy In JavaScript, a shallow copy is a duplication of an array or object that replicates its top-level elements, but not its nested structures. When creating a shallow copy of an array, common methods include using the spread operator ([…]), Array.from(), or the slice() method. For objects, the spread operator ({…}) and Object.assign() are commonly used. It is important to note that while the top-level statements are being duplicated, any nested object or arrays that are within the original structure are not cloned, instead their references are retained in the shallow copy. Consequently, modifications to nested structures in the copied version affect the original and vice versa. For deep cloning, where nested structures are also duplicated, alternative techniques or libraries such as lodash”s _.cloneDeep are required. Deep Copy vs. Shallow Copy Two methods exist for duplicating objects or arrays: deep copying and shallow copying. Deep copying creates an entirely independent duplicate even including nested structures; conversely, shallow copying only replicates top-level elements while maintaining references to the nested ones. While deep copying guarantees complete independence, shallow copy proves more memory-efficient and faster but at a cost: modifications in nested structures impact both original and copied objects. Task requirements dictate the choice: for total independence, deep copying is preferred; however, when efficiency is paramount and nested references can be preserved, shallow copying becomes the optimal option. Examples Example 1: Shallow copy using Object assign() method In the following example, we use the Object.assign() method create a shallow copy of an object. <!DOCTYPE html> <html> <body> <h2>Shallow copy using Object.assign() method</h2> <p>Original Object:</p> <p id=”originalObject”></p> <p>Copied Object:</p> <p id=”copiedObject”></p> <script> const originalObject = { name: “Alice”, age: 30 }; const copiedObject = Object.assign({}, originalObject); document.getElementById(“originalObject”).textContent = JSON.stringify(originalObject); document.getElementById(“copiedObject”).textContent = JSON.stringify(copiedObject); </script> </body> </html> Example 2: Shallow copy using spread operator In this example we use the spread operator (…) to creating a shallow copy of an array. <!DOCTYPE html> <html> <body> <h2>Shallow copy using spread operator (…)</h2> <p>Original Array:</p> <p id=”originalArray”></p> <p>Copied Object:</p> <p id=”copiedArray”></p> <script> const originalArray = [1, 2, 3]; const copiedArray = […originalArray]; document.getElementById(“originalArray”).textContent = JSON.stringify(originalArray); document.getElementById(“copiedArray”).textContent = JSON.stringify(copiedArray); </script> </body> </html> Example 3:Shallow copy of object with array In the example below, a combination of Object.assign() and Array.prototype.slice() is used to create a shallow copy of an object, emphasizing proper handling of arrays within the object structure. <!DOCTYPE html> <html> <body> <h2>Shallow copy using array slice() method</h2> <p>Original Object:</p> <p id=”originalObject”></p> <p>Copied Object:</p> <p id=”copiedObject”></p> <script> const originalObject = { name: “Bob”, hobbies: [“reading”, “coding”] }; const copiedObject = Object.assign({}, originalObject, { hobbies: originalObject.hobbies.slice() }); document.getElementById(“originalObject”).textContent = JSON.stringify(originalObject); document.getElementById(“copiedObject”).textContent = JSON.stringify(copiedObject); </script> </body> </html> Example 4: Shallow Copy with Nested Objects In this example we demonstrate creating of shallow copies of an object with nested properties using the JSON.stringify and JSON.parse methods of JavaScript. The original object contains of a nested structure which has properties like name and address. Address further consists of properties like street and city. We then use JSON.stringify to convert the original object into a JSON formatted string & then apply the JSON.parse to parse the string back into a new object thereby creating a shallow copy. <!DOCTYPE html> <html> <body> <h2>Shallow Copy with Nested objects using JSON.stringify & JSON.parse</h2> <p>Original Object:</p> <pre id=”originalObject”></pre> <p>Copied Object:</p> <pre id=”copiedObject”></pre> <script> const originalObject = { name: “Charlie”, address: { street: “123 Main St”, city: “New York” } }; const copiedObject = JSON.parse(JSON.stringify(originalObject)); document.getElementById(“originalObject”).textContent = JSON.stringify(originalObject, null, 2); document.getElementById(“copiedObject”).textContent = JSON.stringify(copiedObject, null, 2); </script> </body> </html> Example 5: Shallow copy impact of modification Illustrating the impact of modifications on a shallow copy created via JavaScript”s Object.assign() method, the following code initially presents an original object. The original object features properties named “name” and “age,” side by side with its corresponding shallow copy. Next, we observe how this code alters the “age” property of our copied object. Subsequently, the code presents an exposition of both the original and copied objects” states post-modification. This instance accentuates that alterations to the shallow copy despite isolating within its duplicated object do not influence the base object; it thereby confirms a peculiar behaviour wherein top-level properties are captured by shallow copies while preserving independence between primary and secondary instances. <!DOCTYPE html> <html> <body> <h2>Shallow Copy impact of modification</h2> <h3>Before Modification</h3> <p>Original Object</p> <pre id=”originalObjectBefore”></pre> <p>Copied Object</p> <pre id=”copiedObjectBefore”></pre> <h3>After Modification</h3> <p>Original Object</p> <pre id=”originalObjectAfter”></pre> <p>Copied Object</p> <pre id=”copiedObjectAfter”></pre> <script> const originalObject = { name: “Alice”, age: 30 }; const copiedObject = Object.assign({}, originalObject); document.getElementById(“originalObjectBefore”).textContent = JSON.stringify(originalObject, null, 2); document.getElementById(“copiedObjectBefore”).textContent = JSON.stringify(copiedObject, null, 2); copiedObject.age = 40; document.getElementById(“originalObjectAfter”).textContent = JSON.stringify(originalObject, null, 2); document.getElementById(“copiedObjectAfter”).textContent = JSON.stringify(copiedObject, null, 2); </script> </body> </html> Importance of Shallow Copy To preserve the original data structure and manage memory efficiently, one must critically understand shallow copying in JavaScript: it duplicates top-level elements a concept that achieves balance. This understanding empowers non-destructive manipulation tasks; for example, array sorting. Furthermore, it simplifies feature implementation processes like undo/redo functionalities, all while significantly enhancing overall user experience – an integral role indeed. Shallow copies possessing the capacity to adeptly handle alterations in practical applications maintain data integrity: a crucial aspect when isolating modifications from an original object is necessary in certain scenarios. Print Page Previous Next Advertisements ”;
JavaScript – Functions
JavaScript Built-in Functions ”; Previous Next Number Methods The Number object contains only the default methods that are part of every object”s definition. Sr.No. Method & Description 1 constructor() Returns the function that created this object”s instance. By default this is the Number object. 2 toExponential() Forces a number to display in exponential notation, even if the number is in the range in which JavaScript normally uses standard notation. 3 toFixed() Formats a number with a specific number of digits to the right of the decimal. 4 toLocaleString() Returns a string value version of the current number in a format that may vary according to a browser”s locale settings. 5 toPrecision() Defines how many total digits (including digits to the left and right of the decimal) to display of a number. 6 toString() Returns the string representation of the number”s value. 7 valueOf() Returns the number”s value. Boolean Methods Here is a list of each method and its description. Sr.No. Method & Description 1 toSource() Returns a string containing the source of the Boolean object; you can use this string to create an equivalent object. 2 toString() Returns a string of either “true” or “false” depending upon the value of the object. 3 valueOf() Returns the primitive value of the Boolean object. String Methods Here is a list of each method and its description. Sr.No. Method & Description 1 charAt() Returns the character at the specified index. 2 charCodeAt() Returns a number indicating the Unicode value of the character at the given index. 3 concat() Combines the text of two strings and returns a new string. 4 indexOf() Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found. 5 lastIndexOf() Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. 6 localeCompare() Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. 7 length() Returns the length of the string. 8 match() Used to match a regular expression against a string. 9 replace() Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring. 10 search() Executes the search for a match between a regular expression and a specified string. 11 slice() Extracts a section of a string and returns a new string. 12 split() Splits a String object into an array of strings by separating the string into substrings. 13 substr() Returns the characters in a string beginning at the specified location through the specified number of characters. 14 substring() Returns the characters in a string between two indexes into the string. 15 toLocaleLowerCase() The characters within a string are converted to lower case while respecting the current locale. 16 toLocaleUpperCase() The characters within a string are converted to upper case while respecting the current locale. 17 toLowerCase() Returns the calling string value converted to lower case. 18 toString() Returns a string representing the specified object. 19 toUpperCase() Returns the calling string value converted to uppercase. 20 valueOf() Returns the primitive value of the specified object. String HTML wrappers Here is a list of each method which returns a copy of the string wrapped inside the appropriate HTML tag. Sr.No. Method & Description 1 anchor() Creates an HTML anchor that is used as a hypertext target. 2 big() Creates a string to be displayed in a big font as if it were in a <big> tag. 3 blink() Creates a string to blink as if it were in a <blink> tag. 4 bold() Creates a string to be displayed as bold as if it were in a <b> tag. 5 fixed() Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag 6 fontcolor() Causes a string to be displayed in the specified color as if it were in a <font color=”color”> tag. 7 fontsize() Causes a string to be displayed in the specified font size as if it were in a <font size=”size”> tag. 8 italics() Causes a string to be italic, as if it were in an <i> tag. 9 link() Creates an HTML hypertext link that requests another URL. 10 small() Causes a string to be displayed in a small font, as if it were in a <small> tag. 11 strike() Causes a string to be displayed as struck-out text, as if it were in a <strike> tag. 12 sub() Causes a string to be displayed as a subscript, as if it were in a <sub> tag 13 sup() Causes a string to be displayed as a superscript, as if it were in a <sup> tag Array Methods Here is a list of each method and its description. Sr.No. Method & Description 1 concat() Returns a new array comprised of this array joined with other array(s) and/or value(s). 2 every() Returns true if every element in this array satisfies the provided testing function. 3 filter() Creates a new array with all of the elements of this array for which the provided filtering function returns true. 4 forEach() Calls a function for each element in the array. 5 indexOf() Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found. 6 join() Joins all elements of an array into a string. 7 lastIndexOf() Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found. 8 map() Creates a new array with the results of calling a provided function on every element in this array. 9 pop() Removes the last element from an array and returns that element. 10 push() Adds one or more elements to the end of an array and returns the new length of the array. 11 reduce() Apply a function simultaneously against two values of the
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