What is i++ in javascript – JavaScript Increment ++ and Decrement —

What is i++ in javascript: The increment and decrement operators in JavaScript will add one (+1) or subtract one (-1), respectively, to their operand, and then return a value.

Increment & Decrement operators

SYNTAX: Consider ‘x’ to be a variable:

Then,
Increment:  — x++ or ++x
Decrement:  — x– or –x

#NAME?: In the syntax we can see that the — and ++ have been used before and after the variable, so in terms of code, it might look similar to :

// Increment
let a = 1;
a++;
++a;
// Decrement
let b = 1;
b--;
--b;

Using ++/– Before the Variable

i++ javascript: If you want to make the variable increment and decrement before using it, this is the way it has to be done, and in terms of code and example it is demonstrated below.

// Increment
let a = 1;
console.log(++a);    // 2
console.log(a);      // 2
// Decrement
let b = 1;
console.log(--b);    // 0
console.log(b);      // 0

As you can see, that the variable have been incremented/decremented before logging out the result in the first line.

Using ++/– After the Variable

x++ javascript: If you want to make the variable increment and decrement after using it, this is the way it has to be done, and in terms of code and example it is demonstrated below.

// Increment
let a = 1;
console.log(a++);    // 1
console.log(a);      // 2
// Decrement
let b = 1;
console.log(b--);    // 1
console.log(b);      // 0

As you can see, that the variable have been incremented/decremented after logging out the result in the first line.

Conclusion:

Hopefully, my article was helpful, and by now you are clear how the increment and decrement operators works in any programming language.

 

Typeerror failed to fetch – How to Fix TypeError: Failed to fetch and CORS in JavaScript?

How to Fix TypeError Failed to fetch and CORS in JavaScript

Typeerror failed to fetch: The “TypeError: Failed to fetch” error can arise for several reasons:

  • Passing an incorrect or incomplete URL to the fetch() method.
  • The server to which you are making a request does not return the correct CORS headers.
  • The URL has an incorrect protocol.
  • Passing a wrong method or headers to the fetch() method.

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

async function getEmployDetails() {
  try {
    // Here we are passing incorrect/incomplete URL.
    // Hence TypeError: Failed to fetch occurs
    const url_response = await fetch('https://jhgdwyhnzlk.com/udybsjhdir');
    // check if the status of url response is not okay (failed)
    if (!url_response.ok) {
      throw new Error(`Error! status: ${url_response.status}`);
    }
    // if the response is okay then apply the json() function on url response
    const output = await url_response.json();
    // return the result(response) from the url
    return output;
  } catch (error) {
    // If any error occurs then in the catch block print it
    console.log(error);
  }
}
// Call the getEmployDetails() function
getEmployDetails();

Explanation:

Since the URL we passed to the fetch method was incorrect, we received two errors:

  • CORS: No ‘Access-Control-Allow-Origin’ header is present on the requested resource
  • TypeError: Failed to fetch

Fixing “TypeError: Failed to fetch” Error

Typeerror: failed to fetch: Check that the URL that you are passing to the fetch() method is complete and valid. Do the following for this:

  • Include the protocol, for example, https:// or http:// if you are testing on localhost without an SSL certificate.
  • The URL path must be correct, for example, /btechgeeks.
  • The HTTP method must be appropriate for the path specified.
  • If you misspell any of the configuration, such as a property in the headers object or an HTTP method, you will receive an error.

To resolve the "TypeError: Failed to fetch," ensure that the correct configuration is sent to the fetch method, including the URL, HTTP method, headers, and that the server to whom you are making a request is setting the necessary CORS headers with the response.

// 
async function getWebsiteDetails() {
  try {
    // Pass the url as an argument to the fetch() function
    const url_response = await fetch('https://randomuser.me/api/', {
      // Add request method
      method: 'GET',
      // Add headers of the request using the accept
      headers: {
        accept: 'application/json',
      },
    });
    // check if the status of url response is not okay (failed)
    if (!url_response.ok) {
      throw new Error(`Error! status: ${url_response.status}`);
    }
    // if the response is okay then apply the json() function on url response and store the response in a variable
    const output = await response.json();
    // return the result(response) from the url
    return output;
  } catch (error) {
    // If any error occurs then in the catch block print it
    console.log(error);
  }
}
// Call the getEmployDetails() function
getWebsiteDetails();

NOTE:

If we perform a POST, PUT, or PATCH, make sure the body is passed to the JSON.stringify()
method in the fetch method call.

If the configuration that you pass to the fetch method is correct, check to see if your server is sending the correct/valid CORS headers in the response.

Along with the response, the server must set the following CORS headers:

# Paste your domain/server link below like http://localhost:5000
Access-Control-Allow-Origin: http://example.com

Access-Control-Allow-Methods: POST, PUT, PATCH, GET, DELETE, OPTIONS

Access-Control-Allow-Headers: Origin, X-Api-Key, X-Requested-With, Content-Type, Accept, Authorization

Depending on your use case, you may need to adjust the values, by opening the Network tab in your browser, clicking on the request, and seeing if your server is setting these CORS-related headers.

The headings are as follows:

Access-Control-Allow-Origin: It specifies which origins are permitted/allowed to make requests to the server.

Access-Control-Allow-Methods: It specifies which HTTP methods the origins are permitted to use when making requests to the server.

Access-Control-Allow-Headers: It specifies which HTTP headers origins are permitted to use when making requests to the server.

 

Fix – Unexpected token u in JSON at position 0 Error in JS

Fix - Unexpected token u in JSON at position 0 Error in JS

Unexpected token b in json at position 0: When we use the JSON.parse or $.parseJSON methods with an undefined value, we get the “Unexpected token u in JSON at position 0” error. Before parsing the value you’re trying to parse, inspect it to ensure it’s a proper JSON string.

Below are the examples where this “Uncaught SyntaxError: Unexpected end of Input” occurs and how to fix that.

Fix – Unexpected token u in JSON at position 0 Error in JS

Cause 1: Undefined Values

// SyntaxError: Unexpected token u in JSON at position 0
// Here we are passing undefined value to the parse() function and apply it on the JSON and print it using console.log()
console.log(JSON.parse(undefined));

// SyntaxError: Unexpected token u in JSON at position 0
// Here we are passing undefined value to the parseJSON() function and getting its value using $ and print it using console.log()
console.log($.parseJSON(undefined));

Output:

undefined:1
undefined
^

SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at Object.<anonymous> (C:\Users\cirus\Desktop\pyrebase4\index.js:3:18)
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)
at node:internal/main/run_main_module:17:47

When an undefined value is passed to the JSON.parse method, it is converted to a string, with the letter u as the first character, indicating the error message.

When executing JSON.parse, the error “Unexpected token u in JSON at position 0” can happen for a variety of reasons:

  • A non-existent property on an object is being referenced.
  • An empty response was returned by your server or local storage call.
  • You’re retrieving data as soon as the page loads, resulting in a race issue.

Fix 1: Using try-catch block

You can put the JSON.parse call in a try/catch to ensure that you handle the error.

//try catch block
try {
    // pass the undefined value as an argument to the parse() function of the JSON and store this result in a variable
  const reslt = JSON.parse(undefined);
} catch (err) {
  // Print the error message in catch block using the message attribute
  console.log('Error: ', err.message);
}

Output:

Error: Unexpected token u in JSON at position 0

The try block attempts to execute the block of statements included within it, but when an error occurs, the catch block is invoked, and the error message is printed in the catch block.

Note:

JSON values must all be of the string type. Although not all strings are valid JSON, all JSON values have a string type.

Cause #2: Incorrect Spellings

When you try to parse a property that doesn’t exist, you’ll get this error. This is usually due to a mistake or referring the incorrect property (one that is not parsable).
Have you noticed the mistake? We’re trying to parse my.data, but we’re referring a non-existent property, my.date, which is undefined, owing to a typo. That there  is a “unexpected token u in JSON at position 0”

Another less typical cause of this problem is because the JSON is not received. This could be due to a client-side script that ignores errors and sends requests when they aren’t supposed to be sent. You’ll get an error each time this happens because there’s no data to pass to the request.

// Creating sample Object
my = {}
//sample json object
my.dataVal = '{"website":"BTechGeeks"}';
// Pass the above dataVal as an argument to the parse() function
JSON.parse(my.dateVal)

Output:

undefined:1
undefined
^

SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at Object.<anonymous> (C:\Users\cirus\Desktop\pyrebase4\index.js:5:6)
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)
at node:internal/main/run_main_module:17:47

Fix #2: Giving Correct Spellings

// Creating sample Object
my = {}
//sample json object
my.dataVal = '{"website":"BTechGeeks"}';
// Pass the above dataVal as an argument to the parse() function
console.log(JSON.parse(my.dataVal))

Output:

{ website: 'BTechGeeks' }

Fix #3: Removing unwanted white Spaces

Remove any white space that could cause your data to become corrupted. Here’s an example:

//removing unwanted whitespaces using the trim() function
dataValues = dataValues.trim(); 
result= JSON.parse(dataValues );

Fix #4: Clearing local storage

Clear local storage (browser console -> localStorage.clear()) and try again if you’re using it to store your info (remember to rewrite your data if this was done manually).

localStorage.clear()

 

Background image opacity without affecting text – How to Change Background Image Opacity in CSS without Affecting Text | HTML/CSS

Background image opacity without affecting text: In today’s generation, when making a website, we need to have all the visual effects we can induce in it to make it look more presentable and pleasing to the eyes of all the users who access it. So here I will be writing a blog for developers who are looking to implement background image transparency using CSS and HTML.

CSS Background Opacity Without Affecting the Child Elements

CSS background image opacity without affecting text: We all like learning how to make new designs using CSS, but still, it is recommended to know some basics of CSS and HTML beforehand before progressing further towards our blog.

NOTE:

There is no CSS property that can be used to change the opacity ONLY of the background image.

background: url('img.jpeg');
opacity: 0.5;

The result will be similar to : (faded image)

If we try to use it then it produces blurred unpleasant views which are very displeasing to look at and not production ready. So to overcome it we have to manipulate it indirectly using other CSS properties described below. From the next steps we start designing the HTML and implementing the CSS on how we should do it.

Skelton HTML

Background image opacity without affecting text: First we shall create a basic HTML file where the CSS styling will be implemented, a skeleton design of a HTML file is more than enough to cater our needs. I have made a section to keep the box/card component which is to be displayed on the page.

<section>
      <div class="box">
        <h2>CSS Transparent Background</h2>
        <p>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
          eiusmod tempor incididunt ut labore et dolore magna aliquaenim ad
          minim veniam, quis nostrud exercitation ullamco laboris nisi ut
          aliquip ex ea commodo consequat. Duis aute irure dolor in
          reprehenderit in voluptate velit esse cillum dolore eu fuginulla
          pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
          culpa qui officia deserunt mollit anim id est laborum.
        </p>
      </div>
  </section>

Section Styling

section {
  padding: 0, 100px;
  background: url("//some_image");
  height: 100vh;
  /* opacity: 0.25; */
  display: flex;
  justify-content: center;
  align-items: center;
}

Here we could have used opacity property to make it look opaque but we all have seen the discrepancies that it causes while using it directly (refer NOTE). We have made it a flex and justify-content: centre to highlight it with a background.
Moving on to the next section.

Box/Card Component Styling

.box {
  position: relative;
  max-width: 600px;
  padding: 50px;
  /* background: url("img.jpeg"); */
  /* opacity: 0.75; */
  background: rgba(255, 255, 255, 0.2);
  box-shadow: 12px 2px 30px 10px rgba(0, 0, 0, 0.77);
  -webkit-box-shadow: 12px 2px 30px 10px rgba(0, 0, 0, 0.77);
  -moz-box-shadow: 12px 2px 30px 10px rgba(0, 0, 0, 0.77);
}

.box h2 {
  margin: 0 0 20px;
  padding: 0;
  font-size: 48px;
  text-transform: uppercase;
  color: #044463;
}

The box-shadow property one or more shadows to the element.
The -WebKit-box-shadow applies a drop shadow effect to the border-box/card of an object.

In the .box section of the CSS, we use the transparency effect to counter the opacity effect of the overall background to make it look readable.

Conclusion

CSS background opacity without affecting text: This is, in my opinion, one of the best solutions to have a work around for not having a dedicated property for background image transparency (and or opacity).

BONUS: we also learned the box-shadowing property in CSS.

Window is not defined javascript – How to Fix ReferenceError window is not defined in JavaScript?

How to Fix ReferenceError window is not defined in JavaScript

Window is not defined javascript: The “ReferenceError: window is not defined” error can occur for a variety of causes, including:

  • When you the windowin Node.js.
  • Using the windowon the server (for example server-side rendering in Next.js).
  • When the windowglobal variable is misspelled. It must be all lowercase.

Here the windowrepresents a window containing a DOM document and is only available in the browser.

NOTE:

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

Fixing ReferenceError window is not defined in JavaScript

Example: index.html

Referenceerror: window is not defined: If your browser displays “ReferenceError: window is not defined,” try moving your JS <script/> tag to the bottom of the <body/>tag:

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

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


    <!--Moving the script tag at bottom of body -->
    <!-- Adding type as module in the script   -->
    <script type="module" src="index.js"></script>
  </body>
</html>

Output:

Hello this is Btechgeeks
  • You may have addons that are executed before the DOM is created.
  • The window global variable denotes the window in which the script is being run (browser side).

To know Whether you’re in the Browser or Server

Javascript window is not defined: If you’re using React.js or Next.js and need to know if you’re in the browser (can use window) or on the server (can’t use window), perform the following:

// 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')
  // We can use 'window' here
} else {
  // Else print ' we are on the server'
  console.log('Hey!! we are on the server')
  // We must NOT use window here
}

Output:

Hey!! we are on the server

Explanation:

  • Here we checked if the global window variable has a type other than undefined.
  • If we have the window global defined, we are on the browser and can use the window 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

NOTE:

  • To fix the “ReferenceError: window is not defined” error, simply use the window global variable on the browser.
  • The variable represents a DOM document in a window and cannot be used on the server-side (example in Node.js).

Using global in Node.js

Referenceerror: window is not defined nextjs: If you need to define global variables in Node.js, use global rather than window

index.js:

// Declare a variable using global
global.data = 'Hello Btechgeeks';

We now use the above variable in another file:

another_File.js:

// Import the above index.js file using the import keyword
import './index.js';
// Print the same variable(global.data) which is present in index.js file
// Here it returns 'Hello Btechgeeks' of index.js
console.log(global.data); 


Output:

Hello Btechgeeks

Another Simple Method

Window is not defined: However, it is far more convenient to just export a variable from the index.js file and import it as needed.

index.js:

// Declare a const and export it using the export keyword
export const data = 'Hello Btechgeeks';

We now import the above same variable(data) into another file.

another_File.js:

// Declare a const variable and export it using the export keyword
export const data = 'Hello Btechgeeks';

// Import the variable present in the index.js file(data)
// using the import keyword
import {data} from './index.js';
// print the variable of index.js file 
// Here it returns 'Hello Btechgeeks' of index.js
console.log(data); 

Output:

Hello Btechgeeks

NOTE:

Using this export is a far better, and more efficient approach than defining global variables.

Uncaught syntaxerror: unexpected token ‘export’ – How to Fix Unexpected token ‘export’ Error in JavaScript

How to Fix Unexpected token 'export' Error in JavaScript

uncaught syntaxerror: unexpected token ‘export’: The error “Uncaught SyntaxError Unexpected token ‘export'” happens for two reasons:

  • In a Node.js application, using the ES6 Module syntax without specifying a type to module in package.json.
  • Using the ES6 Module syntax in a script without setting the script tag type to module.

Let us now see an example to understand how the Error occurs in the Node.js application.

index.js:

// Create a class with some parameterized constructor
export class Employ {
  constructor(hello) {
   // Inside the constructor initialize the variable with the value.
    this.hello = hello;
  }
}

Output:

export class Employ {
^^^^^^

SyntaxError: Unexpected token export
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)

Set the type property in your package.json file to module to resolve the “Uncaught SyntaxError Unexpected token ‘export'” error.

The Files ending with a .js extension are loaded as ES6 modules when the nearest package. json has a type field set to module.

If you don’t already have a package.json file, use the below command to create one.

npm init -y

Run the following command from your terminal in the root directory of your application.

shell:

npm init -y

In the package.json file, now set the type property to module

package.json:

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

You can now use ES6 module syntax in your Node.js application.

index.js:

// Create a class with some parameterized constructor
export class Employ {
  constructor(hello) {
   // Inside the constructor initialize the variable with the value.
    this.hello = hello;
  }
}

Here is another file that imports the above class.

anotherFile.js:

// Import the Employ class from the anotherFile.js using 
// the import keyword
import {Employ} from './anotherFile.js';
// Create an object for the above Employ class by passing 
// some random name as an argument to it and store it in a variable
const e = new Employ('Nick');
// Print the above object
console.log(e);

By setting the type property to module in your project’s package.json file allows us to use ES6 modules in our Node.js application.

If you don’t want to set the type property in your package.json to module, you can use the older CommonJS syntax.

Refactor your code to use the module CommonJS syntax i.e, given below to resolve the “Uncaught SyntaxError Unexpected token ‘export'” issue.

exports = {num}; rather than export num = 500;

index.js:

// Create a class with some parameterized constructor
export class Employ {
  constructor(hello) {
   // Inside the constructor initialize the variable with the value.
    this.hello = hello;
  }
}

// Here we use module.exports rather than export to export 
// the Employ class
module.exports = {
  Employ,
};

Now, the variables can then be imported into another file as follows:

anotherFile.js:

// Import the Employ class from the index.js file using the 
// require() function and store it in a variable
const {Employ} = require('./index.js');

Explanation:

  • The issue arises because we are not yet allowed to utilize the ES6 Module syntax in Node.js.
  • There are multiple solutions, such as using babel to transpile our ES6 code to an earlier/older version of JavaScript or simply refactoring our code to CommonJS syntax.

Fixing Unexpected token ‘export’ Error in JavaScript

Syntaxerror: unexpected token export: Set the type of your <script/> tags to module, to fix the “Uncaught SyntaxError Unexpected token ‘export'” error.

For example:

<script type="module" src="index.js"></script>

All recent browsers have the type=”module” attribute, which allows us to use the ES6 modules syntax.

index.html:

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

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

We can now use the ES6 modules syntax in our index.js file

index.js:

// Create a class with some parameterized constructor
export class Employ {
  constructor(hello) {
   // Inside the constructor initialize the variable with the value.
    this.hello = hello;
  }
}

we can utilize the syntax of the ES6 module as long as you specify/set the type attribute to module when loading our scripts.

The exports can then be imported into another file as follows:

anotherFile.js:

// Importing Employ class from the index.js file using the import keyword
import {Employ} from './index.js';
console.log(Employ);

NOTE:

we must also set the type attribute of the anotherFile.js in our html file to module.

index.html:

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

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

This attribute is supported by all current browsers. It’s no surprise that Internet Explorer doesn’t.

Check out this table on the caniuse website for browser support.

The following are some examples of how to use the syntax of the ES6 module with named or default exports.

The Named exports using ES6 modules

index.js:

// Here we export the classes Employ & Website using the export keyword
export class Employ {}
export class Website {}

We are now importing them into another file from the above index.js file.

anotherFile.js:

// Here we are importing the Employ & Website classes from
// the 'index.js' file using the import keyword
import {Employ, Website} from './index.js'

The Default exports using ES6 modules.

Syntaxerror: unexpected token ‘export’: Please keep in mind that each file can only have one default export.

index.js:

export default class Employ {}

We are now importing them into another file from the above index.js file.

anotherFile.js:

// Import the default export class 'Employ' from the 
// index.js file using the import keyword
import Employ from './index.js'

We now try to combine and match

index.js:

export default class Employ {}

export const salary = 60000;

We are now importing them into another file from the above index.js file.

anotherFile.js:

import Employ, {salary} from './index.js'

Probably soon, in the future, the syntax of the ES6 module will be used by default in both Node.js and the browser.

Typeerror: cannot read property ‘length’ of undefined – How to Fix Cannot read property ‘length’ of Undefined in JavaSript?

How to Fix Cannot read property 'length' of Undefined in JavaSript

Typeerror: cannot read property ‘length’ of undefined: When accessing the length property on an undefined value, the error “Cannot read property ‘length’ of undefined” occurs. To avoid the error, only use the length property on data types that support it, such as arrays or strings.

Let us see an example to know how this error occurs.

index.js:

// Declare an array with  undefined and store it in a variable
const gvn_arr = undefined;

// Get the length of an array using the 'length' attribute
gvn_arr.length;

Output:

gvn_arr.length;
^

TypeError: Cannot read property 'length' of undefined
at Object.<anonymous> (/tmp/ER7rLDlJor.js:5: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:

The properties of an undefined array cannot be read using the length attribute.
 So, TypeError: Cannot read property 'length' of undefined has occured

To resolve the error, either give a fallback for the value before accessing the length property or check to see if the value is of the correct type.

Fixing the “Cannot read property ‘length’ of undefined” Error

For Arrays

Here are some solutions to the problem while accessing the length property on arrays or strings.

Example1: Using Optional Chaining (index.js)

// Create a const variable with value as undefined 
const fromDb = undefined;

// Give an empty array fallback and store it in a variable
const gvn_arry = fromDb || [];

// Use optional chaining(.) i,e apply length attribute on the above array to get the length of an array and store it in another variable
const rslt = gvn_arry.length;
// Print the rslt i.e, length of the an empty array
console.log(rslt); 

Output:

0

Example2: Giving 0 as a fallback 

// Create a const variable with value as undefined 
const fromDb = undefined;

// Give an empty array fallback and store it in a variable
const gvn_arry = fromDb || [];

// Give 0 as fallback if the value is undefined
const rslt = gvn_arry.length || 0;
// Print the above result
console.log(rslt)

Output:

0

Example3: Using Array.isArray() Function

// Create a const variable with value as undefined 
const fromDb = undefined;

// Give an empty array fallback and store it in a variable
const gvn_arry = fromDb || [];

// Check if the above variable gvn_arry is an array using the Array.isArray() function and if conditional statement
if (Array.isArray(gvn_arry)) {
  // If it is an array then print the length of an array
  // using the length attribute
  const rslt = gvn_arry.length;
  console.log(rslt)
} else {
   // Else print "NOT an Array"
  console.log("The above given variable 'gvn_arry' is NOT an array");
}

Output:

0

Example4: Giving fallback in Place

// Create a const variable with value as undefined 
const fromDb = undefined;

// Give an empty array fallback and store it in a variable
const gvn_arry = fromDb || [];

// Apply fallback in place and add length attribute to the result
const rslt = (gvn_arry || []).length;
console.log(rslt)

Output:

0

FOR STRINGS

The following examples give the same solutions, but for strings.

Example1: Using Optional Chaining (index.js)

// Create a const variable with value as undefined 
const fromDb = undefined;

// Give an empty string fallback and store it in a variable
const gvn_str = fromDb || '';

// Use optional chaining(.) i,e apply length attribute on the above string to get the length of a string and store it in 
// another variable
const rslt = gvn_str.length;
// Print the result i.e, length of the an empty string
console.log(rslt);

Output:

0

Example2: Giving 0 as a fallback 

// Create a const variable with value as undefined 
const fromDb = undefined;

// Give an empty string fallback and store it in a variable
const gvn_str = fromDb || '';

// Give 0 as fallback if the value is undefined
const rslt = gvn_str.length || 0;
// Print the above result
console.log(rslt)

Output:

0

Example3: Using typeof

// Create a const variable with value as undefined 
const fromDb = undefined;

// Give an empty string fallback and store it in a variable
const gvn_str = fromDb || '';

// Check if the above variable gvn_str is a string using typeof and if conditional statement
if (typeof gvn_str === 'string') {
   // If it is a string then print the length of a string
  // using the length attribute
  const rslt = gvn_str.length;
  console.log(rslt)
} else {
     // Else print "NOT a String"
  console.log("The above given variable 'gvn_str' is NOT a string");
}

Output:

0

Example4: Giving fallback in Place

// Create a const variable with value as undefined 
const fromDb = undefined;

// Give an empty string fallback and store it in a variable
const gvn_str = fromDb || '';

// Apply fallback in place and add length attribute to the result
const rslt = (gvn_str || '').length;
console.log(rslt)

Output:

0

Remove substring from string javascript – How to Remove a Substring from a String using JavaScript

How to Remove a Substring from a String using JavaScript

Remove substring from string javascript: To remove a substring from a string, use the replace() function with the substring and an empty string as inputs, for example, gvn_str.replace (“example”, “”).

The replace() function returns a new string that removes the first occurrence of the specified substring.

Let us now see some of the below examples to understand this concept more clearly.

Removing a Substring From a String using JavaScript

1)Removing the first occurrence of ‘hello’ from a given string

// Give the string as static input and store it in a variable.
const gvn_str = 'hello,hello,Btechgeeks';

// Removing the first occurrence of 'hello' from a given string 
// using the replace() function
const remove_firststoccur = gvn_str.replace('hello', '');
console.log(remove_firststoccur); 

Output:

,hello,Btechgeeks

2)Removing All occurrences of ‘hello’ from a given string

// Give the string as static input and store it in a variable.
const gvn_str = 'hello,hello,Btechgeeks';

// Removing all occurrences of 'hello' from a given string
// using the replaceAll() function
const remove_all_occur = gvn_str.replaceAll('hello', '');
console.log(remove_all_occur);

Output:

,,Btechgeeks

3) Removing the first occurrence of hello from a given string using regex

// Give the string as static input and store it in a variable.
const gvn_str = 'hello,hello,Btechgeeks';

// Removing first occurrence of hello from a given string 
// using regex and replace() function
const removing_usingRegex = gvn_str.replace(/hello/, '');
console.log(removing_usingRegex);

Output:

,hello,Btechgeeks

4)Removing all occurrences of ‘hello’ from a given string using regex

// Give the string as static input and store it in a variable.
const gvn_str = 'hello,hello,Btechgeeks';

// Removing all occurrences of 'hello' from a given string 
// using regex and replace() function
const removeAllOccur_regex = gvn_str.replace(/hello/g, '');
// Print it on the console
console.log(removeAllOccur_regex);

Output:

,,Btechgeeks

string.replace() function:

Remove substring javascript: The String.replace() function accepts the following two parameters:

  • A substring of the string that we wish to match.
  • Replacement for the first match.

Here we provided an empty string as the replacement since we want to remove the substring.

NOTE:

The replace method returns a new string rather than changing the old string. 
Strings in JavaScript are immutable.

string.replaceAll() function:

Javascript remove substring from string: Use the string.replaceAll() function to remove all occurrences of a substring from a string.

To delete all occurrences of a substring from a string, use the replaceAll() method with the substring as the first parameter and an empty string as the second.

The replaceAll method will return a new string that removes all occurrences of the substring.

The replaceAll() function takes the same 2 arguments as the replace() method takes

  • The search string
  • The replacement for each match.

Example

JS remove substring from string: The forward slashes / / indicate the start and end of the regular expression. Within the regular expression, we have a character class [] that matches all digits from 0 to 9. The first example replaces the first occurrence of a digit in the string with an empty string.

Approach:

  • Give the string as static input and store it in a variable.
  • Remove the first occurrence of any number between 0 to 9(included) from a given string using regex and replace it with an empty string using replace() function
  • Print the result on the console.
  • Remove All the occurrences of any number between 0 to 9(included) from a given string using regex and replace it with an empty string using replace() function.
  • The Exit of the Program.

Below is the implementation:

// Give the string as static input and store it in a variable.
const gvn_str = '1, one, 5, 9';

// Remove first occurrence of any number between 0 to 9(included)
// from a given string using regex and replace it with an empty
// string using replace() function
const removeFstOccur_regex  = gvn_str.replace(/[0-9]/, '');
// Print the result on console
console.log(removeFstOccur_regex); 

// Remove All the occurrences of any number between 0 to 9(included)
// from a given string using regex and replace it with an empty
// string using replace() function
const removeAllOccur_regex  = gvn_str.replace(/[0-9]/g, '');
console.log(removeAllOccur_regex ); 

Output:

, one, 5, 9
, one, ,

Explanation:

Here in the first case, 1 is a number between 0 to 9(both included) hence it is replaced with 
an empty string. Removing only the first occurence keep the rest numbers undisturbed.

In the second case, 1, 5, 9 are the numbers in a range 0 to 9, hence all of them are replaced 
with an empty string. Removing all the occurences

NOTE:

We can also replace it with any other string instead of an empty string

Example

// Give the string as static input and store it in a variable.
const gvn_str = '1, one, 5, 9';

// Remove first occurrence of any number between 0 to 9(included)
// from a given string using regex and replace it with "@" symbol
// using replace() function
const removeFstOccur_regex  = gvn_str.replace(/[0-9]/, '@');
// Print the result on console
console.log(removeFstOccur_regex); 

// Remove All the occurrences of any number between 0 to 9(included)
// from a given string using regex and replace it with "@" symbol
// using replace() function
const removeAllOccur_regex  = gvn_str.replace(/[0-9]/g, '@');
console.log(removeAllOccur_regex ); 

Output:

@, one, 5, 9
@, one, @, @

JS unexpected end of input – Uncaught SyntaxError: Unexpected end of input Error in JavaScript Solution

Uncaught SyntaxError Unexpected end of input Error in JavaScript Solution

JS unexpected end of input: The error “Uncaught SyntaxError: Unexpected end of Input” arises for three reasons mostly:

  • Missing a closing parenthesis, bracket, or quote.
  • Using JSON.parse() or $.parseJSON to parse an empty response.
  • Receiving a text/Html response or no response at all from a server and attempting to parse it as JSON.

Below are the examples where this “Uncaught SyntaxError: Unexpected end of Input” occurs.

Uncaught SyntaxError: Unexpected end of input Error in JavaScript Solution

Method #1: Forgetting to close parenthesis, bracket, or quote

Example1:

// Solving Uncaught SyntaxError: Unexpected end of input Error
// Create a function say 'multiply' which accepts two numbers
// as arguments and perform multiplication operation
function multiply(x, y) {
  // Multiply the given two numbers and return their result
  return x*y;

// Here the function is not closed with the curly braces
// we may forget to enclose the brackets sometimes which leads to 
// Uncaught SyntaxError: Unexpected end of input Error

Output:

return x*y;
^

SyntaxError: Unexpected end of input
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 the function is not enclosed with the curly braces, leading to the
Uncaught SyntaxError: Unexpected end of input Error

Example2:

//Check if the condition is true using the if conditional statement
if (true) {
    
//Here we forgot to close the curly brace.

Output:

if (true) {
^

SyntaxError: Unexpected end of input
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 the if conditional statement is not enclosed with the curly braces.
Sometime we may forget these small things which leads to 
Uncaught SyntaxError: Unexpected end of input Error

Example3:

//Here the array is not enclosed with the square bracket
const array = ['x', 'y', 'z'

Output:

const array = ['x', 'y', 'z' 
^^^

SyntaxError: Unexpected end of input
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)

Example4:

//Similarly we may forget to enclose the curly braces while creating
// an object. 
//Hence SyntaxError: Unexpected end of input occurs
const object = {website: 'Btechgeeks'

Output:

const object = {website: 'Btechgeeks'
^^^^^^^^^^^^

SyntaxError: Unexpected end of input
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)

Method #2: Using JSON.parse() or $.parseJSON to parse an empty response.

Javascript unexpected end of input: The “Uncaught SyntaxError Unexpected end of input” error also arises when you use the JSON.parse() function to parse an empty response from your server or an empty string.

Example1:

// Here we are using the JSON.parse() function to parse 
// an emptyresponse 
// Hence, SyntaxError: Unexpected end of JSON input occurs
console.log(JSON.parse(''));

Output:

undefined:1

SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at Object.<anonymous> (/tmp/Aff2Utqlg8.js:4:18)
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)

Example2:

console.log($.parseJSON(''));

Output:

console.log($.parseJSON(''));
^

ReferenceError: $ is not defined
at Object.<anonymous> (/tmp/Aff2Utqlg8.js:1: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)

Explanation:

We encountered an error when parsing an empty string. 
This can also happen if your server returns an empty response and 
you try to parse it with JSON.parse.

To handle this case, we can use the following methods:

  • In a try/catch block, wrap your parsing logic.
  • Ensure that your server returns a valid JSON response
  • If you expect an empty server response, remove the parsing logic from your code.
// Using try-catch blocks to handle the 
// SyntaxError: Unexpected end of JSON input while passing
// an empty string to JSON.parse
try {
  const rslt = JSON.parse('');
  // printing result on the console
  console.log(rslt);
} 
catch (error) {
  // Handling the SyntaxError: Unexpected end of JSON input
  // inside the catch block
  console.log(' SyntaxErro', error);
}

Explanation:

Unexpected end of input javascript: If the JSON.parse function returns an error as a result of parsing invalid JSON, the error is passed as a parameter to the catch function, where it can be handled.

If you know the server’s response does not include valid JSON, you can delete/remove the call to the JSON.parse function.

Handling the Uncaught SyntaxError: Unexpected end of input Error in Brief

To resolve the “Uncaught SyntaxError Unexpected End of Input” error, follow these steps:

  • Close any missing parenthesis, bracket, or quote.
  • Don’t use JSON to parse an empty response. $.parseJSON or parse()
  • Check that your server gives the correct response type; for example, attempting to parse invalid JSON results in an error.

 

Cannot read property style of null – How to Fix Cannot read property ‘style’ of Null in JavaScript?

How to Fix Cannot read property 'style' of Null in JavaScript

Cannot read property style of null: In this article, let us see how to fix the Cannot read property ‘style’ of Null error in JavaScript.

There are two main causes of the “Cannot read property ‘style’ of null” error:

  • Accessing the style property of a non-existent DOM element.
  • Inserting the JS script tag above the HTML element declarations, where the DOM elements are defined.

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

Fixing Cannot read property ‘style’ of Null in JavaScript

Case#1: Accessing the style property of ‘null’ Variable

 index.js 

// Declare an variable with value as null  
const data = null;

// Apply style property on the above variable and print the result
console.log(data.style);

Output:

console.log(data.style);
^

TypeError: Cannot read property 'style' of null
at Object.<anonymous> (/tmp/ER7rLDlJor.js:5:18)
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 the style attribute cannot read the properties of 'null'. 
Hence TypeError: Cannot read property 'style' of null occurs

Case#2: Accessing the style property of a non-existent DOM element.

Typeerror: cannot read property ‘style’ of null: The error mostly arises when you call the getElementById() method with an id that does not exist in the DOM.

const gvn_id = document.getElementById('Id Not Exist');
console.log(gvn_id); 

// Apply the text attribute to the given element as below
gvn_id.style.text = 'Italic';

Output:

const gvn_id = document.getElementById('Id Not Exist');
^

ReferenceError: document is not defined
at Object.<anonymous> (/tmp/ER7rLDlJor.js:1:16)
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:

To resolve the “Cannot read property ‘style’ of null” problem, ensure that the DOM element on which the style property is being accessed exists.

Because an element with the specified id does not exist in the DOM in this example, the getElementById function returns null We get the error when we try to access the style property on a null value.

Case#3: Placing the <script> Tag Before the HTML elements Declaration

Cannot read property ‘style’ of null: The other common cause of the error is positioning the JS script tag before declaring the DOM elements.

To resolve the “Cannot read property ‘style’ of null” error, add the JS script tag at the bottom of the body, after the HTML elements have been declared.

index.html:

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

    <div id="abc" style="color: blue">Btechgeeks</div>
  </body>
</html>

Since the JS script tag was positioned before declaring the div element, the index.js file is executed before the DOM element is declared.

This indicates that the div will be inaccessible in the index.js file.

index.js:

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

// As the div tag was declared below the scrpit tag 
// It is not accessible in index.js. so, error occurs
abc.style.color = 'red';

NOTE:

So, we must place the JS <script/> tag after the HTML elements at the bottom of the body.

Fixing the Error

index.html: Placing the <script/> tag at the bottom of body

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <!-- Here we write the HTML declaration-->
    <div id="abc" style="color: blue">Btechgeeks</div>

    <!-- Here we write the script tag at the bottom of the body 
    which is a GOOD approach-->
    <script src="index.js"></script>
  </body>
</html>

In the index.js file, the div element is now accessible.

index.js:

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

// NOW it works fine 
abc.style.color = 'red';

We may now access the DOM element because the HTML element is created before the index.js script is executed.

In Brief

The error “Cannot read property ‘style’ of null” occurs when:

  • Attempting to access the style property on a null value, for example, after calling getElementById with an invalid identifier.
  • Inserting the JS script tag before the DOM elements have been declared.