Modern Class Syntax in JavaScript

In previous article, we saw how to create classes, constructors, properties and methods.

In Next Generation JavaScript, we skip constructor function and use Arrow functions for our methods. We can directly declare parameters.

Let’s see below example:

class Person{
    name = "Akanksha";
    address = "Delhi";  

  getPersonDetails = () => {
    console.log("Name: " + this.name);
    console.log("Location: " + this.address);
  }
}

class Student extends Person{
  cls = "12th";

  getStudentDetails = () => {
    console.log("Class: " + this.cls);
  }
}

const student = new Student();
student.getPersonDetails();
student.getStudentDetails();

Inheritance in JavaScript Classes

We have seen how to create Classes in JavaScript.

Let’s now learn how to inherit classes in JavaScript.

  • In inheritance, parameters and methods of base class can be used in derived class.
  • We inherit class using extend keyword.
  • constructor is a default function which is automatically called when a class is instantiated. It is used to initialize the parameters of the class.
  • super is a method that is used to call base class’ constructor.
  • this keyword is used to access the parameters for current object.

Below is a sample code for inheritance

class Person{
  constructor(personName, personAddress){
    this.name=personName;
    this.address=personAddress;  
  }
  getPersonDetails(){
    console.log("Name: " + this.name);
    console.log("Location: " + this.address);
  }
}

class Student extends Person{
  constructor(name, address,studentClass, studentId){
    super(name, address);
    this.studentClass = studentClass;
    this.Id=studentId;
  }
  getStudentDetails(){
    console.log("Class: " + this.studentClass);
    console.log("ID: " + this.Id);
  }
}

class CollegeStudent extends Student{
  constructor(name, address, stdCls, id, clgName){
    super(name, address, stdCls, id);
    this.CollegeName=clgName;
  }
  getDetails(){
    console.log("College Name: " + this.CollegeName);
  }
}

const student = new CollegeStudent("Akanksha","Delhi","12th",12345,"NIT");
student.getPersonDetails();
student.getStudentDetails();
student.getDetails();

Classes in JavaScript

  • Classes are the core feature of next generation JavaScript. Classes are generally blueprints of objects. A Class can have both properties and methods.
  • Methods are functions attached to classes where properties acts as variables and are attached to classes.
  • A Class is instantiated with a new keyword.
  • Classes also support Inheritance. A class can inherit another class and use its properties and methods.
  • Constructor is a default method used for creating and initializing an object created with the class. This is automatically executed whenever you instantiate a class. In this, you can set up properties with this keyword.
  • Let’s see an example:
class Person{
  constructor(){
    // setting up properties using this keyword
    this.name="Akanksha";
    this.address="Delhi";  
  }
  // creating a custom method within a class
  getName(){
    console.log("Name: " + this.name + " and Location: " + this.address);
  }
}

// creating an object of the class using new keyword.
// constructor function is called as soon as you instantiate a class using new keyword
const prsn = new Person();

// calling method using the object of the class
prsn.getName();

You can also pass the data while instantiating the class

Related Article: Inheritance in JavaScript

imports and exports in JavaScript

When we write JavaScript code, we prefer to split our code in multiple functions and different files. But we want to use these files from one another.

For this, we use import and export. We will also see the concept of named export and default export.

Default Export: We can have only one default export per file. When we import, we have to specify a name of the import. This name can be the actual name or any other name we like. We have to use default keyword when defining the default export.

Named Export: We can have multiple named exports from a single file, but the name of the import module should be same as the name of the export module. They should me enclosed in curly brackets {} while importing.

Let’s have a file names Person.js with following structure. We are using default export here.

const Person = {
  name:"Akanksha"
}
export default Person;

Another file test.js with the following structure. We are using named export here.

export const settings = () => {}
export const url = "URL";

Another file as App.js where we will be importing these two files

// these are default exports
import Person from './Person.js'
import prsn from './Person.js'

// these are named exports
import {settings} from './test.js'
import {url} from './test.js'

The named exports can also be combined in one import like following

import {settings, url} from './test.js'

If there are multiple named exports from one file, we can import them together like below

import * as testData from './test.js'

We can then use this as testData.settings when we want to access that module.

Arrow Functions in JavaScript

I am using jsbin.com for demo purpose.

  • Arrow functions is a different syntax for JavaScript functions.
  • A normal JavaScript function looks like this with a function keyword. Parameters are optional.
function myFunc(parameters){
// lines of code
}

Below is an example of JavaScript function.

function myFunc(name){
  console.log(name);
}
myFunc("Akanksha");

The output of above code is “Akanksha“.

Arrow Functions
  • An Arrow function looks like this. Parameters are optional.
const myFunc = (parameters) => {
// lines of code
}
  • Solves many problems that we have with this keyword.

Below is the conversion of above JavaScript function in an Arrow function.

const myFunc = (name) => {
  console.log(name);
}
myFunc("Akanksha");

The output of above code is also “Akanksha“.

  • If there is a single parameter, you can omit the round brackets. This syntax is not valid with zero or multiple parameters. You have to provide brackets at that time.
const myFunc = name => {}
  • Passing multiple parameters
const myFunc1 = (name, age) => {
  console.log(name, age);
}
myFunc1("Akanksha",28);

Below is the output of above code

  • Syntax when Arrow function have return statement as the only statement. We do not need to include curly brackets and return keyword. Complete Arrow function can be written in single line. Below is an example of an Arrow function with a single line of code as the return statement. Please NOTE that this one-liner syntax is not applicable if there are multiple statements with return statement as one of them OR any other statement apart from return statement. This syntax works only with return statement as a single statement.
const addition = (num1, num2) => {
  return num1+num2;
}
console.log(addition(10,20));

const add = (n1, n2) => n1+n2;
console.log(add(20,30));

Below is the output of above code

var, let & const in JavaScript

  • With ES6, a version of JavaScript, two new keywords, let & const, were introduced to create variables.
  • var is still used to declare variables, but let & const are recommended.
  • Use let if you want to create a variable and use const if you want to create a variable that holds a constant value (a value that you assign once and never change).

var

  • We use var to declare variables in JavaScript.
  • It is function or globally scoped.
  • Can be re-declared in the same scope
var name="David";
// can use name here
function getName(){
// can use name here as well
}

var name="Mike"; // can be easily re-declared

function myFunc(){
var address="US";
// address can be used anywhere within this function, but not outside this function.
}

let

  • It is used to declare variables.
  • These variables are block scoped.
  • They cannot be re-declared
for(let i=1;i<=10;i++){
console.log(i); // i is used here
}
// i cannot be used here, throws an error: i not defined

let i=100; // cannot be re-declared, throws an error: i is already declared

function newFunction(){
let phone=78989879;
// phone can be used anywhere within the function, but NOT outside the function.
}

const

  • It is used to declare constant variables.
  • They cannot be re-assigned.
  • We generally use const variables for defining settings like URL link, database settings etc.
const PI = 3.1416;
PI = 3.14; // This will throw an error
const PI=45.23; // This will also throw an error: Assignment to constant variable

Pass data from Child component to Parent component

we have previously seen how to pass data from parent component to child component. In this article, we will see how to pass data from child component to parent component.

For this, we pass functions as props in React component.

Let’s create a new react application. Delete all the files from src folder EXCEPT index.js. Create a new file SearchBar.js in src folder.

index.js

Replace the existing code with below code

import React from 'react';
import ReactDOM from 'react-dom';
import SearchBar from './SearchBar'

class App extends React.Component {
    // defining state
    state = { name: '' };
    render() {
        return (                    
            <div>
                <SearchBar onNameSubmit={this.onSearchSubmit}/>
            </div>
        );
    }

    onSearchSubmit(userName){
        console.log(userName);
    }
}

ReactDOM.render(<App />, document.getElementById('root'));
SearchBar onNameSubmit={this.onSearchSubmit}
This statement will pass function as prop to the Child Component, SearchBar
SearchBar.js

Paste the below code in this file

import React from 'react';

class SearchBar extends React.Component {
    constructor(){
        super();
        this.state = { name: '' };
        this.onFormSubmit=this.onFormSubmit.bind(this); 
    }
    
    onFormSubmit(event) {
        event.preventDefault();
        this.props.onNameSubmit(this.state.name);
    }

    render() {
        return (           
          <div className="ui segment">             
            <form className="ui form" onSubmit={this.onFormSubmit}>       
               <div className="field">
                  <label>Enter your name</label>
                  <input type="text" value={this.state.name} onChange={(e) => this.setState({ name: e.target.value })} />
               </div>
             </form>
           </div>
        );
    }
}

export default SearchBar;
this.props.onNameSubmit(this.state.name);
This piece of code will pass the value from child component to parent component using functions in props.

Below is the output of above code
Type your name or anything else in the textbox, press enter. You can see the value you types in console.

Get User Input in ReactJS Application

We know that ReactJS is used to create the View part of our application.

In this article, we will create a TextBox and get that data in state, and use it to set the value property of the TextBox.

Create a new react application. Delete all the files from src folder EXCEPT index.js

Replace the existing code with the below code in index.js file

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
    state = { name: '' };
    render() {
        return (
            < div >
                Enter your name: <input type="text" value=   {this.state.name} onChange={e => this.setState({ name:e.target.value })} />
                <div>Hi {this.state.name}!</div>
            </div >
        );
    }
}

ReactDOM.render(<App />, document.getElementById('root'));

In this, whatever the user writes in the TextBox, it gets stored in state and then assigned to the value property of the TextBox.
We can then use this state value wherever we want. In this example, we are simply displaying it in another div.

Get Weather (Summer/Winter) using ReactJS Application

I came through below example in one of the articles on internet, so thought of mentioning it here. This example explains a lot of concepts of ReactJS.

In this, we will get the latitude of the current location of the user, based on that we display the season (winter or summer).

Create a new react application. Delete all the files from src folder except index.js. Create new files in src folder: Season.js, Loading.js and index.css.

Also install Semantic UI React package.

npm install --save semantic-ui-react

Include below link in index.html file

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" >
index.js

Copy and paste below code in index.js file. User has to allow the application to access the location.

import React from 'react';
import ReactDOM from 'react-dom';
import Season from './Season';
import Loading from './Loading';
import './index.css';

class App extends React.Component {
    // initializing component state
    state = { lat: null, errMsg: '' };

    // initial data loading
    componentDidMount() {
        window.navigator.geolocation.getCurrentPosition(
            position => this.setState({ lat: position.coords.latitude }),
            err => this.setState({ errMsg: err.getMessage() })
        );
    }

    // custom method
    renderComponent() {
        if (this.state.errMsg && !this.state.lat) {
            return <div><b>Error: </b>{this.state.errMsg}</div>
        }
        else if (!this.state.errMsg && this.state.lat) {
            return <Season lat={this.state.lat} />
        }
        else {
            return <Loading message="Kindly allow us to access your location..." />
        }
    }

    render() {
        return (            
            <div>
                {this.renderComponent()}
            </div>

        );
    }
}

ReactDOM.render(<App />, document.getElementById('root'));
Season.js

Get the icon name and details from Semantic UI React Site. There are lots of icons available for use.
Copy and paste below code in below file

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

// get the season based on latitude and current month
const getSeason = (lat, month) => {
    if (month > 2 && month < 9) { return lat > 0 ? 'summer' : 'winter';
    } else {
        return lat > 0 ? 'winter' : 'summer';
    }
}

// configuration 
const seasonConfig = {
    summer: {
        text: "It's hot!",
        iconName: 'sun'
    },
    winter: {
        text: "It's cold!",
        iconName: 'snowflake'
    }
}

// functional component
const Season = (props) => {
    const currentSeason = getSeason(props.lat, new Date().getMonth());
    const { text, iconName } = seasonConfig[currentSeason];
    return (
        <div className={`season-display ${currentSeason}`}>
            <i className={`massive icon-left ${iconName} icon`} />
            <h1>{text}</h1>
            <i className={`massive icon-right ${iconName} icon`} />
        </div>
    );
};

export default Season;
Loading.js

Copy and paste below code in this file

import React from 'react';
import ReactDOM from 'react-dom';
import { Loader, Dimmer } from 'semantic-ui-react';

// loading the Loader component
const Loading = props => {
    return (
        <Dimmer active>
            <Loader>{props.message}</Loader>
        </Dimmer>
    );
}

//setting default value of Loader component
Loading.defaultProps = {
    message: "Loading..."
};

export default Loading;
index.css

Copy and paste below code in index.css file

.icon-left{
    position: absolute;
    top: 10px;
    left: 10px;
}
.icon-right{
    position: absolute;
    bottom: 10px;
    right: 10px;
}
.season-display{
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}
.season-display.winter i{
    color: blue;
}
.season-display.summer i{
    color: orange;
}
.winter{
    background-color: aquamarine;
}
.summer{
    background-color: orange;
}

As it is January here and I am in Northern Hemisphere, it’s winters here!!
Below is the output of above code

Set default values for Props in ReactJS Components

When we define props in components, we usually pass values to them But what will happen if we do not pass any value? In this case, no data will be displayed.

There is sometimes a need when we want to specify a default value for properties of components just in case we forget to pass the values to the properties.

Let’s continue with this example where we have created a Comments component ad passed values in the properties.

index.js

Replace the original code with the below code.

import React from 'react';
import ReactDOM from 'react-dom';
import { Comment } from 'semantic-ui-react';
import Comments from './Comments';
import Approvalcard from './ApprovalCard';

const App = function () {
    return (
        // We will not pass the values in props for last Comments component
        <Comment.Group>
            <Approvalcard>
                <Comments user="Apoorv" time="May" commentData="Comment1" />
            </Approvalcard>
            <Approvalcard>
                <Comments user="Akanksha" time="Yesterday" commentData="Comment2" />
            </Approvalcard>
            <Approvalcard>
                <Comments />
            </Approvalcard>
        </Comment.Group>
    );
};

ReactDOM.render(<App />, document.getElementById('root'));
Comments.js

Replace the original code with the below code

import React from 'react';
import { Comment} from 'semantic-ui-react';
import faker from 'faker';

const Comments = function (props) {
    return (
            <Comment>
                <Comment.Avatar src={faker.image.avatar()} />
                <Comment.Content>
                    <Comment.Author as='a'>{props.user}</Comment.Author>
                    <Comment.Metadata>
                        <div>{props.time}</div>
                    </Comment.Metadata>
                    <Comment.Text>{props.commentData}</Comment.Text>
                    <Comment.Actions>
                        <Comment.Action>Reply</Comment.Action>
                    </Comment.Actions>
                </Comment.Content>
            </Comment>
    );
}

// defining default values for the properties
Comments.defaultProps={
    user:"User Name",
    time: "Now",
    commentData: "Comment"
};

export default Comments;

Below is the output of above code. You can see that the last Comment component has taken the default property values.

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started