How to build an accessible React modal component

How to build an accessible React modal component

A step-by-step guide to creating an accessible and reusable modal component in React.

A step-by-step guide to creating an accessible and reusable modal component in React.

Modal is an overlay on the web-page, but has some standards to follow. WAI-ARIA Authoring Practices are the standards set by W3C. This lets bots and screen-readers know that it is a modal. It is not within the regular flow of the page. We’ll create an awesome react modal using React components.

On top of this, React has its own workflow. Components shouldn’t be on the DOM before rendering. So, you can’t just use display properties to toggle the Modal. Never ever touch the DOM, do everything within the virtual DOM. React is smart to re-render components partially, DOM manipulations are slower. React Modal in the tutorial follows the standards!

If you’d like to see code for any reason, it’s here on codesandbox. Output is also embedded at the end of this tutorial.

Setting Up the Application

Here are the basic requirements of a simple react modal:

  1. Lock the focus within the Modal. And freeze the background.
  2. Must follow WAI-ARIA practice, with roles and semantic HTML tags. More on this later.
  3. Escape key exits an open Modal. So does a click outside of the modal.

Set up the application with create-react-app

npx create-rect-app react-modal

App component

Clean up the *App.js *to return some dummy text. Text is required to show that scrolling is locked whenever the Modal is active. You can add images or other react components. React Modal will overlay on top of these contents. Let’s get into it.

For random text, I’ll create a separate component Text instead of cluttering the App.js. Import Text into App and place it in the return method a couple of times. I’ll put the Modal in between these Textcomponents for the most realistic representation of a modal.

Here’s the initial App.js file.

import React, { Component } from 'react';
import './App.css';
import Text from './Text';
class App extends Component {
  render() {
    return (
      <div className="App">
        <Text />
        <Text />
        <Text />
      </div>
    );
  }
}
export default App;


Text Component

Text component returns paragraphs of text. Multiple paragraphs are wrapped by a React Fragment. As multiple containers cannot be returned, they must be wrapped in React.Fragment if such case arises.

Here’s what Text component looks like.

import React, { Component } from "react";

export class Text extends Component {
  render() {
    return (
      <React.Fragment>
        <p className="lorem-text">
          Lorem ipsum dolor sit amet consectetur, adipisicing elit...
        </p>
        <p className="lorem-text">
          Lorem ipsum dolor sit amet consectetur, adipisicing elit...
        </p>
      </React.Fragment>
    );
  }
}
export default Text;


I’ve used lorem ipsum as a filler text. You can use any text or image as placeholder. Or you can generate lorem ipsum within the VS Code. To get a lorem ipsum text in VS Code, type lorem,* s*uggestion for lorem ipsum will appear. Expand it with TAB key. The suggestion is provided by emmetplugin (comes built-in).

Modal Component

The Modal component, for now, is a button to launch the react modal. Import the Modal in App.

export class Modal extends Component {
  render() {
    return <button className="modal-button">Launch the Modal!</button>;
  }
}


Import and insert it somewhere between other contents in App.

class App extends Component {
  render() {
    return (
      <div className="App">
        <Text />
        <Modal />
        <Text />
        <Text />
      </div>
    );
  }
}


The output is shown below. I added some CSS for a better-looking button, all of which is in index.css, I’ll talk about the CSS where it’s used for functionality over aesthetics.

Modal Trigger Component

The Modal component will handle the actual content in the modal as well as the ModalTrigger.

Create a ModalTrigger component, it’s same as Modal component for now.

Change the Modal to return ModalTrigger.

export class Modal extends Component {
  render() {
    return <ModalTrigger />; ;
  }
}


Making Trigger Component Dynamic

React Components should be reusable. But our content in the ModalTrigger remains the same. I want to be able to use this component with other buttons as well.

Make it reusable by receiving a text prop from the parent component. For a dynamic react modal trigger, pass modalProps from App to Modal, include a triggerText in modalProps*.* You can pass styles as well and apply them to Modal or ModalTrigger.

class App extends Component {
  modalProps = {
    triggerText: 'Launch the Modal!'
  };
  render() {
    return (
      <div className="App">
        <Text />
        <Modal modalProps={this.modalProps} />
        <Text />
        <Text />
      </div>
    );
  }
}
export default App;


Also, pass the triggerText prop from Modal to ModalTrigger.

export class Modal extends Component {
  render() {
    return <ModalTrigger triggerText={this.props.modalProps.triggerText} /> ;
  }
}


Now, the ModalTrigger component should render triggerText

export class ModalTrigger extends Component {
  render() {
    return <button className="modal-button">{this.props.triggerText}</button>;
  }
}


We have the same output, but changing triggerText in modalProps will change the text in button. Try for yourself.

Actual Modal

This far to the tutorial and I haven’t even talked about the actual modal. I’ll name this component ModalContent.

import React, { Component } from 'react';

export class ModalContent extends Component {
  render() {
    return <div>Hello! This is content!</div>;
  }
}

export default ModalContent;


Well, that is a valid component. But let’s make some changes to make it a modal!

The first thing to do is to change container div to aside. Why? Semantically, this React modal or any modal is more of an extra/aside component from the main content.

Let’s look at the whole code…

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
export class ModalContent extends Component {
  render() {
    return ReactDOM.createPortal(
      <aside
        className="modal-cover"
      >
        <div className="modal-area">
          <button
            className="_modal-close"
          >
            <span id="close-modal" className="_hide-visual">
              Close
            </span>
            <svg className="_modal-close-icon" viewBox="0 0 40 40">
              <path d="M 10,10 L 30,30 M 30,10 L 10,30" />
            </svg>
          </button>
          <div className="modal-body">The Actual Content in the Modal</div>
        </div>
      </aside>,
      document.body
    );
  }
}
export default ModalContent;


Modal Cover is a full-page container (100% height and width). The actual Modal content of the react modal is inside this container. Use the cover for closing the modal whenever use clicks outside the Modal content. The actual modal portion is the modal-body. There’s also a close button to exit the modal. The close text will be invisible to the user but can be accessed by the screen-readers to locate the close option.

The react modal cover and modal are both in a fixed layout. This is done to keep the modal in the center of the page. The close button is positioned absolutely at the right-top of the modal.

If you replace ModalTrigger with ModalContent in Modal component, you’ll get the output as below.

Render the Modal at the end of the body

If you look at the modal, it looks fine. But it’s always in the DOM. The Modal is just rendered wherever you call it. A proper Modal is appended to the end of the body.

To take components out of the place it’s rendered, an event can be bubbled up through DOM. DOM should not be accessed directly in React and event bubbling is difficult to debug in a complex application. I’ll take an easier Route of React Portals. They serve this particular case.

React Portal is an API in ReactDOM.

ReactDOM.createPortal() takes two parameters: first JSX and second location on DOM.

ReactDOM.createPortal(

Hello

, document.body) creates a new paragraph at the end of document.body. Now replace this p by the aside in ModalContent.

Here’s the code…

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
export class ModalContent extends Component {
  render() {
    return ReactDOM.createPortal(
      <aside className="modal-cover">
        <div className="modal-area">
          <button className="_modal-close">
            <span className="_hide-visual">Close</span>
            <svg className="_modal-close-icon" viewBox="0 0 40 40">
              <path d="M 10,10 L 30,30 M 30,10 L 10,30" />
            </svg>
          </button>
          <div className="modal-body">The Actual Content in the Modal!</div>
        </div>
      </aside>,
      document.body
    );
  }
}
export default ModalContent;


The output looks the same, but the ModalContent is rendered at the end of the body, outside the App*.*

Modal went outside the App to render the Modal. This would be nearly impossible without React Portal.

Display the Modal with a state

Only render the Modal whenever a user clicks the Launch button. To handle this, use a state.

First, render both ModalTrigger and ModalContent from Modal. But JSX can return only one wrapping tag.

Don’t use div for wrapping. Wrap in React.Fragment, it doesn’t render in the DOM but does wrap the content. After rendering, it looks as if multiple components were returned.

return (
      <React.Fragment>
        <ModalTrigger triggerText={this.props.modalProps.triggerText} />
        <ModalContent />
      </React.Fragment>
    );


Set a state in the Modal component to toggle the ModalContent. I’ll call the state isShown for rendering ModalContent.

I’ll do this through a constructor.

 constructor() {
    super();
    this.state = {
      isShown: false
    };
  }


Modal is hidden initially, so isShown is false.

Set up the conditional display

In Modal, replace by the code below

{this.state.isShown?<ModalContent/>:<React.Fragment/>}

This is a ternary operation, it returns ModalContent if this.state.isShown is true*,* else returns a blank Fragment. A blank fragment means a container that doesn’t render itself and contains nothing. So, it’s blank, literally!

Toggling the state and ModalContent

Now there’s a state in consideration, but there isn’t a way to change the state.

In Modal component, pass the showModal prop to ModalTrigger*.*

<ModalTrigger
showModal={this.showModal}
triggerText={this.props.modalProps.triggerText}
>


Add an onClick handler to the button in ModalTrigger*.*

<button onClick={this.props.showModal} className="modal-button">
        {this.props.triggerText}
      </button>


Now, clicking the button should show the ModalContent*.*

Similarly, add closeModal to close the ModalContent*.* Pass the closeModalas a prop to ModalContent.

<ModalContent closeModal={this.closeModal}/>

In the ModalContent, add onClick handler to close button.

 <button className="_modal-close" onClick={this.props.closeModal}>
   ...Contents inside...
</button>


Now, the modal can open and close!

The Modal renders at the end of the body. And it does not render until the trigger button is clicked!

On closing, modal is removed from the DOM.

Perfect!

But, we aren’t done yet. A click outside modal doesn’t close it, neither does the Escape key.

The accessibility of the Modal

Give aside tag an attribute of aria-modal=”true”, this indicates this is a modal.

Also, give it a tabIndex of -1. You can traverse through an element of the page with Tab, tabIndex gives power to custom order the elements to focus. The value -1 takes it out of focus, which means it can’t be focused with Tab. Clicking the trigger button is the only way to open the modal.

Give it a role of dialog as it a dialog and independent on everything else on the page.

For the close button, give it an aria-label of Close Modal and an id of close-modal. This id can be referred by aria-labelledby in the parent close button. aria-label should not be repeated in a page (they’re unique, just like id, in a HTML document.)

<button
            aria-label="Close Modal"
            aria-labelledby="close-modal"
            className="_modal-close"
            onClick={this.props.closeModal}
          >
            <span id="close-modal" className="_hide-visual">
              Close
            </span>


With aria-label, it follows the web accessibility guidelines.

Passing the content to the Modal

Currently, modal has a fixed content. Being able to pass content to the ModalContent makes it reusable.

In App*,* set modalContent as a JSX value, and pass it to Modal*.*

<ModalmodalProps={this.modalProps}modalContent={this.modalContent}/>

Now, Modal receives the content, pass it to ModalContent as content.

{this.state.isShown ? (
          <ModalContent
            closeModal={this.closeModal}
            content={this.props.modalContent}
          />
        ) : (
          <React.Fragment />
        )}


In ModalContent, replace the generic text in a body by this code.

<div className="modal-body">{this.props.content}</div>

It’ll display whatever you pass as modalContent from App.

class App extends Component {
  modalProps = {
    triggerText: 'Launch the Modal!'
  };
  modalContent = (
    <div>
      <p>Hello From passed modalContent from App!</p>
    </div>
  );
...


The above output illustrates this change!

Event Listeners to Close the Modal

Add some event listeners to improve the user experience with the modal. Pressing escape key or clicking outside the modal area should exit the modal.

With Escape Key

Set onKeyDown = {this.props.keyDown} event listener to the aside component in ModalContent. Pass onKeyDown={this.onKeyDown} to ModalContent from Modal.

<ModalContent
            closeModal={this.closeModal}
            content={this.props.modalContent}
            onKeyDown={this.onKeyDown}
          />


Also, define keyDown in Modal, it just closes the Modal. keyCode for Escape key is 27.

onKeyDown = event => {
    if (event.keyCode === 27) {
      this.closeModal();
    }
  };


Activating the Modal doesn’t give focus to the aside component. It gets focus if you click anywhere in the Modal. And Escape key does call closeModal thereafter. We’ll fix this in a while, continue with the mouse event listener for now!

With a click outside the Modal area

Technically, I’ve used 100% of the width and height for the modal. But the aside component is only the container, the actual modal is

Modal closes on clicking outside this modal-area div are the expected result.

Clicking on modal cover outside the modal-area will close the modal. Use ref in React to refer to the children and detect modal-area.

In the Modal component, pass a reference to ModalContent as *a *modelRefprop. The ref can take a callback function.

Also, create a onClickOutside function and pass to the ModalContent. The reference modalRef is passed as modalRef={n=>(this.modal=n)}.

Add the ref = this.props.modalRef to modal-area, and onClick = {this.props.onClickOutside} to modal-cover.

The onClickOutside method is as follows.

onClickOutside = event => {
    if (this.modal && this.modal.contains(event.target)) return;
    this.closeModal();
  };
I


onClickOutside checks if the click is within the modal-area. It does nothing in that case. The closeModal method is called otherwise.

Focus Lock on Modal Component

Focus the Modal on its appearance. This is also the reason why escape key works only after clicking in the modal once.

The close button in the Modal requires a reference for this, pass buttonReffrom Modal to ModalContent.

buttonRef={n => this.closeButton = n}

Add this reference to the close button as

<button
            ref={this.props.buttonRef}
            aria-label="Close Modal"
            aria-labelledby="close-modal"
            className="_modal-close"
            onClick={this.props.closeModal}
          >


The setState can optionally take a callback method, use this to focus on the modal close button.

showModal = () => {
    this.setState({ isShown: true }, () => {
      this.closeButton.focus()
    });
  };


It immediately focuses on the close button after opening the modal, Escapes key works as expected. Return key will also do the same until user focuses on other parts within the Modal.

Once closed, the focus in not back to the trigger button.

Getting focus back to trigger button

Pass the buttonRef to the TriggerModal component as well.

<ModalTrigger
          showModal={this.showModal}
           buttonRef={n => this.TriggerButton = n}
          triggerText={this.props.modalProps.triggerText}
        />


In the ModalTrigger, set this ref to the button.

 <button
        ref={this.props.buttonRef}
        onClick={this.props.showModal}
        className="modal-button"
      >


As in the openModal, add the focus to closeModal.

closeModal = () => {
    this.setState({ isShown: false });
    this.TriggerButton.focus();
  };


Focus the trigger button automatically after closing the modal. This is why it’s not in the callback!

Focus locking

Modal does not have the focus locked in it. This is for people that traverse the modal with a keyboard, TAB.

Get all focus-able elements from modal. And loop through them to trap the focus.

The better way is to use a *npm * library that serves this particular case. It doesn’t have more features to bloatware our lightweight react modal.

npm i focus-trap-react

and import

import FocusTrap from 'focus-trap-react'

Wrap the aside container in ModalContent with FocusTrap.

It’ll lock the focus to the modal and won’t allow to focus elements out of the modal with TAB key while modal is active.

<FocusTrap>
     <aside>
   .........
    </aside>
</FocusTrap>


Fix the Page Scroll

The modal works as expected. But content in the page can scroll even when the modal is shown.

Set a method scrollLock that toggles the overflow. Call this method from closeModal as well as openModal.

toggleScrollLock = () => {
    document.querySelector('html').classList.toggle('scroll-lock');
  };


What does the scroll-lock class do?

It hides the overflowing content and thus able to scroll.

.scroll-lock {
     overflow:hidden;
}


From showModal

showModal = () => {
    this.setState({ isShown: true }, () => {
      this.closeButton.focus();
    });
    this.toggleScrollLock();
  };


From closeModal

closeModal = () => {
    this.setState({ isShown: false });
    this.TriggerButton.focus();
    this.toggleScrollLock();
  };


There you have a perfectly valid and accessible react modal. Pass any html-like JSX as modelContent from App.js, you’ll get the desired output.

If you want to become a React master, check out Mosh’s React course. It’s the best React course out there!

Originally published on https://programmingwithmosh.com

What is JavaScript – All You Need To Know About JavaScript

What is JavaScript – All You Need To Know About JavaScript

In this article on what is JavaScript, we will learn the basic concepts of JavaScript.

After decades of improvement, JavaScript has become one of the most popular programming languages of all time. It all started in the year 1995 when Brendan Eich created JavaScript in a span of 10 days. Since then, it has seen multiple versions, updates and has grown to the next level.

Here’s a list of topics that I’ll be covering in this blog:

  1. What is JavaScript
  2. What can JavaScript do?
  3. JavaScript Frameworks
  4. The Big Picture: HTML, CSS & JavaScript
  5. Benefits of JavaScript
  6. Fundamentals of JavaScript
    VariablesConstantsData TypesObjectsArraysFunctionsConditional statementsLoopsSwitch case
What is JavaScript?

JavaScript is a high level, interpreted, programming language used to make web pages more interactive.

Have you ever thought that your website is missing something? Maybe it’s not engaging enough or it’s not as creative as you want it to be. JavaScript is that missing piece which can be used to enhance web pages, applications, etc to provide a more user-friendly experience.

What is JavaScript?

JavaScript is the language of the web, it is used to make the web look alive by adding motion to it. To be more precise, it’s a programming language that let’s you implement complex and beautiful things/design on web pages. When you notice a web page doing more than just sit there and gawk at you, you can bet that the web page is using JavaScript.

Feature of JavaScript

Scripting language and not Java: In fact, JavaScript has nothing to do with Java. Then why is it called “Java” Script? When JavaScript was first released it was called Mocha, it was later renamed to LiveScript and then to JavaScript when Netscape (founded JavaScript) and Sun did a license agreement. Object-based scripting language which supports polymorphism, encapsulation and to some extent inheritance as well.**Interpreted language: **It doesn’t have to be compiled like Java and C which require a compiler.JavaScript runs in a browser: You can run it on Google Chrome, Internet Explorer, Safari, etc. JavaScript can execute not only in the browser but also on the server and any device which has a JavaScript Engine.

What is JavaScript – Stackoverflow stats

Currently, we have 100s of programming languages and every day new languages are being created. Among these are few powerful languages that bring about big changes in the market and JavaScript is one of them.

JavaScript has always been on the list of popular programming languages. According to StackOverflow, for the 6th year in a row, JavaScript has remained the most popular and commonly used programming language.

What can JavaScript do?

JavaScript is mainly known for creating beautiful web pages & applications. An example of this is Google Maps. If you want to explore a specific map, all you have to do is click and drag with the mouse. And what sort of language could do that? You guessed it! It’s JavaScript.JavaScript can also be used in smart watches. An example of this is the popular smartwatch maker called Pebble. Pebble has created Pebble.js which is a small JavaScript Framework that allows a developer to create an application for the Pebble line of watches in JavaScript.

What is JavaScript – Applications of JavaScript
Most popular websites like Google, Facebook, Netflix, Amazon, etc make use of JavaScript to build their websites.Among things like mobile applications, digital art, web servers and server applications, JavaScript is also used to make Games. A lot of developers are building small-scale games and apps using JavaScript.## JavaScript Frameworks

One major reason for the popularity of JavaScript is the JavaScript Frameworks. Here’s a brief introduction of the most trending JavaScript frameworks :

  1. AngularJS is Google’s web development framework which provides a set of modern development and design features for rapid application development.

  2. ReactJS is another top JavaScript framework mainly maintained by Facebook and it’s behind the User Interface of Facebook and Instagram, showing off its efficiency in maintaining such high traffic applications.

What is JavaScript – JavaScript Frameworks

  1. MeteorJS is mainly used for providing back-end development. Using JavaScript on the back-end to save time and build expertise is one of the major ideas behind Meteor.

  2. jQuery can be used when you want to extend your website and make it more interactive. Companies like Google, WordPress and IBM rely on jQuery.

The Big Picture: HTML, CSS & JavaScript

Anyone familiar with JavaScript knows that it has something to do with HTML and CSS. But what is the relationship between these three? Let me explain this with an analogy.

What is JavaScript – HTML, CSS and JavaScript

Think of HTML (HyperText Markup Language) as the skeleton of the web. It is used for displaying the web.

On the other hand, CSS is like our clothes. We put on fashionable clothes to look better. Similarly, the web is quite stylish as well. It uses CSS which stands for Cascading Style Sheets for styling purpose.

Then there is JavaScript which puts life into a web page. Just like how kids move around using the skateboard, the web also motions with the help of JavaScript.

Benefits of JavaScript

There has to be a reason why so many developers love working on JavaScript. Well, there are several benefits of using JavaScript for developing web applications, here’s a few benefits:

It’s easy to learn and simple to implement. It is a weak-type programming language unlike the strong-type programming languages like Java and C++, which have strict rules for coding.

It’s all about being fast in today’s world and since JavaScript is mainly a client-side programming language, it is very fast because any code can run immediately instead of having to contact the server and wait for an answer.

Rich set of frameworks like AngularJS, ReactJS are used to build web applications and perform different tasks.

**Builds interactive websites: **We all get attracted to beautifully designed websites and JavaScript is the reason behind such attractive websites and applications.

JavaScript is an interpreted language that does not require a compiler because the web interprets JavaScript. All you need is a browser like Google Chrome or Internet Explorer and you can do all sorts of stuff in the browser.

JavaScript is platform independent and it is supported by all major browsers like Internet Explorer, Google Chrome, Mozilla Firefox, Safari, etc.

JavaScript Fundamentals

In this What is JavaScript blog, we’ll cover the following basic fundamentals of JavaScript
VariablesConstantsData TypesObjectsArraysFunctionsConditional statementsLoopsSwitch case## Variables

Variable is a name given to a memory location which acts as a container for storing data temporarily. They are nothing but reserved memory locations to store values.

What is JavaScript – Variables

To declare a variable in JavaScript use the ‘let’ keyword. For example:

let age;
age=22;

In the above example, I’ve declared a variable ‘age’ by using the ‘let’ keyword and then I’ve stored a value (22) in it. So here a memory location is assigned to the ‘age’ variable and it contains a value i.e. ’22’.

Constants

Constants are fixed values that don’t change during execution time.

To declare a constant in JavaScript use the ‘const’ keyword. For example:

const mybirthday;
mybirthday='3rd August'; 

Data types

You can assign different types of values to a variable such as a number or a string. In JavaScript, there are two categories of data types :

What is JavaScript – Data Types

Objects

An object is a standalone entity with properties and types and it is a lot like an object in real life. For example, consider a girl, whose name is Emily, age is 22 and eye-color is brown. In this example the object is the girl and her name, age and eye-color are her properties.

What is JavaScript – Objects example

Objects are variables too, but they contain many values, so instead of declaring different variables for each property, you can declare an object which stores all these properties.

To declare an object in JavaScript use the ‘let’ keyword and make sure to use curly brackets in such a way that all property-value pairs are defined within the curly brackets. For example:

let girl= {
name: 'Emily',
age: 22,
eyeColour: 'Brown'
};

In the above example, I’ve declared an object called ‘girl’ and it has 3 properties (name, age, eye colour) with values (Emily, 22, Brown).

Arrays

An array is a data structure that contains a list of elements which store multiple values in a single variable.

For example, let’s consider a scenario where you went shopping to buy art supplies. The list of items you bought can be put into an array.

What is JavaScript – Arrays example

To declare an array in JavaScript use the ‘let’ keyword with square brackets and all the array elements must be enclosed within them. For example:

let shopping=[];
shopping=['paintBrush','sprayPaint','waterColours','canvas'];

In the above example I’ve declared an array called ‘shopping’ and I’ve added four elements in it.

Also, array elements are numbered from zero. For example this is how you access the first array element:

shopping[0];		

Functions

A function is a block of organised, reusable code that is used to perform single, related action.

Let’s create a function that calculates the product of two numbers.

To declare a function in JavaScript use the ‘function’ keyword. For example:

function product(a, b) {
return a*b;
}

In the above example, I’ve declared a function called ‘product’ and I’ve passed 2 parameters to this function, ‘a’ and ‘b’ which are variables whose product is returned by this function. Now, in order to call a function and pass a value to these parameters you’ll have to follow the below syntax:

product(8,2);

In the above code snippet I’m calling the product function with a set of values (8 & 2). These are values of the variables ‘a’ and ‘b’ and they’re called as arguments to the function.

Conditional statements – if

Conditional statement is a set of rules performed if a certain condition is met. The ‘if’ statement is used to execute a block of code, only if the condition specified holds true.

What is JavaScript – if flowchart

To declare an if statement in JavaScript use the ‘if’ keyword. The syntax is:

if(condition) {
statement;
}

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[2]) {
console.log('Correct!');
}

In the above example I’ve defined an array of numbers and then I’ve defined an if block. Within this block is a condition and a statement. The condition is ‘(numbers[0]==numbers[2])’ and the statement is ‘console.log(‘Correct!’)’. If the condition is met, only then the statement will be executed.

Conditional statements- Else if

Else statement is used to execute a block of code if the same condition is false.

What is JavaScript – Else-if flowchart

The syntax is:

if(condition) {
statement a;
}
else (condition) {
statement b;
}

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[4] {
console.log("Correct!");
}
else {
console.log("Wrong, please try again");
}

In the above example, I’ve defined an if block as well as an else block. So if the conditions within the if block holds false then the else block gets executed. Try this for yourself and see what you get!

**Loops **

Loops are used to repeat a specific block until some end condition is met. There are three categories of loops in JavaScript :

  1. while loop
  2. do while loop
  3. for loop
While loop

While the condition is true, the code within the loop is executed.

What is JavaScript – while loop flowchart

The syntax is:

while(condition) {
loop code;
}

Now let’s look at an example:

let i=0;
while(i < 5) {
console.log("The number is " +i);
i++;
}

In the above example, I’ve defined a while loop wherein I’ve set a condition. As long as the condition holds true, the while loop is executed. Try this for yourself and see what you get!

Do while loop

This loop will first execute the code, then check the condition and while the condition holds true, execute repeatedly.

What is JavaScript – Do while loop flowchart

Refer the syntax to better understand it:

do {
loop code;
} while(condition);

This loop executes the code block once before checking if the condition is true, then it will repeat the loop as long as the condition holds true.

Now let’s look at an example:

do {
console.log("The number is " +i);
i++;
}
while(i > 5);

The above code is similar to the while loop code except, the code block within the do loop is first executed and only then the condition within the while loop is checked. If the condition holds true then the do loop is executed again.

For loop

The for loop repeatedly executes the loop code while a given condition is TRUE. It tests the condition before executing the loop body.

What is JavaScript – for loop flowchart

The syntax is:

for(begin; condition; step) {
loop code;
}

In the above syntax:

  • begin statement is executed one time before the execution of the loop code
  • condition defines the condition for executing the loop code
  • step statement is executed every time after the code block has been executed

For example:

for (i=0;i<5;i++) {
console.log("The number is " +i);
}

In the above example, I’ve defined a for loop within which I’ve defined the begin, condition and step statements. The begin statement is that ‘i=0’. After executing the begin statement the code within the for loop is executed one time. Next, the condition is checked, if ‘i<5’ then, the code within the loop is executed. After this, the last step statement (i++) is executed. Try this and see what you get!

Switch Case

The switch statement is used to perform different actions based on different conditions.

What is JavaScript – Switch case flowchart

Let’s look at the syntax for switch case:

switch(expression) {
case 1:
code block 1
break;
case 2:
code block 2
break;
default:
code block 3
break;
}

How does it work?

  • Switch expression gets evaluated once
  • Value of the expression is compared with the values of each case
  • If there is a match, the associated block of code is executed

Let’s try this with an example:

let games='football';
switch(games) {
case "throwball":
console.log("I dislike throwball!");
break;
case "football":
console.log("I love football!");
break;
case "cricket":
console.log("I'm a huge cricket fan!");
break;
default:
console.log("I like other games");
break;
}

In the above example the switch expression is ‘games’ and the value of games is ‘football’. The value of ‘games’ is compared with the value of each case. In this example it is compared to ‘throwball’, ‘cricket’ and ‘football’. The value of ‘games’ matches with the case ‘football’, therefore the code within the ‘football’ case is executed. Try this for yourself and see what you get!

With this, we come to the end of this blog. I hope you found this blog informative and I hope you have a basic understanding of JavaScript. In my next blog on JavaScript I’ll be covering in-depth concepts, so stay tuned.

Also, check out our video on JavaScript Fundamentals if you want to get started as soon as possible and don’t forget to leave a comment if you have any doubt and also, let us know whether you’d want us to create more content on JavaScript. We are listening!