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.

 

JS get last character of a string – How to Get the Last Character of a String in JavaScript?

How to Get the Last Character of a String in JavaScript

JS get last character of a string: Given a string, the task is to print the last character of the given string using JavaScript.

Get the Last Character of a String Using JavaScript

Method #1: Using charAt() Function

To get the last character of a string, use the string’s charAt() method, passing it the last index as an argument. For example, gvn_str .charAt(str.length – 1) returns a new string with the string’s last character.

The charAt() function returns the character present at the specified index.

Here gvn_str.length is used to find the total length of the given string.

Approach:

  • Give the string as static input and store it in a variable.
  • Pass the last index of the string(length of the string – 1) to the charAt() function and apply it to the given string to get the last character of the given string.
  • Print the last character of the given string.
  • The Exit of the Program.

Below is the implementation:

// Give the string as static input and store it in a variable.
const gvn_str = 'hello btechgeeks';
// Pass the last index of the string(length of the string - 1) to the
// charAt() function and apply it on the given string to get the last
// character of the given string
const last_char = gvn_str.charAt(gvn_str.length - 1);
// Print the last character of the given string
console.log(" The last character of the given string = ",last_char); 

Output:

The last character of the given string = s

NOTE:

JavaScript indexes are zero-based. Since the first character in the string has an 
index of 0, the last character has an index of gvn_str.length - 1.

Passing index on an Empty String

The charAt method returns an empty string if an index is passed that does not exist on the string.

// Give the empty string as static input and store it in a variable.
const gvn_str = '';
// Pass the last index of the string(length of the string - 1) to the
// charAt() function and apply it on the given string to get the last
// character of the given string
const last_char = gvn_str.charAt(gvn_str.length - 1);
// Print the last character of the given string
console.log(last_char);

Output:


Method #2: Using slice() Function

Approach:

  • Give the string as static input and store it in a variable.
  • Pass the last index value using negative indexing -1 to the slice() function and apply it on the given string to get the last character of the given string.
  • Print the last character of the given string.
  • The Exit of the Program.

Below is the implementation:

// Give the string as static input and store it in a variable.
const gvn_str = 'good morning';
// Pass the last index value using negative indexing -1 to the 
// slice() function and apply it on the given string to get the 
// last character of the given string
const last_char = gvn_str.slice(-1)
// Print the last character of the given string
console.log(" The last character of the given string = ",last_char); 

Output:

The last character of the given string = g

Method #3: Using Bracket Notation to Access the Index on the String.

To get the last character of a string, use bracket notation to access the string at the last index. For example, gvn_str[gvn_str.length – 1] returns the string’s last character.

Approach:

  • Give the empty string as static input and store it in a variable.
  • Use the bracket notation to the last character of a given string and store it in another variable.
  • Here gvn_str.length – 1 represents the last index
  • Print the last character of the given string.
  • The Exit of the Program.

Below is the implementation:

// Give the empty string as static input and store it in a variable.
const gvn_str = 'hello btechgeeks';
// Use the bracket notation to the last character of a given string
// Here gvn_str.length - 1 represents the last index
const last_char = gvn_str[gvn_str.length - 1];
// Print the last character of the given string
console.log(" The last character of the given string = ",last_char);

Output:

The last character of the given string = s

 

Javascript string slice – The String slice() method in JavaScript | Definition, Syntax, How it works, Examples of JavaScript String slice() method

JavaScript String slice() method

Javascript string slice: In this ultimate tutorial, we have discussed complete details about the JavaScript String slice() method like definition, syntax, how to use the string slice() method to extract a substring from a string with examples.

JavaScript String slice() method – Definition

Return a new string from the part of the string included between the begin and end positions.

The original string is not mutated.

end is optional.

"This is my work".slice(5)
//"is my work"
"This is my work".slice(5,10)
//"is my"

If you set a negative first parameter, the start index starts from the end, and the second parameter must be negative as well, always counting from the end:

"This is my work".slice(-4)
//"work"
"This is my work".slice(-4,-1)
//"wor"

String.prototype.slice() Syntax

slice(beginIndex)
slice(beginIndex, endIndex)

Parameters Included in String Slice() Method

1. beginIndex: 

The zero-based index whereat to start extraction. In the case of negative, it is treated as str.length + beginIndex. (For instance, if beginIndexis -2, it is interpreted as str.length – 2.) If beginIndex is not a numeral after Number (beginIndex), it is considered as 0. In case beginIndexis greater than or equal to the str.length, an empty string is returned.

2. endIndex (Optional):

The zero-based index before which to end extraction. The character at this index wouldn’t be involved.

If endIndex is excluded or undefined, or greater than str.length, slice() extracts to the edge of the string. If negative, it is handled as str.length + endIndex. (For instance, if endIndex is -5, it is treated as str.length – 5.) If it is not undefined, and the Number(endIndex) is not positive, an empty string is returned.

If endIndex is defined, then beginIndex should be smaller than endIndex otherwise, an empty string is returned. (For example, slice(-3, 0), slice(-1, -3), or slice(3, 1) returns "".)

Return Values

It returns a part or a slice of the furnished input string.

Do Check:

Examples on String slice() method in JavaScript

In this section, you will find plenty of example programs to learn how to create and use the javascript string slice() method in various conditions:

1. Using slice() to create a new string

The following examples utilize the string slice() method to create a new string.

let str1 = 'The morning is upon us.', // the length of str1 is 23.
    str2 = str1.slice(1, 8),
    str3 = str1.slice(4, -2),
    str4 = str1.slice(12),
    str5 = str1.slice(30);
console.log(str2)  // OUTPUT: he morn
console.log(str3)  // OUTPUT: morning is upon u
console.log(str4)  // OUTPUT: is upon us.
console.log(str5)  // OUTPUT: ""

2. Using slice() with negative indexes

The following example uses slice() with negative indexes.

<script> 
var str = "Javatpoint"; 
document.writeln(str.slice(-5)); 
</script>

Output:

point

Doctype html unexpected token – How to Fix Unexpected token Error in JavaScript?

How to Fix Unexpected token Error in JavaScript

Doctype html unexpected token: The “Uncaught SyntaxError: Unexpected token” error can occur for a variety of reasons, including:

  • Using a <script /> tag that leads to an HTML file rather than a JS file.
  • Receiving an HTML response from a server where JSON is expected,
  • Having a <script /> tag that leads to the wrong path.
  • When your code is missing or contains extra brackets, parenthesis, or commas.
  • When you forgot to close the <script />tag.

Let us see some of the cases where the “Uncaught SyntaxError: Unexpected token” error Occurs

Cases where the “Uncaught SyntaxError: Unexpected token” error Occurs

Example1

Unexpected token js: Below is an example of an error: our script tag points to a html file rather than a JS file.

index.html:

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

  <body>
    <!-- Here script tag is pointing to an html file instead of JS file 
    Hence Uncaught SyntaxError: Unexpected token '<' occurs-->
    <script src="index.html"></script>
  </body>
</html>

NOTE:

Check that any script tag you use lead to a valid path, and try to rename all your files
using just lowercase characters. 
If the file name contains uppercase letters or special characters, the error may occur.

Example2

Unexpected token doctype: The other common cause of the “Uncaught SyntaxError: Unexpected token” is when we forget to close a script tag.

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

    <!-- Here we forgot to close the script tag, hence 
    Uncaught SyntaxError: Unexpected token '<' occurs -->
    <script
      console.log("Uncaught SyntaxError: Unexpected token '<'");
    </script>
  </head>

  <body></body>
</html>
  • When attempting to parse JSON data, the error is also generated if you make an http request to a server and receive an HTML response.
  • To solve this we can use console.log. The response you receive from your server and ensure it is a proper JSON string free of HTML tags.
  • Alternatively, you can open your browser’s developer tools, navigate to the Network tab, and inspect the response.

Example3: index.js (Giving another extra curly brace)

// Create a function say multiply whict accepts two numbers
// as arguments and returns the multiplication result
function multiply(x, y) {
  // Multiply the above passed two numbers and return the result
  return x * y;
}}

Output:

}}
^

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

Explanation:

Here we gave another extra curly brace, hence SyntaxError: Unexpected token } occured

These syntax errors are difficult to spot, but an useful tip is:

  • If you receive the “Uncaught SyntaxError: Unexpected token ‘<‘” (ovserve the ‘<‘) error, you are most likely attempting to read HTML code that begins with ‘<‘.
  • If your error message comprises a curly brace, parenthesis, comma, colon, etc., you most certainly have a SyntaxError, which occurs when your code has an additional or missing character.

Example4: index.js (Giving colons two times(::) instead of once(:))

// Create an object and store it in a variable
const obj = {
  // Here we gave colons two times(::) instead of once(:) to separate the key-value pairs
  // so,the SyntaxError: Unexpected token : occurs
  Website:: "Btechgeeks",
}

Output:

Website:: "Btechgeeks",
^

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

Explanation:

Here we gave colons two times(::) instead of once(:) to separate the key-value pairs 
so,the SyntaxError: Unexpected token : occurs

Example5: index.js (Giving an extra comma)

// Create an object and store it in a variable
const obj = {
  // Here we gave an extra comma(,) 
  // Hence the SyntaxError: Unexpected token occurs
  Website: "Btechgeeks",,
}

Output:

Website: "Btechgeeks",,
^

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

Fixing the “Uncaught SyntaxError: Unexpected token” Error

To resolve the “Uncaught SyntaxError: Unexpected token” error, make the following changes:

  • We should not have a <script/> tag that points to an HTML file, instead of a JS file.
  • Instead of requesting an HTML file from a server, you are requesting JSON.
  • There is no <script/> tag pointing to an incorrect path.
  • There must be no missing or excessive brackets, parenthesis, or commas.
  • Do not forget to close a <script tag.

Javascript get object class name – How to Get the Class Name of an Object in JavaScript?

How to Get the Class Name of an Object in JavaScript

Javascript get object class name: To obtain the class name of the object, such as obj.constructor.name, access the name property on the object’s constructor.

The constructor property returns a reference to the constructor function that created the instance object.

index.js:

// @@ Create a contsructor say Employ
class Employ {}

// Create an object for the above class using the new keyword
const obj = new Employ();
// Get the name of the contsructor using the Object.constructor.name attribute by applying it on the above object
console.log(obj.constructor.name);

Output:

Employ

Explanation:

Here we accessed the name property on the Object.constructor property.

The Object.constructor property returns a reference to the constructor function, that was used to create the object.

// @@ Create a class say Employ
class Employ {}

// Create an object for the above class using the new keyword
const obj = new Employ();
// Get the reference to the constructor using the constructor attribute by applying it on the above object
console.log(obj.constructor);

Output:

[Function: Employ]

Javascript get class name of object: Another option is to create a method on the class that returns the object’s class name.

// Create a class say Employ
class Employ {
  // Inside the class create a function say getClassName()
  // which returns the name of the class using the constructor.name property
  getClassName() {
    return this.constructor.name;
  }
}
// Create an object for the above class using the new keyword
const obj = new Employ();

// Apply getClassName() function on the above object 
// to get the class name of the above created class
const class_name = obj.getClassName();
// Print the class name 
console.log(class_name);

Output:

Employ

If you frequently need to access the Object.constructor.name property, you can create a method to hide it.

NOTE:

All objects (excluding those created with Object.create(null)) have a constructor property.

Objects that are created without a constructor function have a constructor property that refers to the main/primary Object constructor for the particular type.

index.js:

// Get the type of the contrusctor using the constructor.name
// Property. Here {} represents object hence it returns Object
console.log({}.constructor.name); 

// Get the type of the contrusctor using the constructor.name
// Property. Here [] represents an array hence it returns Array
console.log([].constructor.name); 

Output:

Object
Array

Javascript array contains object – How to Check if Array Contains an Object in JavaScript?

How to Check if Array Contains an Object in JavaScript

Javascript array contains object: In this article, we are going to check if the javascript array contains an object or not.

Checking if Array Contains an Object in JavaScript

We can check whether the array contains an object in javascript in a number of ways. The following are the ways to check:

Method #1: Using Array.some() Method

  • Invoke/call the Array.some() method by passing it a function.
  • The function should verify whether the object’s identifier is equal to a specific value and return true if it is.
  • If the conditional check is satisfied at least once, Array.some() method will return true.

Example1:

// This supports in IE 9-11

// Create an array of objects and store it in a variable
const websites = [
  {sno: 1, websiteName: 'Btechgeeks'},
  {sno: 2, websiteName: 'Python-Programs'},
  {sno: 3, websiteName: 'SheetsTips'},
];

// Check whether the array contains any specific object using the 
// Array.some() function
const objectFound = websites.some(element => {
  // If the object is found return true
  if (element.sno === 2) {
    return true;
  }
    // Else return false
  return false;
});

console.log(objectFound);

if (objectFound) {
  // object is contained in array
}

Output:

true

Example2:

// This supports in IE 9-11

// Create an array of objects and store it in a variable
const websites = [
  {sno: 1, websiteName: 'Btechgeeks'},
  {sno: 2, websiteName: 'Python-Programs'},
  {sno: 3, websiteName: 'SheetsTips'},
];

// Check whether the array contains any specific object using the 
// Array.some() function
const objectFound = websites.some(element => {
  // If the object is found return true
  if (element.sno === 4) {
    return true;
  }
    // Else return false
  return false;
});

console.log(objectFound);

if (objectFound) {
  // object is contained in array
}

Output:

false

Explanation:

Here sno 4 does not exist in a given object, hence it returns false
  • The function that we passed to the Array.some() method will be invoked with each value of the array.
  • The Array.some short circuits and returns true, If it returns a truthy value at least once.
  • In our condition, we check to see if the object’s identifier field equals a specified value. If it is, we know the object is there in the array.

Method #2: Using Array.find() Method

To check if a JavaScript array contains an object, use the following steps:

  • Invoke/call the Array.find() method by passing it a function.
  • The function should verify whether the object’s identifier is equal to a specific value and return true if it is.
  • If the conditional check is satisfied at least once, Array.find() will return the object.

Example1:

// This does NOT supports in IE 6-11

// Create an array of objects and store it in a variable
const websites = [
  {sno: 1, websiteName: 'Btechgeeks'},
  {sno: 2, websiteName: 'Python-Programs'},
  {sno: 3, websiteName: 'SheetsTips'},
];

// Check whether the array contains any specific object using the 
// Array.find() function
const objectFound = websites.find(element => {
  // If the object is found return true
  if (element.sno === 3) {
    return true;
  }
    // Else return false
  return false;
});

console.log(objectFound);

if (websites !== undefined) {
  // Then object is contained in an array
}

Output:

{ sno: 3, websiteName: 'SheetsTips' }

Explanation:

Here sno: 3 exists in the given array, hence the Array.find() method returns that object
  • The function that we passed to the Array.find() method gets invoked with each array element until it gives a true value or iterates over all array elements.
  • If the condition is met, Array.find returns the array element; else, undefined is returned.
  • Since the condition in the above example returns true, the find() method returns the object.

NOTE:

When you need to access additional properties on the object, use 'Array.find' 
instead of 'Array.some'; unfortunately, 'Array.find' is not supported in IE 6-11.

Method #3: Using Array.findIndex() Method

To check if a JavaScript array contains an object, use the following steps:

  • Invoke/call the Array.findIndex()method by passing it a function.
  • The function should verify whether the object’s identifier is equal to a given value and return true if it is.
  • Array.findIndex returns the index of the object if meets the condition and -1 if none do.

Example1:

// This does NOT supports in IE 6-11

// Create an array of objects and store it in a variable
const websites = [
  {sno: 1, websiteName: 'Btechgeeks'},
  {sno: 2, websiteName: 'Python-Programs'},
  {sno: 3, websiteName: 'SheetsTips'},
];

// Check whether the array contains any specific object using the 
// Array.findIndex() function
const objectFound_index = websites.findIndex(element => {
  // If the object is found i.e, true then it returns index value
  if (element.sno === 1) {
    return true;
  }
    // Else if false return -1
  return false;
});

console.log(objectFound_index);

if (objectFound_index !== -1) {
  // Then object is contained in an array
}

Output:

0

Explanation:

Here sno: 1 exists in the given array, hence the findIndex() method returns the index of sno1 i.e 0

Example2:

// This does NOT supports in IE 6-11

// Create an array of objects and store it in a variable
const websites = [
  {sno: 1, websiteName: 'Btechgeeks'},
  {sno: 2, websiteName: 'Python-Programs'},
  {sno: 3, websiteName: 'SheetsTips'},
];

// Check whether the array contains any specific object using the 
// Array.findIndex() function
const objectFound_index = websites.findIndex(element => {
  // If the object is found i.e, true then it returns index value
  if (element.sno === 5) {
    return true;
  }
    // Else if false return -1
  return false;
});

console.log(objectFound_index);

if (objectFound_index !== -1) {
  // Then object is contained in an array
}

Output:

-1

Explanation:

Here sno: 5 does NOT exist in the given array, hence the findIndex() method returns -1

The Array.findIndex method is identical to the Array.find method, except that it returns the index of the element that meets the conditional check rather than the element itself.

Array.findIndex executes its callback function with each element in the array until a true value is returned or the array’s values are exhausted.

NOTE:

This Array.findIndex() method returns -1 if all calls to its callback function return a false value.

Method #4: Using Array.filter() Method

To check if a JavaScript array contains an object, use the following steps:

  • Invoke/call the Array.filter() method by passing it a function.
  • The function should verify whether the object’s identifier is equal to a given value and return true if it is.
  • The Array.filter method will return an array of objects that satisfy the conditional check (if any)

Example1

// This supports in IE 9-11

// Create an array of objects and store it in a variable
const websites = [
  {sno: 1, websiteName: 'Btechgeeks'},
  {sno: 2, websiteName: 'Python-Programs'},
  {sno: 3, websiteName: 'SheetsTips'},
];

// Check whether the array contains a specific object using //the  Array.findIndex() function
const objectFound = websites.filter(element => {
  // If the object is found i.e, true then it returns that corresponding object values
  if (element.sno === 2) {
    return true;
  }
    // Else if false returns an empty array
  return false;
});

console.log(objectFound);

if (objectFound.length > 0) {
  // The object is contained in a given array
}

Output:

[ { sno: 2, websiteName: 'Python-Programs' } ]

Example2

// This supports in IE 9-11

// Create an array of objects and store it in a variable
const websites = [
  {sno: 1, websiteName: 'Btechgeeks'},
  {sno: 2, websiteName: 'Python-Programs'},
  {sno: 3, websiteName: 'SheetsTips'},
];

// Check whether the array contains a specific object using //the  Array.findIndex() function
const objectFound = websites.filter(element => {
  // If the object is found i.e, true then it returns that corresponding object values
  if (element.sno === 5) {
    return true;
  }
    // Else if false returns an empty array
  return false;
});

console.log(objectFound);

if (objectFound.length > 0) {
  // The object is contained in a given array
}

Output:

[]

 

JavaScript — Breaking Down The Shortest Possible FizzBuzz Answer

JavaScript — Breaking Down The Shortest Possible FizzBuzz Answer

Fizzbuzz solution javascript: FizzBuzz is a classic programming task, usually used in software development interviews to determine if a candidate can code.

The Question

Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers that are multiples of both three and five print “FizzBuzz”.

We just need to loop through each number from 1 to 100. So, one of the simplest solutions can be achieved with a for loop:

for (var i=1; i < 101; i++){
    if (i % 15 == 0) console.log("FizzBuzz");
    else if (i % 3 == 0) console.log("Fizz");
    else if (i % 5 == 0) console.log("Buzz");
    else console.log(i);
}

If you run this code in your console, you’ll see this works just fine. Here’s a snippet of the first 16 iterations through the loop:

FizzBuzz Output

There are probably hundreds of different ways to solve FizzBuzz. Some are cleaner, faster, and better than others. Some are just plain crazy.

for(let i=0;i<100;)console.log((++i%3?'':'fizz')+(i%5?'':'buzz')||i)

JavaScript Concepts You Need to Understand

Fizzbuzz javascript solution: This code utilizes many different JavaScript concepts to solve FizzBuzz. I’ve written about all of these concepts in the past — so I’ll give minor explanations in this article, but feel free to use these links to further your understanding if something isn’t entirely clear:

  • Logical OR / Short Circuit Evaluation
  • The Ternary Operator
  • Truthy & Falsy Values
  • The Increment Operator
  • Type Coercion

Breaking Down The Solution

The first thing we’ll do to better understand our code is to space things out a bit.

Here’s the same code with some breathing room added:

for(let i=0;i<100;)
  console.log(
    ( ++i%3 ? '' : 'fizz' ) + ( i%5 ? '' : 'buzz' ) || i
  )

Ok. Now we can start to see what our code is attempting to do. We clearly have a for loop that goes from 0 — 100. And within our for loop, we are attempting to console.log something.
Let’s take a deeper look at our first set of parenthesis within our console.log:

++i%3 ? '' : 'fizz'

If we recall the syntax for ternary operators, it is:

condition ? true result : false result ;

In this example, the condition that we’re testing is ++i%3. If that is true, then '' will be returned. If ++i%3 is false, then fizz will be returned.

++i%3

Above, the increment operator is being used. Using the operator before the operand ++i will increment the operator i before returning it. This means that on our first pass through the loop, i will increase from 0 to 1.
Now that i has increased to 1, our code will then check to see if 1%3 is true or false.
1 % 3 utilizes the remainder operator. The remainder operator returns the remainder of one number divided another. In this case we’ll check to see what the remainder of 1/3 is.
The remainder is 1 and thus our ternary condition is now simplified to 1:

1 ? '' : 'fizz'

A ternary condition is a Boolean Context. This means whatever we are testing must coerce to a true or false value.

true ? '' : 'fizz'

Since we have a true value in our ternary condition, the first expression is returned and the result of our first set of parenthesis is a blank string: ''.

Here’s where we’re at now:

for(let i=0;i<100;)
  console.log(
    ( '' ) + ( i%5 ? '' : 'buzz' ) || i
  )
i%5 ? '' : 'buzz'
console.log( '' + '' || i )

Since an empty string plus an empty string is still an empty string, our code will reduce further:

console.log( '' || i )

Now our code utilizes the JavaScript Logical OR Operator ||. Because an empty string is one of the seven falsy values in JavaScript, we skip over that operand entirely and accept whatever the second operand is. In this code, it is i.

console.log(i)