Unexpected identifier javascript – How to Fix Unexpected identifier Error in JavaScript?

How to Fix Unexpected identifier Error in JavaScript

Unexpected identifier javascript: Uncaught syntaxerror unexpected identifier javascript, Uncaught syntaxerror unexpected identifier node js, Javascript error unexpected identifier selenium, Unexpected identifier mysql, Syntax error unexpected identifier php, Unexpected identifier jquery, Uncaught syntaxerror unexpected token are solved by the errors with two reasons.

The error “Uncaught SyntaxError: Unexpected identifier” occurs for two reasons:

  • Misspelling a keyword, for example, Let or Class instead of let and class
  • Including a missing or extra comma, parentheses, quote, or bracket in your code.

Let us see some of the cases how does this error occur

NOTE:

You can compile the below codes in any online complier or vs code etc for more clarity

1)Giving ‘Let’ instead of ‘let’ keyword

// Here we gave Let insted of let. So, the 
// SyntaxError: Unexpected identifier occurs
Let EmpId = 1254; 

Output:

Let EmpId = 1254; 
^^^^^

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

2) Giving ‘Class’ instead of ‘class’ keyword

// Here we gave Let 'Class' instead of class. So, the 
// SyntaxError: Unexpected identifier occurs
Class Employ { 
    
}

Output:

Class Employ { 
^^^^^^

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

3) Giving ‘Function’ instead of ‘function’ keyword

// Here we gave Let 'Function' instead of 'function'. So, the 
// SyntaxError: Unexpected identifier occurs
Function multiply(x, y) { 
  return x * y;
}

Output:

Function multiply(x, y) { 
^^^^^^^^

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

4)Missing comma(,)

const object = {
  // Here we missed a comma(,) to separate each key-value pair.
  // So, the  SyntaxError: Unexpected identifier occurs
  EmpName: 'Nick' 
  EmpId: 4256
};

Output:

EmpId: 4256
^^^^^

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

The first and second cases indicate how a keyword misspelling generates an error. Generally, the keywords are case-sensitive.

You can validate your code by pasting it into an online Syntax Validator/online javascript compiler. The validator should be able to tell you which line has the error.

Alternatively, use your browser’s Console tab to find the line in which the error occurred.

Fixing Unexpected identifier Error in JavaScript

Unexpected identifier js: A great way to start is around the line where the problem occurred and look for:

  • Let, Const, Class, or Function are all misspelled or incorrect keywords.
  • Check if we are missing any colon, comma, bracket, parenthesis, or quote.
  • Also, see if we are giving an extra colon, comma, bracket, parenthesis, or quote.

To resolve the “Uncaught SyntaxError: Unexpected identifier” error, check for misspelled keywords, such as Let or Function instead of let and function, and correct any mistakes relating to missing or additional commas, colons, parenthesis, quotes, or brackets.

Let us now fix the above examples one by one to avoid SyntaxError: Unexpected identifier Error

index.js:

// Give let keyword NOT Let
let EmpId = 1254; 

// Give class keyword NOT Class
class Employ { 
    
}

// Give function NOT Function
function multiply(x, y) { 
  return x * y;
}

const object = {
  // Give a comma to separate each key-value pair
  EmpName: 'Nick',
  EmpId: 4256
};

Test Yourself:

  1. How to fix uncaught syntaxerror invalid or unexpected token?
  2. How to fix identifier expected error in java?
  3. How to fix undefined error in javascript?
  4. How to fix unexpected identifier?
  5. How to fix uncaught syntaxerror unexpected end of input?
  6. How to fix identifier has already been declared?
  7. How to fix unexpected token?

Props.children react – A quick intro to React’s props.children

INTRODUCTION

Props.children react: At the first sight, the this.props.children can be a bit overwhelming when studying class based components. As many developers and tutorials use React class based components as it gives access to state, it is very necessary to be familiar with props.children (if you are using stateless functional components) and this.props.children (if you are using class components)

What is ‘children’?

What this.props.children  does is that it displays whatever you include between the opening and closing tags when invoking a component.

A simple example

For example, in a class based component.

import React, { Component } from "react";

class Welcome extends Component {
  render(props) {
    return (
      <div>
        <p>Hello Class Component</p>
        <p>{this.props.children}</p>
      </div>
    );
  }
}
export default Welcome;

Here the component is receiving children from , say, app.js which can be passed in the manner shown below.

import Welcome from "./components/React/Welcome";

function App() {
  return (
    <>
      <div className="App">
        <Welcome children="I am a child" />
      </div>
    </>
  );
}

export default App;

As you can see, when the string “I am a child” is passed through to the Welcome component the output looks similar to what is shown below.

Hello Class Component.

I am a child 

Whenever this component is invoked {props.children} will also be displayed and this is just a reference to what is between the opening and closing tags of the component.

 

A complex example

I will now demonstrate an error solving method via this.props.children , where if there is an error in code it will display Something Went Wrong  or if it is error free code it will simply say Error Free Code

import React, { Component } from "react";

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);

    this.state = {
      hasError: true,
    };
  }

  componentDidCatch(error, info) {
    console.log(error);
  }

    render() {
        if (this.state.hasError) {
        return <h1>Something Went Wrong</h1>;
        } else if (!this.state.hasError) {
        return (<>
                   <h1>Error Free Code</h1>
                   {this.props.children};
                </>);
        }
    }
    }
export default ErrorBoundary;

So, if there is error in the code, then the first return statement will be implemented and all others will be ignored. Or else, the this.props.children that is passed via another (parent) component will be displayed.

 

CONCLUSION

I hope this shed a little bit more light on React and how you can use props.children to help you customize your app’s content while still being able to reuse the same components in my case for error checking purposes.

 

First letter uppercase js – How to uppercase the first letter of a string in JavaScript? | JavaScript Program to Convert the First Letter of a String into UpperCase

How to Uppercase the first letter of a String in JavaScript

First letter uppercase js: In this tutorial, passionate learners can grab the opportunity to study and understand how to write a JavaScript program that converts the first letter of a string into uppercase. Here, we have used two approaches with neat examples and explained How to Capitalize the First Letter of a String in JavaScript. So, check out the below links directly and learn thoroughly.

How to Uppercase the first letter of a string in JavaScript?

How to uppercase first letter in javascript: JavaScript offers several methods to capitalize a string to make the first character uppercase. Discover what are the various ways, and also find out which one is best for using with plain JavaScript.

The most common operation with strings is to make the string capitalized: uppercase its first letter, and leave the rest of the string as-is.

The best way to do this is by a combination of two functions. One uppercases the first letter, and the second slices the string and returns it starting from the second character.

const name = "flavio";
const nameCapitalized = name.charAt(0).toUpperCase() + name.slice(1);
console.log(nameCapitalized);

You can extract that to a function, which also checks if the passed parameter is a string, and returns an empty string if not.

const capitalize = (s) => {
  if (typeof s !== 'string') return ''
  return s.charAt(0).toUpperCase() + s.slice(1)
}

capitalize('flavio') //'Flavio'
capitalize('f')      //'F'
capitalize(0)        //''
capitalize({})       //''

Instead of using s.charAt(0) you could also use string indexing (not supported in older IE versions): s[0].

Some solutions online advocate for adding the function to the String prototype.

String.prototype.capitalize = function() {
  return this.charAt(0).toUpperCase() + this.slice(1)
}

(we use a regular function to make use of this -arrow functions would fail in this case, as this in arrow functions does not reference the current object)

This solution is not ideal, because editing the prototype is not generally recommended, and it’s a much slower solution than having an independent function.

Don’t forget that if you just want to capitalize for presentational purposes on a Web Page, CSS might be a better solution, just add a capitalize class to your HTML paragraph and use:

p.capitalize {
  text-transform: capitalize;
}

Do Refer:

Example 1: Convert the First letter to UpperCase

Let’s see the below program on converting the first letter to uppercase. Here, the user is prompted to enter a string and that string is transferred into the capitalizeFirstLetter() function.

  • First and foremost, the string’s first character is extracted performing charAt() method. Here, str.charAt(0); gives p.
  • The toUpperCase() method changes the string to uppercase. Here, str.charAt(0).toUpperCase(); gives P.
  • The rest of the string is return by the slice() method. Here, str.slice(1); gives Programming
  • Finally, these two values are concatenated using the + operator.
// program to convert first letter of a string to uppercase
function capitalizeFirstLetter(str) {

    // converting first letter to uppercase
    const capitalized = str.charAt(0).toUpperCase() + str.slice(1);

    return capitalized;
}

// take input
const string = prompt('Enter a string: ');

const result = capitalizeFirstLetter(string);

console.log(result);

Output:

Enter a string: programming 
Programming

Example 2: Convert the First letter to UpperCase using Regex

Below the given program, convert the first letter of a string to uppercase by using the regular expression (regex).

  • The regex pattern is /^./ meets the first character of a string.
  • The toUpperCase() method changes the string to uppercase.
// program to convert first letter of a string to uppercase
function capitalizeFirstLetter(str) {

    // converting first letter to uppercase
    const capitalized = str.replace(/^./, str[0].toUpperCase());

    return capitalized;
}

// take input
const string = prompt('Enter a string: ');

const result = capitalizeFirstLetter(string);

console.log(result);

Output:

Enter a string: programming 
Programming

Javascript global object – The JavaScript Global Object | What is a Global Object in JavaScript? | JavaScript Global Variables, Properties, Functions

The JavaScript Global Object

Javascript global object: JavaScript implements a global object which holds a kit of properties, functions, and objects that are accessed globally, without a namespace. Want to learn more about the JavaScript Global Object Variables, Functions & Properties? Then, this tutorial is the perfect one for all beginners and experienced programmers. So, dive into this page and directly get into the topic using the direct links available below.

What is a Global Object in JavaScript?

Objects in JavaScript are distinct from the Global Object. Applying the new operator, you cannot build global objects. When the scripting engine is initialized then only it comes into existence. Once the initialization is completed, the functions and constants are ready to use while coding in JavaScript.

A global object enables you to perform the below conditions −

  • It provides access to built-in functions and values. Call alert immediately like the below code snippet, with window −
alert("Demo Text");
// or
window.alert("Demo Text");
  • Even, it also provides access to global function declarations and var variables in JavaScript. Look at the below code –
<script>
         var str = "Demo Text";
         // using window
         alert( window.str );
</script>

Some of the JavaScript Global objects are:

  • Array
  • Boolean
  • Date
  • Function
  • JSON
  • Math
  • Number
  • Object
  • RegExp
  • String
  • Symbol

and errors:

  • Error
  • EvalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError

Window object in the Browser

In the Browser, the window object is the Global Object. Any JavaScript Global Variables or Functions can be accessed as properties of thewindowobject while programming.

Do Refer:

JavaScript Global Properties

The properties of JavaScript Global Object are:

  • Infinity
  • NaN
  • undefined

Infinity

Infinity in JavaScript is a value that represents infinity.

Positive infinity. To get negative infinity, use the  operator: -Infinity.

Those are equivalent to Number.POSITIVE_INFINITY and Number.NEGATIVE_INFINITY.

Adding any number to Infinity, or multiplying Infinity for any number, still gives Infinity.

NaN

The global NaN value is an acronym for Not a Number. It’s returned by operations such as zero divided by zero, invalid parseInt() operations, or other operations.

parseInt()    //NaN
parseInt('a') //NaN
0/0           //NaN

A special thing to consider is that a NaN value is never equal to another NaN value. You must use the isNaN() global function to check if a value evaluates to NaN:

NaN === NaN //false
0/0 === NaN //false
isNaN(0/0)  //true

undefined

The global undefined property holds the primitive value undefined.

Running a function that does not specify a return value returns undefined:

const testFunc = () => {}
testFunc() //undefined

Unlike NaN, we can compare an undefined value with undefined, and get true:

undefined === undefined

It’s common to use the typeof operator to determine if a variable is undefined:

if (typeof cat === 'undefined') {

}

JavaScript Global Functions

The functions are:

  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • eval()
  • isFinite()
  • isNaN()
  • parseFloat()
  • parseInt()

decodeURI()

Performs the opposite operation of encodeURI()

decodeURIComponent()

Performs the opposite operation of encodeURIComponent()

encodeURI()

This function is used to encode a complete URL. It does encode all characters to their HTML entities except the ones that have a special meaning in a URI structure, including all characters and digits, plus those special characters:

~!@#$&*()=:/,;?+-_.

Example:

encodeURI("http://google.com/good morning/")
//"http://google.com/good%20morning/"

encodeURIComponent()

Similar to encodeURI()encodeURIComponent() is meant to have a different job.

Instead of being used to encode an entire URI, it encodes a portion of a URI.

It does encode all characters to their HTML entities except the ones that have a special meaning in a URI structure, including all characters and digits, plus those special characters:

-_.!~*'()

Example:

encodeURIComponent("http://www.example.org/a file with spaces.html")
// "http%3A%2F%2Fwww.example.org%2Fa%20file%20with%20spaces.html"

eval()

This is a special function that takes a string that contains JavaScript code and evaluates/runs it.

isFinite()

Returns true if the value passed as parameter is finite.

isFinite(1)                        //true
isFinite(Number.POSITIVE_INFINITY) //false
isFinite(Infinity)                 //false

isNaN()

Returns true if the value passed as parameter evaluates to NaN.

isNaN(NaN)        //true
isNaN(Number.NaN) //true
isNaN('x')        //true
isNaN(2)          //false
isNaN(undefined)  //true

This function is very useful because a NaN value is never equal to another NaN value. You must use the isNaN() global function to check if a value evaluates to NaN:

0/0 === NaN //false
isNaN(0/0)  //true

parseFloat()

Like parseInt()parseFloat() is used to convert a string value into a number, but retains the decimal part:

parseFloat('10.000', 10) //10     
parseFloat('10.20', 10)  //10.2   
parseFloat('10.81', 10)  //10.81

parseInt()

This function is used to convert a string value into a number.

Another good solution for integers is to call the parseInt() function:

const count = parseInt('1234', 10) //1234

Don’t forget the second parameter, which is the radix, always 10 for decimal numbers, or the conversion might try to guess the radix and give unexpected results.

parseInt() tries to get a number from a string that does not only contain a number:

parseInt('10 lions', 10) //10

but if the string does not start with a number, you’ll get NaN (Not a Number):

parseInt("I'm 10", 10) //NaN

Also, just like Number, it’s not reliable with separators between the digits:

parseInt('10.20', 10)  //10 
parseInt('10.81', 10)  //10

JS check object empty – How to Check whether an Object is Empty in JavaScript?

How to Check whether an Object is Empty in JavaScript

JS check object empty: In this article, we are going to check whether the object is empty or not in Javascript

Check whether an Object is Empty in JavaScript?

Javascript check object empty: We can check whether the object is empty or NOT in a number of ways. Let us see them one by one:

Method #1: Using Object.keys() Method

In JavaScript, use the following steps to determine whether an object is empty:

  • Pass the object to the ‘Object.keys’ method to obtain an array of all the keys of an object
  • Access the length property on the array.
  • If the length of the keys is equal to 0, the object is empty.

Using ‘Object.keys’ on an Empty Object

// This Supports in IE 9-11
// Declare an empty object 
const object = {};

// Check if the above object is empty using the Object.keys and length attribute
const chk_isEmpty = Object.keys(object).length === 0;
// If it is empty it prints true, else false
console.log(chk_isEmpty)

Output:

true

Explanation:

Here, the Object.keys() method is used to get an array of all of the keys of an object.

Using ‘Object.keys’ on a Non-Empty Object

// This Supports in IE 9-11
// Declare an empty object 
const object = {1:"Hello", 2:"this is", 3:"Btechgeeks"};

// Check if the above object is empty using the Object.keys and length attribute
const chk_isEmpty = Object.keys(object).length === 0;
// If it is empty it prints true, else false
console.log(chk_isEmpty)

Output:

false

Explanation:

Here the given object is not empty, hence it returns false

NOTE:

If the object has no key-value pairs (if it is empty), the Object.keys method returns an empty array.

Method #2: Iterating Over the Properties of Object

Another way is to iterate over the properties of an object. If the object has even a single iteration, it is not empty.

Example

// This supports in IE 6-11

// Declare an empty object and store it in a variable
const gvn_obj = {};

// Create a function say checkIsEmpty by passing the object 
// as an argument to it.
function checkIsEmpty(object) {
  // Iterate over the properties of an object using the for loop.
  // Check If the object has even a single iteration(object is not empty)
  for (const property in object) {
    // As the object is NOT empty, return false  
    return false;
  }
  // As the object is empty, return true  
  return true;
}

// Pass the given object as an argument to the above checkIsEmpty
// function and print the result
console.log(checkIsEmpty(gvn_obj)); 

Output:

true

Method #3: Using Object.entries() Method (ECMA 7+)

// Declare an empty object and store it in a variable
const gvn_obj = {};

// Check if the above object is empty using the Object.entries and length attribute
const chk_isEmpty = Object.entries(gvn_obj).length === 0 && gvn_obj.constructor === Object

//If it is empty it prints true, else false
console.log(chk_isEmpty)

Output:

true

Method #4: Using hasOwnProperty() function (Pre-ECMA 5)

Example1

// Declare an empty object and store it in a variable
const gvn_obj = {};

// Create a function say checkIsEmpty by passing the object 
// as an argument to it.
function checkIsEmpty(gvn_obj) {
  for(var property in gvn_obj) {
     // using hasOwnProperty() function to check if an object is empty or NOT
    if(gvn_obj.hasOwnProperty(property)) {
      return false;
    }
  }
  return JSON.stringify(gvn_obj) === JSON.stringify({});
}

// Pass the given object as an argument to the above checkIsEmpty
// function and print the result
console.log(checkIsEmpty(gvn_obj));

Output:

true

Example2

// Declare an object and store it in a variable
const gvn_obj = {1:"Hello", 2:"this is", 3:"Btechgeeks"};

// Create a function say checkIsEmpty by passing the object 
// as an argument to it.
function checkIsEmpty(gvn_obj) {
  for(var property in gvn_obj) {
     // using hasOwnProperty() function to check if an object is empty or NOT
    if(gvn_obj.hasOwnProperty(property)) {
      return false;
    }
  }
  return JSON.stringify(gvn_obj) === JSON.stringify({});
}

// Pass the given object as an argument to the above checkIsEmpty
// function and print the result
console.log(checkIsEmpty(gvn_obj));

Output:

false

React js alternatives – Lightweight Alternatives to React

Lightweight Alternatives to React

React js alternatives: React.js is a marvelous JavaScript library that employs Virtual DOM. React is the prime choice of developers when it comes to building single-page applications.

Why do you need an alternative to React.js?

  • Most of the React developers find it challenging to manage the huge library size of the React.js framework. Surely you can not afford to invest in a framework that demands an exquisite memory space.
  • Secondly, React lacks MVC architecture, especially since the View functionality is not managed by its Model and Controller. Hence, you need an alternative React framework, which is view-oriented.
  • React has a steep learning curve, and developers need to invest a lot of time to learn new technology. Project ignition is delayed.
  • Many React.js developers find it hard to grasp the documentation of JSX React. Beginners are never comfortable with this framework.

In this blog, I am recalling and bringing in front of you the list of React.js alternatives that those experts realized in the tech-talk show. Along with the javascript frameworks, I have mentioned the pros and cons of each of the frameworks and their comparison with React.js.

Preact

Alternatives to react: Jason Miller introduced Preact under the open-source MIT license. You can think of Preact as a lightweight alternative to the React library for developing mobile or web applications, and progressive web apps PWA.

Preact Pros

React js alternatives: It is much compact, precise, and lightweight in size (3KB) so your application can perform faster.

  • Preact uses ES6 API, which enables you to uplift your application from React to Preact very easily. You can even adapt it as a library to create fantastic user interfaces for your project.
  • Entrepreneurs can create new projects easily by using the official CLI without the trouble of getting into Babel and Webpack configuration.
  • You can get all the help from the official website examples and Preact documentation to kick-start your application development.
  • Along with all the inspiring features of React, the Preact library also consists of some special features like the LinkedState.

Preact Cons

You do not get the context support.

  • For the stateful functionalities of your application, the createClass function is missing. Preact only allows you to use ES6 class and stateless components.
  • Preact doesn’t care about the React propTypes.
  • The community size is yet to reach the competition with React.
  • Preact lacks innovation and mostly mimics React.

Preact Vs. React

  • API: Not all the React features are present in Preact; it contains only a small part of the React Application Interface functionality.
  • Size: As I mentioned in the beginning, Preact is much lighter than React. React is 5.3 KB, whereas Preact is only 3 KB.
  • Performance: Because of being lightweight, Preact is faster as compared to React applications.

Svelte

React alternatives: Svelte is a free and open-source front-end compiler created by Rich Harris and maintained by the Svelte core team members. Svelte applications do not include framework references.

Svelte Pros

  • The building time is blazing fast when compared to React or even other frameworks. Usage of the rollup plugin as the bundler might be the secret here.
  • Bundle size is smaller and tiny when gzipped when compared to React, and this is a huge plus point. Even with the shopping cart application I built, the initial load time and the duration to render the UI is extremely low, only the chunky images I have added takes some time :).
  • Binding classes and variables are relatively easy, and custom logic is not needed when binding classes.
  • Scoping CSS <style> within the component itself allows flexible styling.
  • Easier to understand and get started when compared to other frameworks as the significant portion of Svelte is plain JavaScript, HTML, and CSS.
  • More straightforward store implementation when compared to React’s context API, granted context API provides more features, and Svelte might be simple enough for common scenarios.

Svelte Cons

  • Svelte won’t listen for reference updates and array mutations, which is a bummer, and developers need to actively lookout for this and make sure arrays are reassigned so the UI will be updated.
  • Usage style for DOM events can also be annoying, as we need to follow Svelte’s specific syntax instead of using the predefined JS syntax. Cannot directly use onClick like in React, but instead, have to use special syntax such as on:click.
  • Svelte is a new and young framework with minimal community support, thereby doesn’t have support for a wide range of plugins and integrations that might be required by a heavy production application. React is a powerful contender here.
  • No additional improvements. Ex- React suspense actively controls your code and how it runs and tries to optimize when the DOM is updated and sometimes even provides automatic loading spinners when waiting for data. These extra features and continued improvements are relatively low in Svelte.
  • Some developers might not prefer using special syntaxes such as #if and #each within their templates and instead would want to use plain JavaScript, which React allows. This might come down to personal preferences.

Svelte Vs. React

Svelte does provide noticeable improvements in certain features when compared to React. But it may not still be significant or large enough to replace React completely. React is still robust and broadly adopted. Svelte has quite some catching up to do. But concept-wise, the compiling approach taken by Svelte has proven that virtual DOM diffing isn’t the only approach to build fast reactive applications, and a good enough compiler can get the same job done as well as it gets.

Vanilla JS

Vanilla JS is nothing but plain JS without any external libraries or frameworks. Using this we can build powerful and cross-platform applications.

The major differences

Since there are so many ways to write vanilla JS, it can be difficult to pin down a list of differences that applies to 100% of apps. But here we’ll define some key differences that apply to many plain JS apps that are written without a framework.

Those differences are:

  • How the user interface is first created
  • How functionality is split up across the app
  • How data is stored on the browser
  • How the UI is updated

Is Vanilla JS worth over React

Vanilla JS is awesome but it’s not a great alternative when it comes to building huge applications with complex dynamic functionalities. Besides, it cannot create complex and efficient UIs. So if you have an app that changes frequently and drastically with thousands of pages, it is better to use a modern Javascript framework.

On the other hand, React which allows us to use reusable components and is capable of keeping the UI in sync with the state can definitely solve this problem.

Fix – Cannot use import statement outside module

Fix - Cannot use import statement outside module

Cannot use import statement outside a module node: When we use the ES6 Modules syntax in a script that wasn’t loaded as a module, we get the “SyntaxError: Cannot use import statement outside a module” error. Set the type property to the module when loading a script or in your package to fix the error. For Node apps, package.json is used.

Cannot use import statement outside module(Fix)

Cannot use import statement outside a module javascript: Below are some of the fixes for Cannot use import statement outside module error:

Fix #1: Adding type=”module” in index.html(main Page)

Nodejs cannot use import statement outside a module: Set the type attribute to the module when loading the script in your HTML code to fix the problem.

Solution:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- adding type as module in the script   -->
    <script type="module" src="index.js"></script>
</body>
</html>

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.

index.js

// importing from the loadash module
import _ from 'lodash';

// printing the unique values in the array by passing the array as an argument to the uniq() function
console.log(_.uniq([4,2,5,8,4,4]));

Output:

[4,2,5,8]

Fix #2: Adding type=module in Node.js

Cannot use import statement outside a module: When working with Node.js, you must set the type property in your package to the module. To use ES6 module imports, you’ll need a package.json file.

If your project doesn’t have a package.json file, create one with the npm init -y command in the project’s root directory.

npm init --y

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",
  "type":"module"
}

In your Node.js application, you can now use the syntax of the ES6 module.

index.js

// importing from the loadash module
import _ from 'lodash';

// printing the unique values in the array by passing the array as an argument to the uniq() function
console.log(_.uniq([4,2,5,8,4,4]));

Output:

[4,2,5,8]

Importing from another user created module:

You must add the .js extension when importing local files with the type attribute set to module.

btechgeeks.js

function mySum(a, b) {
  return a + b; 
}
export default mySum;

index.js

// importing mysum function from btechgeeks.js module using the import keyword
import mysum from './btechgeeks.js';

// passing some random two values to the mysum() function of the btechgeeks module and printing the summ
console.log('sum is:',mysum(11,17));

Output:

sum is: 28

If we remove the .js from the import then:

index.js

// importing mysum function from btechgeeks.js module using the import keyword
import mysum from './btechgeeks';

// passing some random two values to the mysum() function of the btechgeeks module and printing the summ
console.log('sum is:',mysum(11,17));

Output:

node:internal/process/esm_loader:94
internalBinding('errors').triggerUncaughtException(
^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\cirus\Desktop\LinkedIn\btechgeeks' imported from C:\Users\cirus\Desktop\LinkedIn\index.js
Did you mean to import ../btechgeeks.js?
at new NodeError (node:internal/errors:371:5)
at finalizeResolution (node:internal/modules/esm/resolve:418:11)
at moduleResolve (node:internal/modules/esm/resolve:983:10)
at defaultResolve (node:internal/modules/esm/resolve:1080:11)
at ESMLoader.resolve (node:internal/modules/esm/loader:530:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:251:18)
at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:79:40)
at link (node:internal/modules/esm/module_job:78:36) {
code: 'ERR_MODULE_NOT_FOUND'
}

Fix #3: Using require()

If none of the above options worked, try substituting require() for the import/export syntax.

// Using the require() function to import some random package
const myRandomFunction = require('some-package');

// For named exports enclosed the function in {}
const {someRandomFunction} = require('some-package')

Note:

If you try to run your source files that use ES6 module import/export syntax instead of your compiled files from your build directory, you’ll get the “Cannot use import statement outside module” error. Make sure that your compiled files are only executed from the build/dist directory.

Javascript cannot read property of undefined – How to Fix Cannot read Property of Undefined Error in JavaScript

How to Fix Cannot read Property of Undefined Error in JavaScript

Javascript cannot read property of undefined: There are three main causes of the “Cannot read property of undefined” error:

  • When we access a property on a variable that holds an undefined value.
  • When we access a non-existent property on a DOM element.
  • When we Insert the JavaScript <script/> tag above the HTML, where the DOM elements are declared.

The error most typically happens when you attempt to access a property on a variable that has an undefined value.

index.js:

const employ = undefined;

// Here the variable `employ` is undefined so when we try to
// access the `salary` property on the above variable that holds an
// undefined value we get an ERROR
employ.salary;

Output:

employ.salary;
^

TypeError: Cannot read property 'salary' of undefined
at Object.<anonymous> (/tmp/MOncfvGk3U.js:6:8)
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 variable `employ` is undefined so when we try to access the `salary` property 
on a variable that holds an undefined value we get an ERROR

Fixing Cannot read Property of Undefined Error in JavaScript

Method #1: Using Optional Chaining(.)

Cannot read property of undefined javascript: To fix the “Cannot read property of undefined” error, use the optional chaining (.) operator to ensure that the variable, for example employ.salary, is not null before accessing it.

Instead of throwing an error, the operator short-circuits if the variable is undefined or null.

// Take a variable and initialize its value with undefined
const employ = undefined;

// Print the salary property/attribute of the employ if it is doesn't exists then it prints undefined
console.log(employ.salary); 
console.log(employ.salary.month); 

Output:

Undefined
Undefined

Explanation:

Javascript cannot read property of undefined: The optional chaining (.) operator enables us to access an object’s property without throwing an exception if the reference is invalid.

If the reference is equal to undefined or null, the optional chaining (.) operator returns undefined instead of raising an error.

Method #2: Using if-Else Conditional Statements

// Take a variable and initialize its value with undefined
const employ = undefined;

// Check if the salary attribute is present in employ using optional chaining(.) and if conditional statement
if (employ.salary) {
// If is is true(exists) print that corresponding value 
  console.log(employ.salary);
} else {
    // Else print some random text for acknowledment
  console.log('The employ.salary is NOT found');
}

Output:

The employ.salary is NOT found

Method #3: Using logical AND (&&) operator

// Take a variable and initialize its value with undefined
const employ = undefined;

// Here we use logical AND(&&) operator to check whether the property/attribute exists or not
console.log(employ && employ.salary); 

Output:

undefined

Explanation:

Here we used the logical AND (&&) operator, which ignores the value to the right 
if the value to the left is false (example- undefined).

When trying to access an array element at an index that does not exist in the array, you frequently obtain undefined results.

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

// This is a BAD approach
// Here we get i.e, Cannot read property 'website' of undefined
console.log(gvn_arry[0].website); 

// This is a GOOD approach
console.log(gvn_arry[0].website); 

// This is a GOOD approach
console.log(gvn_arry[0] && gvn_arry[0].website); 

Output:

Undefined

Undefined

Before attempting to access a variable, ensure that it has been declared in your code; otherwise, you will receive the “X is not defined” error.

Accessing a non-existent property on a DOM element.

Another common cause of the error is attempting to access a property on a DOM element that does not exist.

To resolve the “Cannot read property of undefined” problem, verify that the DOM element you are attempting to access exists. When attempting to access the property at a non-existent index after using the getElementsByClassName() method, the error is frequently thrown.

index.js:

// Get the element by class name which doesn't exist

const htmlboxes = document.getElementsByClassName('doesNotExist');
console.log(htmlboxes );

// Here we get an error => Cannot read properties of undefined (reading 'innerHTML')
console.log(htmlboxes [0].innerHTML);

Output:

Cannot read properties of undefined (reading 'innerHTML')

Instead, correct the class name and use the optional chaining (.) operator to see if the property is present in the element at the index 0.

Using Optional Chaining and If else Conditional statements:

// Get the element by class name which doesn't exist 
const htmlboxes = document.getElementsByClassName('doesNotExist');
console.log(htmlboxes ); 

// Check if the element exists using the optional chaining(.)
if (htmlboxes[0].innerHTML) {
  console.log(htmlboxes [0].innerHTML);
} else {
  // If the element doesnt exist then print some random acknowledgement
  console.log('The element is not FOUND');
}

If the element at index 0 has the innerHTML property, the if block is executed; otherwise, the else block is executed.

To resolve the “Cannot read property of undefined” 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 inserted.

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <script src="index.js"></script>

    <!-- The HTML elements must be above the JS script tag,
    otherwise they cannot be accessed
    This is a BAD approach-->
    
    <div class="box">Btechgeeks</div>
  </body>
</html>

The index.js script tag is executed before the declaration of the div element with the class name box.

The div element will not be available if you try to access it in the index.js script, resulting in the error.

index.js:

// Get the element by class name which doesn't exist 
const htmlboxes = document.getElementsByClassName('doesNotExist');
console.log(htmlboxes); // []

// Here we get Cannot read properties of undefined (reading 'innerHTML') Error
console.log(htmlboxes[0].innerHTML);

So, the JS script must be placed 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 HTML elemets are declared first -->
    <div class="box">Btechgeeks</div>

    <!-- Here the Js script tag is palced at the bottom of the body after the declaration of HTML elements
    which is a GOOD Approach>
    <script src="index.js"></script>
  </body>
</html>
Inside the index.js script, the div element with the class name box is now accessible.

index.js:

// Get the element by class name which doesn't exist 
const htmlboxes = document.getElementsByClassName('doesNotExist');
console.log(htmlboxes); // []

// Here we get Cannot read properties of undefined (reading 'innerHTML') Error
console.log(htmlboxes[0].innerHTML);

In Brief

When attempting to access a property on an undefined value, the “Cannot read property of undefined” error occurs.

Undefined values are frequently returned when:

  • when we access a property on an object that does not exist.
  • when we access an index in an array that does not exist

React bootstrap side navbar – How to Create a Navigation Bar and Sidebar Using React

INTRODUCTION

React bootstrap side navbar: The navbar I focus on will be a sidebar via React. I will guide you through the React project creation. Make sure you have node.js installed in your system.

  1. Make a workspace folder and name it.
  2. Use npx create-react-app navbar to create a new project in the directory.
  3. Navigate inside it by using cd navbar in your IDE, I would recommend using Visual Studio Code.
  4. npm start in terminal to start the localhost server in your browser, I would recommend using Google Chrome.

 

DEPENDENCIES REQUIRED

React sidebar navigation: Go into package.json file and paste these dependencies in there:

"bootstrap": "^4.3.1",
"react": "^16.10.2",
"react-bootstrap": "^1.0.0-beta.14",
"react-dom": "^16.10.2",
"react-router-dom": "^5.0.1",
"react-scripts": "3.1.1",
"styled-components": "^4.3.2"

Now actually install these dependencies by opening a terminal and typing:

npm install

Paste this CDN link in the <head> tag inside index.html. It is for Font Awesome icons.

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.3/css/all.css" integrity="sha384-SZXxX4whJ79/gErwcOYf+zWLeJdY/qpuqC4cAa9rOGUstPomtqpuNWT9wdPEn2fk" crossorigin="anonymous">

 

MAKING COMPONENT STRUCTURE

React menu bar: Right click on the src folder and create a folder called components.

Right click on the components folder and create a Navbar.js file. Paste the code written below.

import React from "react";

export const NavigationBar = () => (
  <nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container-fluid">
      <a class="navbar-brand" href="#">
        Navbar
      </a>
      <button
        class="navbar-toggler"
        type="button"
        data-bs-toggle="collapse"
        data-bs-target="#navbarSupportedContent"
        aria-controls="navbarSupportedContent"
        aria-expanded="false"
        aria-label="Toggle navigation"
      >
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link active" aria-current="page" href="#">
              Home
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="#">
              Link
            </a>
          </li>
          <li class="nav-item dropdown">
            <a
              class="nav-link dropdown-toggle"
              href="#"
              id="navbarDropdown"
              role="button"
              data-bs-toggle="dropdown"
              aria-expanded="false"
            >
              Dropdown
            </a>
          </li>
          <li class="nav-item">
            <a
              class="nav-link disabled"
              href="#"
              tabindex="-1"
              aria-disabled="true"
            >
              Disabled
            </a>
          </li>
        </ul>
        <form class="d-flex">
          <input
            class="form-control me-2"
            type="search"
            placeholder="Search"
            aria-label="Search"
          />
          <button class="btn btn-outline-success" type="submit">
            Search
          </button>
        </form>
      </div>
    </div>
  </nav>
);

Now the header will look similar to the picture mentioned below.

Routing is how you get from page to page, so paste the code below inside <Router>. It basically says, if on this path, render this particular component:

<Switch>
  <Route exact path="/" component={Home} />
  <Route path="/about" component={About} />
  <Route component={NoMatch} />
</Switch>

This currently breaks the app because we do not have these components. So, let’s add these pages to make sure navigation will work.

Inside of src/components/Pages, create Home.js and paste this inside:

import React from "react";
import styled from "styled-components";
const GridWrapper = styled.div`
  display: grid;
  grid-gap: 10px;
  margin-top: 1em;
  margin-left: 6em;
  margin-right: 6em;
  grid-template-columns: repeat(12, 1fr);
  grid-auto-rows: minmax(25px, auto);
`;
export const Home = (props) => (
  <GridWrapper>
    <p>This is a paragraph and I am writing on the home page</p>
    <p>This is another paragraph, hi hey hello whatsup yo</p>
  </GridWrapper>
);

Inside of src/components/Pages, create About.js and paste this inside:

import React from "react";
import styled from "styled-components";
const GridWrapper = styled.div`
  display: grid;
  grid-gap: 10px;
  margin-top: 1em;
  margin-left: 6em;
  margin-right: 6em;
  grid-template-columns: repeat(12, 1fr);
  grid-auto-rows: minmax(25px, auto);
`;
export const About = () => (
  <GridWrapper>
    <h2>About Page</h2>
    <p>
      State at ceiling lay on arms while you're using the keyboard so this human
      feeds me.
    </p>
    <p>I am a kitty cat, sup, feed me, no cares in the world</p>
    <p>Meow meow, I tell my human purr for no reason but to chase after</p>
  </GridWrapper>
);

Inside of src/components/Pages, create Nomatch.js and paste this inside:

import React from 'react';
import styled from 'styled-components';
const Wrapper = styled.div`
  margin-top: 1em;
  margin-left: 6em;
  margin-right: 6em;
`;
export const NoMatch = () => (
  <Wrapper>
    <h2>No Match</h2>
  </Wrapper>
)

Do not forget to include the components in App.js file.

import { Home } from "./components/Pages/Home";
import { About } from "./components/Pages/About";
import { Nomatch } from "./components/Pages/Nomatch";

Alright, we can actually create the sidebar now.

Inside of components, create Sidebar.js

We know that we want to create a Sidebar component and export it for use inside of App.js. Put this inside Sidebar.js:

import React, { Component } from 'react'

export class Sidebar extends Component {
    render() {
        return (
            <div>
                
            </div>  
        )
    }
}

export default Sidebar

This basically is a class component, which renders a given code.

Then paste the code given below inside the return statement.

<SideNav></SideNav>

Now creating all the components required in separate files namely,  SideNav.js and NavItem.js.

NavItem.js

class NavItem extends React.Component {
  render() {
    return (
    );
  }
}

Inside of render, but above return, type:

const { active } = this.props;

This gets the active variable out of NavItem’s props. Now import the following

import { BrowserRouter as Router, Route, Link } from "react-router-dom";

Inside NavItem’s return, add this:

<StyledNavItem active={active}>
  <Link to={this.props.path} className={this.props.css} onClick={this.handleClick}>
    <NavIcon></NavIcon>
  </Link>
</StyledNavItem>

If you look at the props on <Link>, to is the path to go to, className passes in the CSS for the Font Awesome icon, and onClick will call the handleClick() method. Let’s create that method. Put it above render:

handleClick = () => {
  const { path, onItemClick } = this.props;
  onItemClick(path);
}

This arrow function gets path and onItemClick from NavItem’s props and then calls onItemClick().

Create StyledNavItem. The <Link> tag uses an anchor, so, the anchor selector is used. The only confusing part about the CSS is the part that uses props. It says: using the active prop, decide which of the colors to choose. So, if the home page is active, make the home page icon white:

const StyledNavItem = styled.div`
  height: 70px;
  width: 75px; /* width must be same size as NavBar to center */
  text-align: center; /* Aligns <a> inside of NavIcon div */
  margin-bottom: 0;   /* Puts space between NavItems */
  a {
    font-size: 2.7em;
    color: ${(props) => props.active ? "white" : "#9FFFCB"};
    :hover {
      opacity: 0.7;
      text-decoration: none; /* Gets rid of underlining of icons */
    }  
  }
`;

 

 

 

SideNav.js

Styled components used for styling the sidenav component.

const StyledSideNav = styled.div`
  position: fixed; /* Fixed Sidebar (stay in place on scroll and position relative to viewport) */
  height: 100%;
  width: 75px; /* Set the width of the sidebar */
  z-index: 1; /* Stay on top of everything */
  top: 3.4em; /* Stay at the top */
  background-color: #222; /* Black */
  overflow-x: hidden; /* Disable horizontal scroll */
  padding-top: 10px;
`;

We want SideNav to be a stateful component. This is because it needs to store what the current path is and based on that decide which icon should be selected and colored white.

Create a constructor. In there, create a state that holds the activePath, which we will set to the home path for now, and items that holds the information for our selectable icons

constructor(props) {
  super(props);
  this.state = {
    activePath: '/',
    items: [
      {
        path: '/', 
        name: 'Home',
        css: 'fa fa-fw fa-home',
        key: 1 
      },
      {
        path: '/about',
        name: 'About',
        css: 'fa fa-fw fa-clock',
        key: 2
      },
      {
        path: '/NoMatch',
        name: 'NoMatch',
        css: 'fas fa-hashtag',
        key: 3
      },
    ]
  }  
}
onItemClick = (path) => {
  this.setState({ activePath: path }); /* Sets activePath which causes rerender which causes CSS to change */
}

All this code says is change the activePath by setting the state. If you do not know, whenever you call setState(), React will rerender your component, which will render the change to show you selected a different icon.

Change your render to look like this:

render() {
  const { items, activePath } = this.state;
  return (
    <StyledSideNav>
      {
        /* items = just array AND map() loops thru that array AND item is param of that loop */
        items.map((item) => {
          /* Return however many NavItems in array to be rendered */
          return (
            <NavItem path={item.path} name={item.name} css={item.css} onItemClick={this.onItemClick} /* Simply passed an entire function to onClick prop */ active={item.path === activePath} key={item.key}/>
          )
        })
      }
    </StyledSideNav>
  );
}

Before return, items and activePath are retrieved from the state. In order to render out all NavItems, we loop through all of the items using map().

 

NOTE: Remember to import all required imports that are used in the files, specially the custom HTML tags.

 

 

Javascript check if object key exists – How to Check if a Key Exists in a JavaScript Object?

How to Check if a Key Exists in a JavaScript Object

Checking if a Key Exists in a JavaScript Object

Javascript check if object key exists: Checking if a key exists in a JavaScript Object can be done using the following ways

Method #1: Using ‘in’ Operator

Check if key exists javascript: Use the in operator, to check if a key exists in a JavaScript object. If the key is found in the given object or its prototype chain, the in operator returns true.

For Example:

"key" in gvn_obj

Example1:

// Create an object say Employ
const Employ = {
  EmpId: 2122,
  EmpName: 'Nick'
};

// Check if EmpId is present in the Employ object using the 
// 'in' operator. If it is present it prints true else false
// Here it prints true
console.log('EmpId' in Employ); 
// salary is NOT present in the Employ object hence it prints false
console.log('salary' in Employ); 

Output:

true
false

Explanation:

Here EmpId is present in the Employ object so it prints true
salary is NOT present in the Employ object hence it prints false

When using the in operator, the syntax is:

 str in object.

The value before the in keyword should be of the ‘string‘ or ‘symbol‘ type. Any value that is not a symbol is automatically converted to a string.

Example2:

// Create an object say Employ
const Employ = {
  1: 2122,
  EmpName: 'Nick'
};

// Here 1 is given as a string and it is present in Employ object
// so it prints true
console.log('1' in Employ); 
// Here 1 automatically gets converted to string hence it prints true
console.log(1 in Employ); 

Output:

true
true

NOTE:

In javascript, object keys can only be of the string or symbol types.
Despite the fact that our object appears to have a key of type integer, it is actually a string.

In our second console.log statement, the in operator will convert the 1 to a string.

Method #2: Using hasOwnProperty Method

Check if key is in object javascript: We can use the Object.hasOwnProperty() method to check if an object has a key,

For Example:

gvn_object.hasOwnProperty('key').

If the key exists in the object, the Object.hasOwnProperty() method returns true; otherwise, it returns false.

Example:

// Create an object say Employ
const Employ = {
  EmpId: 2122,
  EmpName: 'Nick'
};

// Check if EmpId is present in the Employ object using the 
// hasOwnProperty() method.
// If it is present it prints true else false
// Here it prints true since EmpId is present in Employ object
console.log(Employ.hasOwnProperty('EmpId'));

// salary is NOT present in the Employ object hence it prints false
console.log(Employ.hasOwnProperty('salary'));

Output:

true
false

Explanation:

Here EmpId is present in the Employ object so it prints true
salary is NOT present in the Employ object hence it prints false

NOTE:

  • The object.hasOwnProperty() method differs from the in operator.
  • The in operator checks for a key in an object and its prototype chain, but the object.hasOwnProperty() method just looks for the key directly on the object.

Method #3: Using Optional chaining

Javascript check if key exists: To check if a key exists in an object, we can use the Optional chaining (.) operator, such as :

gvn_object.key

If the key is present on the object, the Optional chaining operator returns the value of the key; otherwise, it returns undefined.

Example:

// Create an object say Employ
const Employ = {
  EmpId: 2122,
  EmpName: 'Nick'
};

// Check if EmpId is present in the Employ object using  
// Optional chaining (.) operator
// If it is present it prints value of key else undefined
// Here it prints 2122 since EmpId is present in Employ object
console.log(Employ.EmpId); 
// salary is NOT present in the Employ object hence it prints undefined
console.log(Employ.salary);

Output:

2122
undefined

Explanation:

Javascript check if key exists in object: We used the Optional chaining operator in the code sample to check if the EmpId and salary keys were present in the Employ object.

Because the EmpId key exists, Employ?.EmpId evaluates to 2122 and since the salary key does not exist, the Optional chaining operator returns undefined.

NOTE:

This conditional check would fail if an object had keys with 'undefined' values;
in such case, this approach would return a false negative.

Example:

// Create an object say Employ
const Employ = {
  EmpId: undefined,
};

console.log(Employ.EmpId); // prints undefined

if (Employ.EmpId !== undefined) {
  // The `EmpId` key exists in the Employ object,
  // but this never runs
  console.log('btechgeeks')
}

Output:

undefined

Explanation:

Even though the name key exists on the object in the code example, our conditional check does not account for the situation where its value is set to undefined.