JavaScript Array at() Method

JavaScript Array at() method returns an element at the specified index, accepting positive and negative integers. Negative integers count back from the end of the array (-1 is the last element). Syntax array.at(index) Parameters index(optional): It specifies the index (position) of the array element to be returned. The default is 0. Return value Returns an indexed element … Read more

JavaScript Array entries() Method

JavaScript Array entries() method returns a new array iterator object that contains the key/value pairs for each index in the array. This method doesn’t change the original array. It can be particularly useful when you not only want the values from an array but also their corresponding indices. Syntax array.entries() Parameters None. Return value It … Read more

How to Replace Multiple Strings in JavaScript

2 ways to replace multiple strings: Using String replace() method Using String replaceAll() method Method 1: String replace() method You can use the string.replace() method to replace multiple strings with other strings. Visual Representation let str = “Netflix has StrangerThings, BlackMirror, and HouseOfCards”; let mapObj = { StrangerThings:”Millie Bobby Brown”, BlackMirror:”Anthony Mackie”, HouseOfCards:”Kevin Spacey” }; replacedString = … Read more

How to Check If an Array Includes an Object in JavaScript

Here are five ways to check if an array includes an object in JavaScript: Using the includes() function Using the some() function Using the filter() function Using the findIndex() function Using the find() function Method 1: Using the includes() function The array.includes() method returns true  if an array contains an object, otherwise false. Syntax array.includes( element/object, starting_position) Visual Representation Example … Read more

How to Fix Fatal JavaScript invalid size error

Fatal JavaScript invalid size error occurs when you exceed a limit on the size of some data structure(object, array) in your code. If runtime finds a data structure like an array too large to be handled, it will throw an error like this. To fix the error, ensure you “only access elements within the array’s bounds”. … Read more

How to Check If an Array Contains an Element in JavaScript

Here are five ways to check if an array contains an element in JavaScript: Using array.includes() method Using array.indexOf() method Using array.some() method Using the array.find() method Using the array.findIndex() method Method 1: Using the Array.includes() The includes() method is used to check whether an array contains a specified element.  Example const main_array = [11, 21, 18, 19, 46]; … Read more

How to Make JavaScript Sleep or Wait

JavaScript does not have a built-in “sleep()” function that pauses the code execution for a specified period of time. But you can use methods such as setTimeout() for delaying execution and async/await for creating pauses in asynchronous functions. Using setTimeout() You can intentionally delay function execution by combining setTimeout() and  and Promise. Syntax const sleep = (milliseconds) … Read more

How to Find the Sum of an Array of Numbers

Here are the 5 ways to find the sum of an array of numbers in JavaScript: Using array.reduce() method Using the array.forEach() method Using the array.map() method Using for loop Using while loop Method 1: Using array.reduce() method The easiest way to find a sum of an array is to use the array.reduce() method. It can iterate through an … Read more

How to Get Current Timestamp in JavaScript

To get the current timestamp in JavaScript, you can use the Date.now(), new Date.getTime() , or new Date.valueOf() methods. Method 1: Date.now() The Date.now method is used to return the number of milliseconds elapsed since the epoch, defined as midnight on January 1, 1970, UTC. Visual Representation Example let timestamp = Date.now(); console.log(timestamp); Output 1702012836396 Converting … Read more

JavaScript Math max() Method

The JavaScript Math max() method evaluates two or more numbers and returns the largest number among them. Syntax Math.max(x, y, z, …) Parameters x, y, z,…: The numbers out of which the maximum is to be determined. You can pass any number of arguments. Return Value The maximum of all the parameters passed. If no … Read more

JavaScript String charCodeAt() Method

JavaScript String charCodeAt() method returns the Unicode value of the character at the specified index(position) in the string. The index of the last character is string length – 1. Syntax string.charCodeAt(index) Parameters index(optional): A number representing the index of the character you want to return. (Default 0) Return value Returns an integer between 0 and … Read more

JavaScript Object is() Method

The Object is() method is used to check if two values are the same. This method provides functionality similar to the strict equality (===) operator, but there are some differences particularly with NaN and +0/- 0. Two values are the same if one of the following holds: Both are undefined Both are null Both are … Read more

JavaScript Object defineProperty() Method

The Object defineProperty() method is used to define a new property on an object or modify an existing one and returns the object. Syntax Object.defineProperty(obj, prop, descriptor) Parameters obj: The object on which to define the property. prop: The name or Symbol of the property to be defined or modified. descriptor: The descriptor for the property … Read more

5 Easy Ways to Flatten an Array in JavaScript

Here are 5 ways to flatten an array in JavaScript. Using Array flat() method Using Array reduce() method Using Array concat() method Using a spread operator Using a recursive function Method 1: Using the Array flat() method The Array.prototype.flat() method creates a new array with all sub-array elements concatenated recursively up to the specified depth and … Read more

JavaScript String trimStart() and String trimEnd() Method

String trimStart() String trimStart() method is used to remove whitespace from the beginning of a string. The following characters are the whitespace characters: A space character A tab character A carriage return character A new line character A vertical tab character A form feed character Syntax string.trimStart() Parameters None Return value Returns a new string … Read more

What is Strict Mode and How to Use It in JavaScript

Strict mode is a feature in JavaScript that enables stricter parsing and error handling of your code. By opting into the strict mode, you can catch common coding mistakes and “unsafe” actions, such as using undeclared variables, accidentally overwriting global objects, or using deprecated language features. To enable strict mode, you add the following directive … Read more

JavaScript encodeURI() Method

JavaScript encodeURI() method is used to encode a URI(Uniform Resource Identifier) by escaping certain characters. It escapes all characters except Alphabets (A–Z  a–z) ,Digits(0–9) and Special characters( – _ . ! ~ * ‘ ( ) ; / ? : @ & = + $ , #).  Syntax encodeURI(uri) Parameters uri(required): It is a string … Read more

JavaScript Number isFinite() Method

JavaScript Number isFinite() method is used to check whether a passed value is a finite number. Infinite values include Infinity, -Infinity, and NaN. Syntax Number.isFinite(value) Parameters value(required): It is the value to be tested. Return value It returns true if the number is finite; otherwise false. Visual Representation Example 1: Basic Usage console.log(Number.isFinite(10)); //positive number console.log(Number.isFinite(-10)); //negative number … Read more

JavaScript Array copyWithin() Method

JavaScript Array copyWithin() method shallow copies part of an array to another location in the same array and returns it without modifying its length. It modifies the original array. Syntax array.copyWithin(target, start, end) Parameters target(required): It is the index position to copy the elements. start(optional): It is the index position to start copying elements. The default … Read more

JavaScript Math abs() Method

The JavaScript Math abs() method is used to return the absolute value of a number. For example, the absolute value of -5 is 5, and the absolute value of 5 is 5. Syntax Math.abs(num) Parameters num(required): It is a number whose absolute value is to be determined. Return Value If the argument is non-negative, it … Read more

JavaScript String StartsWith() Method

JavaScript String startsWith() method returns true if a string starts with a specified substring, false otherwise. This method is case-sensitive. Syntax str.startsWith(searchString, position]) Parameters searchString(required): The characters to be searched for at the start of this string. position(optional): The position in this string at which to begin searching for searchString; default is 0. Return value It … Read more

JavaScript Function call() Method

The call() method is used to invoke(call) with a given this value and arguments provided individually. The keyword this refers to the owner of the function or the object to which it belongs. Syntax function.call(this, arg1, arg2, …) Parameters this(required): It is the value of this provided for a call to a function. arg1, arg2(optional): It … Read more

JavaScript JSON stringify() Method

The JSON stringify() method is used to convert a JavaScript object or value to a JSON (JavaScript Object Notation) string. Syntax JSON.stringify(value, replacer, space) Parameters value(required): It is the value to be converted into the JSON string. replacer(optioanl): This parameter can be a function that alters the stringification process or an array used as a … Read more

JavaScript Array flatMap() Method

JavaScript array flatMap() method is used to map all array elements and then flattens it into a new array. This method is a combination of map() and flat() methods and doesn’t modify the original array.  Syntax let new_array = arr.flatMap(function callback(currentValue[, index[, array]]) { // return element for new_array }[, thisArg]) Parameters currentValue(required): It is … Read more

JavaScript String valueOf() Method

The String valueOf() method returns the primitive value of the String object. However, it can be useful in certain situations where explicit conversion is needed. This method does not modify the original string. It can be used to convert a string object into a string. Syntax string.valueOf() Parameters None. Return value Returns the primitive value … Read more

JavaScript Exponentiation(**) Operator

The exponentiation (**) operator is used to return the result of raising the first operand(the base) to the power of the second operand(the exponent). The ** operator is right-associative, meaning that in an expression, it is evaluated from right to left. Syntax x ** y Visual Representation Example 1: Use of Exponentiation operator console.log(2 ** 4); … Read more

How to Use ES6 Import in Node.js

To use ES6 import syntax in Node.js, you must enable ES6 modules to support, and there are two ways to do that: Use the file extension .mjs for your module files and run Node.js with the –experimental-modules flag. Add “type”: “module” to your package.json file and use the .js extension for your module files. Method … Read more

JavaScript Error Object

JavaScript Error constructor is used to create Error objects. To create a new Error object, use the “new Error()” constructor expression. The instance of an error object is thrown when runtime errors occur. It is widely used for debugging, exception handling, and input validation. Syntax new Error([message[, fileName[, lineNumber]]]) Parameters message(optional): A human-readable description of the … Read more

JavaScript Math random() Method

The JavaScript Math random() method is used to generate a random number between 0 (inclusive) and 1 (exclusive). This method is commonly used in games to generate random moves or outcomes, in security for creating tokens or random IDs, and for many other purposes. Syntax Math.random() Parameters It does not accept any argument. Return Value … Read more

JavaScript encodeURIComponent() Method

JavaScript encodeURIComponent() method is used to encode some parts or components of URI. It escapes all characters except Alphabets (A–Z  a–z) ,Digits(0–9) and Special characters( – _ . ! ~ * ‘ ( )).  If you have a complete URL to encode, you can use the encodeURI() method. Syntax encodeURIComponent(uri) Parameters uri(required): It is the component of … Read more

JavaScript Number isNaN() Method

The JavaScript Number.isNaN() method is used to check if a value is NaN(Not a Number). This method is a more reliable version of the older global isNaN(). Syntax Number.isNaN(value) Parameters value(required):It is the value that needs to be tested. Return value Returns true if the given value is NaN; otherwise, false. Visual Representation Example 1: … Read more

JavaScript String split() Method

The String split() method is used to split a string into an array of substrings using a specified separator provided in the argument. This method does not change the original string. Syntax string.split(separator, limit) Parameters Parameter Description separator(optional) Specifies the character, or the regular expression, to use for splitting the string. If omitted, the entire string … Read more

JavaScript Rest Parameter

JavaScript rest parameter denoted by three dots (…) is used to represent an indefinite number of arguments as an array. A function can be called with any number of arguments, regardless of how it was defined. Syntax function f(x, y, …args) { // … } One thing to remember is that only the last parameter can … Read more

JavaScript String includes() Method

JavaScript String includes() method is used to check if a string contains a substring. If the substring is found, the method returns true. Otherwise, it returns false. The includes() method is case-sensitive. Syntax string.includes(searchString, position) Parameters searchString(required):  It is the substring, which we need to search in the String. position(optional): The position within the string to … Read more

How to Convert a String to a Number in JavaScript

Here are the 7 ways to convert a string to a number in JavaScript. Using the Number() function Using the parseInt() function Using the parseFloat() function Using the unary operator(+) Using the Math.floor() function Using the Double tilde (~~) Operator Using the Multiplication Method 1: Using the Number() function The easiest way to convert a string to number is … Read more

How to Redirect to New URL in JavaScript

There are three methods for redirecting to a new URL in JavaScript:  Using window.location.href Using window.location.assign() Using window.location.replace() Method 1: Using window.location.href This is the most straightforward method. It’s similar to clicking a link. Syntax window.location.href = “newURL”; Example <!DOCTYPE html> <html> <head> <script> function redirectToHref() { window.location.href = ‘https://appdividend.com’; } </script> </head> <body> <h2>URL … Read more

JavaScript Switch Statement

The JavaScript switch statement is a control structure used for decision-making. It evaluates an expression and executes code blocks based on the case that matches the expression’s value. Syntax switch (expression) { case value1: // Code to execute when expression equals value1 break; case value2: // Code to execute when expression equals value2 break; // … Read more

JavaScript Array keys() Method

JavaScript Array keys() method is used to return a new array iterator object that contains the keys(indices) for each index in the array. Syntax array.keys() Parameters None. Return value Returns new iterable iterator object. Visual Representation Example 1: How to Use Array keys() Method let countries = [‘IND’, ‘SA’, ‘US’,’UK’,’AUS’]; let iteratorObj = countries.keys(); console.log(iteratorObj); … Read more

JavaScript String charAt() Method

JavaScript String charAt() method is used to return a character at a specified index in a string. If the index is out of range (i.e., greater than or equal to the string’s length), the method returns an empty string. Syntax string.charAt(index) Parameters index(required): An integer representing the index of the character you want to return. … Read more

JavaScript Blob

JavaScript Blob is a “group of bytes that holds the data in a file”. A blob has its size and MIME just like that of a simple file. The blob data is stored in the memory or filesystem of a user depending on the browser features and size of the blob. The browser has additional high-level … Read more

JavaScript Array push() Method

JavaScript Array push() method is used to add one or more elements at the end of an array and returns the new length. Syntax array.push(element1, element2,…,elementN) Parameters element1, element2: These are the elements you want to add to the array. Return Value It returns the number representing the new length of the Array. Visual Representation … Read more

How to Empty an Array in JavaScript

There are four ways to empty(clear) an array in JavaScript :  Method 1: Assign an array to an empty array Method 2: Setting an array length to 0 Method 3: Using the splice() method Method 4: Using pop() in a Loop Method 1: Assigning an array to an empty array If you don’t need to … Read more

JavaScript Number isInteger() Method

JavaScript Number isInteger() method is used to check whether the passed value is an integer.  This method is useful for type checking and validation. Syntax Number.isInteger(value) Parameters value: It is a value that needs to be tested. Return Value Returns true if the provided value is an integer; otherwise, false. If the value is NaN or Infinity, … Read more

JavaScript Array splice() Method

JavaScript Array splice() method is used to add, remove, or replace elements from an array. This method modifies the original array. Syntax array.splice(index, howmany, item1, ….., itemX) Parameters index(required): The position at which to start modifying(add/remove) the array. howmany(optional): The number of elements to remove from the array. If you pass 0, that means no elements … Read more

JavaScript Array slice() Method

JavaScript Array slice() method is used to extract a portion of the original array into a new array object. It doesn’t modify the original array.  Syntax array.slice(start, end) Parameters start(optional): It is the index at which to begin extraction. If not provided, the selection starts at start 0. end(optional): It is the index before which to … Read more

JavaScript parseInt() Method

JavaScript parseInt() method is used to parse a string argument and returns an integer of the specified radix(base). Syntax parseInt(string, radix); Parameters string(required):  It is an argument that needs to be converted into an integer. radix(optional): It is an integer between 2 and 36 that represents the radix which is the base in mathematical numeral … Read more

JavaScript String slice() Method

JavaScript String slice() method is used to extract a part of a string and return it as a substring. It does not modify the original string. This method accepts negative indices, unlike the substring() method, which does not support negative indices. Syntax string.slice(startIndex, endIndex) Parameters startIndex(required): It is the position where to begin the extraction. The … Read more