Cannot read property addeventlistener of null – How to Fix Cannot read Property addEventListener of Null Error in JavaScript?

How to Fix Cannot read Property addEventListener of Null Error in JavaScript

Cannot read property addeventlistener of null: There are two primary causes of the “Cannot read property addEventListener of null” error:

  • Attempting to access the addEventListener() method on an element that does not exist in the DOM.
  • Inserting the JS script tag above the HTML, where the DOM elements are defined/declared.

index.js:

const button = document.getElementById('id not found');
console.log(button); // null

// Here we get cannot read properties of null Error (reading 'addEventListener')
button.addEventListener('click', () => {
  console.log('The button is clicked!!!');
});

Since we provided an id that does not exist in the DOM, the getElementById method returned null.

Use an if statement to verify if the DOM element is found before invoking/calling the addEventListener() method to resolve the “Cannot read property addEventListener of null” problem.

const button = document.getElementById('does-not-exist');
console.log(button); 

// Check if btn exists before addEventListener()
if (button) {
  button.addEventListener('click', () => {
    console.log('The button is clicked!!!');
  });
}

//  Use optional chaining (.)
button.addEventListener('click', () => {
  console.log('The button is clicked!!!');
});

Ensure sure to pass the right identifier and include an if statement to determine whether the DOM element is defined.

The second example is using the optional chaining (.) operator, which causes a short-circuit rather than an error.

If the button variable’s value is null or undefined, the operator returns undefined; otherwise, the method is called.

To resolve the “Cannot read property addEventListener of null” error, place the JS script tag at the bottom of the body. After the HTML elements have been declared, the JS script tag should be placed.

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <!-- Here script tag is placed before the HTMl elements which is 
    a BAD approach since this script tag gets executed before HTML body-->
    <script src="index.js"></script>

    <button id="btn">Submit</button>
  </body>
</html>

Explanation:

Since this JS script tag is added before the button element is declared in the example, 
the button element will not be available in the index.js file.

index.js:

const button = document.getElementById('button');
console.log(button);

// Here we get cannot read properties of null Error (reading 'addEventListener')
button.addEventListener('click', () => {
  console.log('The button is clicked!!!');
});

Fixing Cannot read Property addEventListener of Null Error in JavaScript

Cannot read property addeventlistener of undefined: The JavaScript <script/> tag must be moved to the bottom of the body after the declaration of HTML elements.

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <button id="btn">Submit</button>

    <!--Here the script tag is placed at the bottom of the body after the 
    declaration of HTML elements which is a GOOD approach-->
    <script src="index.js"></script>
  </body>
</html>

Since the DOM elements have already been declared by the time the script is run, the index.js file now has access to them.

index.js:

const button = document.getElementById('button');
console.log(button);

// Now the code does not produce an error. It works fine
button.addEventListener('click', () => {
  console.log('The button is clicked!!!');
});

Since the button element is positioned above the script that loads the index.js file, it gets executed before the script.

The button element is found, and the getElementById method returns the actual element rather than null, allowing us to execute the element’s addEventListener method and attach an event listener.

In Brief

When trying to call the addEventListener() method on an element that does not exist in the DOM, the “Cannot read property addEventListener of null” error occurs.

Variables with a value of null are frequently returned by methods like getElementById() when the element do not exist in the DOM.

How to Fix Cannot read property ‘replace’ of Undefined in JavaScript

How to Fix Cannot read property 'replace' of Undefined in JavaScript

Typeerror: cannot read property ‘replace’ of undefined: In this article, let us see how to fix the Cannot read property 'replace' of Undefined error in JavaScript

Fixing Cannot read property ‘replace’ of Undefined Error in JavaScript

Let us see the examples to know how this error occurs and try to fix them.

1) Calling the replace() function on an undefined String

When calling the replace() function on a variable that stores an undefined value, the error “Cannot read property ‘replace’ of undefined” occurs. To fix the problem, only use the replace function on data types that implement it, such as strings.

index.js:

// Give the string as static input and store it in a variable.
const gvn_str = undefined;

// Apply replace function on the given string to replace 'hello'
// with 'btechgeeks'
// Here we get TypeError: Cannot read property 'replace' of undefined
// error since the string is undefined
gvn_str.replace('hello', 'btechgeeks');

Output:

gvn_str.replace('hello', 'btechgeeks');
^

TypeError: Cannot read property 'replace' of undefined
at Object.<anonymous> (/tmp/toemEjan2d.js:8:9)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

We received the error because we used the replace() method on an undefined value.

2)Reading an Array at an Invalid Index

Another common source of the error is trying to read an array at an invalid index(which does not exist) and then invoking the replace() method.

index.js:

// Give the string as static input and store it in a variable.
const gvn_arry = [];

// Apply replace() function on the first element of the given array as array index starts with 0
// to replace 'hello' with 'btechgeeks'
// Here we get TypeError: Cannot read property 'replace' of undefined
// error since the given array is empty(undefined)
gvn_arry[0].replace('hello', 'btechgeeks');

// we can alse use optional chaining (.) to replace
const rslt = gvn_arry[0].replace('hello', 'btechgeeks');

Output:

gvn_arry[0].replace('hello', 'btechgeeks');
^

TypeError: Cannot read property 'replace' of undefined
at Object.<anonymous> (/tmp/toemEjan2d.js:8:13)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

We can fix Cannot read property 'replace' of Undefined error in JavaScript using the below code

// Take a variable and initilaize its value with undefined
const demo = undefined;
// ✅ Method #1
// Initialize the above variable to empty string
const gvn_str = demo || '';
// ✅ Method #2
// replace hello with btechgeeks using optional chaining(.) and
// replace() function and store it in a variable
const rslt = gvn_str.replace('hello', 'btechgeeks');
console.log(rslt); 

// ✅ Method #3 check if the above result is not empty/undefined using the if conditional statement
if (gvn_str) {
  // If the result is not undefined then replace the hello with btechgeeks using optional chaining and replace function and    // store it in some variable
  const rslt = gvn_str.replace('hello', 'btechgeeks');
}

// ✅ Method #4: Check if the type of the above variable gvn_str is a string using the typeof property
if (typeof gvn_str === 'string') {
    // If it is true, then replace hello with btechgeeks
  const rslt = gvn_str.replace('hello', 'btechgeeks');
}

// ✅ Method #5:  Give the fallback in place
const rslt = (gvn_str || '').replace('hello', 'btechgeeks');

Explanation:

Method #1 in code:

If the value to the left is false (example: undefined), we used the logical OR (||) operator to give a fallback value.

The logical OR operator returns the value to the right if the value to the left is falsy.

Method #2 in code:

The above example explains how to short-circuit instead of throwing an error by using the optional chaining (.) operator.

The optional chaining (?.) operator short-circuits if the value stored in the str variable is undefined or null, returning 
undefined.

Method #3 in code:

The following example verifies that the value saved in the str variable is true. Undefined does not satisfy the criteria because it is a false value.

Method #4 in code:

Before using the replace() method, the fourth example verifies if the value is of the string type.

Method #5 in code:

The final example, right before running the replace method, uses the logical OR (||) operator to provide a fallback.

When working with DOM elements and getting the “Cannot read property’replace’ of undefined” error, make sure:

  • The DOM contains the element you’re working with.
  • After all of the HTML components have been declared, you’ll place the JS script tag at the bottom of the body.

Javascript split is not a function – How to Fix split is not a function Error in JavaScript?

How to Fix split is not a function Error in JavaScript

Javascript split is not a function: When we call the split() method on a value that is not of type string, we get the “split is not a function” error.

To resolve the error, convert the value to a string using the toString() function before calling the split method, or only call the split method on strings.

Let us see the examples to know how this error occurs and try to fix them.

index.js:

// Create a date object and store it in a variable
const gvn_str = new Date();

// Apply split() function on the date object and store it in a variable.
// Here it throws an error since split() function cannot be applied on an object
// It must be used only on strings
const result = gvn_str.split(' ');

Output:

const result = gvn_str.split(' ');
^

TypeError: gvn_str.split is not a function
at Object.<anonymous> (/tmp/ER7rLDlJor.js:4:24)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

Here we called the String.split() method on an object and returned an error.

To fix the problem, only use the split() method on strings. Most values can be 
converted to strings using the function toString()  method.

Using toString() Method for Conversion

// Create a Date object using the new keyword and 
// store it in a variable
const gvn_string = new Date();
// Print the type of above variable using the typeof property
console.log(typeof gvn_string);

// Convert the above Date object to string using the 
// toString() method and split it based on '' using the 
// split() function
const rslt = gvn_string.toString().split(' ');
// Print the above result
console.log(rslt); 

Output:

object
[ 'Sat', 'Jun', '11', '2022', '18:50:00', 'GMT+0000', '(GMT)' ]

Explanation:

We were able to call the split() function on the date object since the 
toString() method converted this date object to a string.

Using Ternary Operator to Check if it is a String and do Conversion if Necessary

Split is not a function: Alternatively, before executing the split() method, you can check to see if the value is a string.

Example1: index.js

// Give some random value as static input and store it in 
// a variable
const gvn_str = 50;
// Check if the type of above variable value is a string using
// the ternary operator. 
// If it is a string then split it based on ' ' using the 
// split() function else print 'Not a String'
const rslt = typeof gvn_str === 'string' ? gvn_str.split(' '): 'Not a String';
// Print the above result
console.log(rslt); 

Output:

Not a String

Example2: index.js

// Give some random value as static input and store it in 
// a variable
const gvn_str = "Hello this is Btechgeeks";
// Check if the type of above variable value is a string using
// the ternary operator. 
// If it is a string then split it based on spaces(' ') using
// the split() function else print 'Not a String'
const rslt = typeof gvn_str === 'string' ? gvn_str.split(' '): 'Not a String';
// Print the above result
console.log(rslt); 

Output:

[ 'Hello', 'this', 'is', 'Btechgeeks' ]

Explanation:

  • To determine whether the gvn_str variable contains a string, we utilized a ternary operator.
  • If it satisfies the condition, it returns the value to the left of the colon(:) otherwise, it returns the value to the right.
  • If it is a string then split it based on spaces(‘ ‘) using the split() function else print ‘Not a String’.
  • If the value is an object, there’s a significant possibility you’re forgetting to access a specific property on which the split() method must be called.

Solve – Cannot find module ‘express’ error in Node.js

Solve - Cannot find module 'express' error in Node.js

Cannot find module ‘express’: Install the package by running the command npm install express in the root directory of your project to resolve the error “Cannot find module ‘express’.”

Run npm init -y to generate a package.json file if you don’t already have one.

Output of npm init -y:

Wrote to C:\Users\cirus\Desktop\Btechgeeks\package.json:

{
"name": "btechgeeks",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}

index.js:

const express =require('express');

const app = express();
const port = 5000;

app.get('/', (req, res) => {
  res.send('Hello This is BTechgeeks!');
});

app.listen(port, () => {
  console.log(`Your app is listening on port ${port}`);
});

Now if we run the above index.js then we get,

PS C:\Users\cirus\Desktop\Btechgeeks> node index.js
node:internal/modules/cjs/loader:936
throw err;
^

Error: Cannot find module 'express'
Require stack:
- C:\Users\cirus\Desktop\Btechgeeks\index.js
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
at Function.Module._load (node:internal/modules/cjs/loader:778:27)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (C:\Users\cirus\Desktop\Btechgeeks\index.js:1:16)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'C:\\Users\\cirus\\Desktop\\Btechgeeks\\index.js' ]
}

i.e Cannot find module ‘express’ error.

Cannot find module ‘express’ error in Node.js Fix:

Node cannot find module express: Below are the ways to fix the above error:

Fix #1: Installing express using npm

error: cannot find module ‘express’: Open your terminal in your project’s root directory (the one that contains your package.json file) and perform the following command to ensure you have express installed:

npm install express

Output:

PS C:\Users\cirus\Desktop\Btechgeeks> npm install express

added 57 packages, and audited 58 packages in 3s

7 packages are looking for funding
run `npm fund` for details

found 0 vulnerabilities

The error should go away once you’ve installed express.

Now when we run index.js we get:

Output(index.js):

Your app is listening on port 5000

Fix #2: Deleting node modules

If the error persists, consider deleting your node modules directory and the package-lock.json file, then re-running npm install and restarting your IDE.

Run the following commands in your terminal in the root directory of your project.

// deleting node_modules and package-lock.json
rm -rf node_modules package-lock.json

// installing all packages in package.json
npm install

If the error persists, be sure to restart your IDE. VSCode has a tendency to crash, and a reboot can occasionally fix the problem.

If you experience any issues after running these commands, consider deleting the node modules and package-lock.json files from the root directory of your project manually.

If a permissions problem occurs, try running the command with sudo, such as

sudo npm install

The express package should now be able to be imported and used.

Now when we run index.js we get:

index.js:

const express =require('express');

const app = express();
const port = 5000;

app.get('/', (req, res) => {
  res.send('Hello This is BTechgeeks!');
});

app.listen(port, () => {
  console.log(`Your app is listening on port ${port}`);
});

Output(index.js):

Your app is listening on port 5000

After installing express our package.json looks like this:

{
  "name": "btechgeeks",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.1"
  }
}

It contains express in dependencies.

Make sure to include the express package to your dependencies object rather than devDependencies.
You can try adding the line manually and re-running npm install.

Command:

npm install

Output:

PS C:\Users\cirus\Desktop\Btechgeeks> npm install

added 57 packages, and audited 58 packages in 2s

7 packages are looking for funding
run `npm fund` for details

found 0 vulnerabilities

missing ) after argument list javascript – How to Solve SyntaxError: missing ) after argument list in JavaSCript?

How to Solve SyntaxError missing ) after argument list in JavaSCript

missing ) after argument list javascript: In JavaScript, the “missing) after argument list” error occurs when we make a syntactic error when calling a function, such as forgetting to split its arguments by a comma. To resolve the error, ensure that any syntax errors in the arguments list of the function invocation are corrected.

Below are the examples where this “SyntaxError: missing ) after argument list” occurs.

Case#1: Forgetting to use comma(,) or ‘+’ to separate the values

// Solving SyntaxError: missing ) after argument list Error

// Here we forgot to use comma(,) or + to separate the values 
// while printing it on the console which leads to 
// SyntaxError: missing ) after argument list error
console.log('x' 'y'); 

Output:

console.log('x' 'y'); 
^^^

SyntaxError: missing ) after argument list
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

Here we forgot to use comma(,) or + to separate the values while printing it
on the console which leads to // SyntaxError: missing ) after argument list error

Case#2: Printing ${} without the template strings

// Here we are printing ${} without the template strings 
// on the console.
// Hence SyntaxError: missing ) after argument list
console.log('The Metadata is:' + ${string_data});

Output:

console.log('The Metadata is:' + ${string_data}); 
^

SyntaxError: missing ) after argument list
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

Here we are printing ${} without the template strings on the console leading to an error

Case#3: When there is no comma(,) between the arguments

// Here there is no comma(,) between arguments for separating them
// so, SyntaxError: missing ) after argument list occurs
mul(3 2);

Output:

mul(3 2); 
^

SyntaxError: missing ) after argument list
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

Here there is no comma(,) between arguments for separating them.
so, SyntaxError: missing ) after argument list occurs

Case#4:

// Initialize the variables 
const EmpName = 'Nick';
const EmpId = 2354;
// Here there is no comma(,) between arguments
// so, SyntaxError: missing ) after argument list occurs
console.log(EmpName EmpId);

Output:

console.log(EmpName EmpId); 
^^^^^^^

SyntaxError: missing ) after argument list
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Case#5: When we forgot to close the bracket ) while calling a function

// Here we forgot to close the bracket ) while calling a function
// Hence SyntaxError: missing ) after argument list occurs
console.log("x", "y"

Output:

console.log("x", "y" 
^^^

SyntaxError: missing ) after argument list
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Solving SyntaxError: missing ) after argument list in JavaSCript

In case#1, the”missing ) after argument list” error is produced when a comma or the addition operator (+) is not added between the parameters in a function.

To resolve the error, ensure that any syntax errors in the parameter list of your function calls are corrected.

// Here we are using '+' operator for separation
console.log('welcome to ' + ' Btechgeeks');

// Here we are using comma(,) to separate the arguments
console.log('Btechgeeks'.slice(0, 3)); 

Output:

welcome to Btechgeeks
Bte

Delimiting a string with backticks (“)

Missing after argument list javascript: If you have a string that contains both double and single quotes, use a template literal, which is a string delimited by backticks (“).

// This is WRONG approch
const gvn_string1 = 'They\'re playing';

// Write the string as here while using both double and single quotes
const gvn_string2 = "They're playing"

// Or we can also write in this way using backticks(``)
const gvn_string3 = `They're playing`

Because template literals enclose the string with backticks, we can use both single and double quotes in the string’s contents without getting errors or having to escape any single or double quotes.

Conclusion

  • To resolve the “missing) after argument list” problem, ensure that any syntax errors are corrected when calling functions.
  • When the function is invoked, the error is frequently issued if the function arguments are not separated by a comma or the addition operator.

 

 

Foreach is not a function javascript – How to Fix forEach is not a function Error in JavaScript?

How to Fix forEach is not a function Error in JavaScript

Foreach is not a function javascript: When we call the forEach() method on a value that is not of the type array, Map, or Set, we get the "forEach is not a function" error. To fix the problem, only use the forEach function on arrays, Map, or Set objects.

Let us see the examples to know how this error occurs.

index.js:

// Get all the boxes from the html script containing class name box
const boxes = document.getElementsByClassName('box');
console.log(boxes); // [div.box, div.box, div.box]

// Here we get Uncaught TypeError: boxes.forEach is not a function error
boxes.forEach(element => {
  console.log(element);
});

// create an empty object
const object = {};

// Uncaught TypeError: obj.forEach is not a function
object.forEach(i=> {
  console.log(i);
});

Explanation:

In the first example, we use the getElementsByClassName function to obtain an array-like
object, then tried to call the Array.forEach() method on it and obtain an error.

The second example invokes the forEach method on an object, and we get an error 
because it isn't implemented on objects.

Fixing forEach is not a function Error in JavaScript

//  with DOM elements
const boxes = document.getElementsByClassName('box');
console.log(boxes); // Output => [div.box, div.box, div.box]

Array.from(boxes).forEach(element => {
  console.log(element);
});

// Create an object which contains some random key value pairs
const object = {EmpCountry: "India", EmpName: "Alex"};
// Iterate in the above object using the forEach() loop
Object.keys(object).forEach(key => {
  console.log(key); // Output=> "EmpCountry", "EmpName"
  console.log(object[key]); // Output = > "India", "Alex"
});

Output:

[div.box, div.box, div.box]
EmpCountry
India
EmpName
Alex

Before calling the forEach() method, we utilized the Array.from() method to convert the array-like object to an array.

In the second example, we used the Object.keys() function to obtain an array of the object’s keys before calling/invoking the forEach() method for iterating over the array

Alternatively, before invoking the forEach method, you can check to see if the value is of the correct type.

index.js:

// Take a variable and initiaize its value with null
const gvn_arry = null;

// Check if the type of above variable is an array using the 
// isArray() function function and if conditional statement
if (Array.isArray(gvn_arry)) {
  // If it is an array, then iterate over each element of
  // of an array using the forEach() loop and print it
  gvn_arry.forEach(i => {
    console.log(i);
  });
}

Output:


Explanation:

Here it prints nothing since the given variable gvn_arry is not an array.
It is initialized with a null value.

To determine whether the gvn_arry variable stores an array, we utilized the Array.isArray() method. The forEach method is then only called if the variable contains an array.

If the “forEach is not a function” issue continues,  print the value that you are calling the forEach method on using console.log  and ensure it’s an array, Map, or Set depending upon the use case.

If the value is retrieved/fetched from a remote server, ensure that the JSON has been parsed to a native JavaScript array before calling the forEach method.

Example2: index.js

// Give the array as static input and store it in a variable
const gvn_arry = [1, 3, 6];

// Check if the type of above variable is an array using the 
// isArray() function function and if conditional statement
if (Array.isArray(gvn_arry)) {
  // If it is an array, then iterate over each element of
  // of an array using the forEach() loop and print it
  gvn_arry.forEach(i => {
    console.log(i);
  });
}

Output:

1
3
6

Javascript calculate percentage – How to Calculate Percentage Between Two Numbers in JavaScript?

How to Calculate Percentage Between Two Numbers in JavaScript

Javascript calculate percentage: To compute the percentage of two numbers, divide one by the other and multiply the result by 100,

For Example:

Here Let us calculate 20% of 400 as follows:

(80 / 400) * 100.

This displays what percentage of the first number is of the second, in this case, 80 is 20% of 400.

Calculating Percentage Between Two Numbers in JavaScript

index.js:

Approach:

  • Create a function say caculatePercentage() which accepts two numbers as arguments and returns the percentage of the first number with the second number.
  • Pass two numbers as arguments to the above caculatePercentage() function and print the result
  • Here it indicates 80 is 20% of 400
  • Similarly, check for the other numbers and print the result
  • Rounding the percentage up to 3 decimal places using the toFixed() function.
  • The Exit of the Program.

Below is the implementation:

// Create a function say caculatePercentage which accepts 
// two  numbers as arguments and returns the percentage of 
// first number with the second number
function caculatePercentage(number1, number2) {
  return (number1 / number2) * 100;
}

// Pass two numbers as arguments to the above
// caculatePercentage function and print the result
// Here it indicates 80 is 20% of 400
console.log(caculatePercentage(80, 400)); 

// Similarly check for the other numbers and print the result
console.log(caculatePercentage(40, 150)); 

// Rounding the percentage upto to 3 decimal places using the toFixed() function
console.log(caculatePercentage(50, 200).toFixed(3));

Output:

20
26.666666666666668
25.000

Calculate Percentage Increase Or Decrease

Formula:

((number1 - number2) / number2) * 100

Approach:

  • Create a function say percentIncreaseOrDecrease which accepts two numbers as arguments and returns the percentage increase or decrease
  • Pass two numbers as arguments to the above percentIncreaseOrDecrease function and print the result
  • Here it indicates that 150 is 87.5% increase from 80.
  • Similarly, check for the other numbers and print the result
  • Here it indicates that 60 is 50% decrease from 120.
  • The Exit of the Program.

Below is the implementation:

// Create a function say percentIncreaseOrDecrease which//accepts two  numbers as arguments and returns the //percentage increase or decrease
function percentIncreaseOrDecrease(number1, number2) {
  return ((number1 - number2) / number2) * 100
}
 // Pass two numbers as arguments to the above
 // percentIncreaseOrDecrease function and print the result
 // Here it indicates 150 is 87.5% increase from 80
 console.log(percentIncreaseOrDecrease(150, 80));
 //Similarly check for the other numbers and print the result
 //Here it indicates 60 is 50% decrease from 120
 console.log(percentIncreaseOrDecrease(60, 120));

Output:

87.5
-50

toFixed() Function:

The toFixed() method formats the number after the decimal to the specified 
number of digits and rounds it if necessary.
  • It should be noted that the toFixed method returns a string rather than a number.
  • If the number has no decimal places, it is padded with zeros.

Using toFixed() Function for padding with zeros if has no decimal places

// Calculate the percentage of two numbers using the above
// given mathematical formula and store it in a variable
const rslt_percent = (100 / 200) * 100;
// Print the percentage of first number with the second
console.log(rslt_percent); 

// Round Off the aboveresult percentage to 3 decimal places 
// using the toFixed() function and store it in another variable
const fixed_percent = rslt_percent.toFixed(3);
// Print the percentage after rounding off to 3 decimals
// Here the result 50.000% is padded with 3 zeros since there are no decimal values for it
console.log(fixed_percent); 

Output:

50
50.000

Referenceerror document is not defined node js – How to Fix ReferenceError document is not defined in JavaScript?

How to Fix ReferenceError document is not defined in JavaScript

Referenceerror document is not defined node js: The “ReferenceError: document is not defined” error can occur for a variety of factors, including:

  • When you use the document in Node.js.
  • While using the document on the server (example:- server-side rendering in Next.js).
  • When misspelled the document global variable (must be all lowercase).

NOTE:

Because Node.js is a server-side runtime and does not provide a browser environment, 
we cannot use the document variable in Node.

Fixing the ReferenceError: document is not defined

Document not defined javascript: If your browser displays the “ReferenceError: document is not defined” issue, try moving your JavaScrpit script tag to the bottom of the body tag as shown below:

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
     <!-- write your HTML here -->
     <p>Hello this is Btechgeeks</p>

    <!-- adding type as module in the script   -->
    <script type="module" src="index.js"></script>
  </body>
</html>

Output:

Hello this is Btechgeeks

In our JavaScript code, we can now use the syntax of the ES6 module.
It’s important to remember that any JavaScript files that use the syntax of the ES6 module must have the type attribute set to the module.

You may have add-ons that are executed before the DOM is created.

If you’re using Next.js and want to know if you’re in the browser (can use document) or on the server (can’t use document), you can do so as follows:

index.js: (for undefined)

// Check if the type of window is not equal to 'undefined' using 
// the if conditional statement 
if (typeof window !== 'undefined') {
  // If it is true then print 'we are on the browser'
  console.log('Hey!!! we are on the browser')
} else {
  // Else print ' we are on the server'
  console.log('Hey!! we are on the server')
}

Output:

Hey!! we are on the server

Explanation:

  • Here we checked if the global window variable does not have a type of ‘undefined’.
  • We are on the browser if the window global is defined, and we can use the document variable.

If we write the same code in the browser then the type of window returns an object.

Input:

console.log(typeof window)

Output:

object

Handling ReferenceError: document is not defined in JS

Referenceerror document is not defined: To fix the “ReferenceError: document is not defined” error, simply use the document global variable on the browser.

The variable is related to the Document Object Model, which represents a browser-loaded web page that cannot be utilized on the server-side (for example -in Node.js).

 

Invalid shorthand property initializer – How to Solve Invalid shorthand property initializer Error in JavaScript

How to Solve Invalid shorthand property initializer Error in JavaScript

What is an Invalid shorthand property initializer Error?

Invalid shorthand property initializer: When we use an equal sign(=) instead of a colon(:) to separate the values in an object, we get the “Invalid shorthand property initializer” error. To correct the mistake, put colons between the keys and values of an object when declaring it.

For example:

const object =  { EmpId:2122, EmpName:'John' }
console.log(object);

Output:

{ EmpId: 2122, EmpName: 'John' }

When Does This Error Occur?

// Here we are giving equal sign(=) instead of a colon(:) 
// between the keys and values of an object
// Hence  Invalid shorthand property initializer error occurs
const object =  { EmpId = 2122, EmpName = 'John' }
console.log(object);

Output:

const object =  { EmpId = 2122, EmpName = 'John' }
^^^^^^^^^^^^

SyntaxError: Invalid shorthand property initializer
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

Explanation:

Here we are giving equal sign(=) instead of a colon(:) between the keys and values of an object 
Hence Invalid shorthand property initializer error occurs

Handling the Invalid shorthand property initializer Error

Uncaught syntaxerror invalid shorthand property initializer: To Handle this see the below code as explained in the above concept:

For example:

const object =  { EmpId:2122, EmpName:'John' }
console.log(object);

Output:

{ EmpId: 2122, EmpName: 'John' }

It’s worth noting that we used an equal sign(=) to separate the object’s key-value pairs.

A colon(:) should be used to separate key-value pairs when declaring an object.

Using equal sign(=) to Add a New Key-Value Pair

If you wish to add a new key-value pair to the object, however, you must use the equal sign(=).

Approach:

  • Give the object containing key-value pairs and store it in a variable
  • Add a new key-value pair to the above object using the equal sign(=)
  • Print the object after adding a key-value pair to the object on the console.
  • The Exit of the Program.

Below is the implementation:

// Give the object containing key-value pairs and store it in a variable 
const object = { EmpId:2122, EmpName:'John' }
// Add a new key-value pair to the above object using the 
// equal sign(=)
object.EmpSalary = 50000;
// Print the object after adding a key-value pair on the console
console.log(object);

Output:

{ EmpId: 2122, EmpName: 'John', EmpSalary: 50000 }

Using the Bracket Notation instead of Dot Notation

When adding a key-value pair to an object, use bracket notation rather than dot notation if the key contains spaces, begins with a number, or contains a special character.

Example:

Approach:

  • Give the object containing key-value pairs and store it in a variable
  • Add a new key-value pair to the above object using the bracket notation instead of dot notation(.)
  • Print the object after adding a key-value pair to the object on the console.
  • The Exit of the Program.

Below is the implementation:

// Give the object containing key-value pairs and store it in a variable
const object = { EmpId:2122, EmpName:'John' }
// Add a new key-value pair to the above object using the 
// bracket notation instead of dot notation(.)
object['Employee Address'] = 'Gachibowli, Hyderabad';
// Print the object after adding a key-value pair on the console
console.log(object);

Output:

{ EmpId: 2122,
EmpName: 'John',
'Employee Address': 'Gachibowli, Hyderabad' }

Conclusion:

To avoid the “Invalid shorthand property initializer” problem, use a colon instead of an equal sign between the key-value pairs of an object literal, such as

const object =  { EmpId:2122, EmpName:'John' }