How to write a simple React search plugin, publish it to npm, and deploy it to Github pages

In this article, we’re going to write a simple search plugin in&nbsp;<a href="https://reactjs.org/" target="_blank">React</a>. Through this article, I hope to help fellow developers understand how to write plugins using React, publish them to&nbsp;<a href="https://www.npmjs.com/" target="_blank">npm</a>&nbsp;and deploy a demo to Github pages.

In this article, we’re going to write a simple search plugin in React. Through this article, I hope to help fellow developers understand how to write plugins using React, publish them to npm and deploy a demo to Github pages.

The source code of the plugin is available on Github.

Getting started

We’re going to bootstrap our plugin using create-react-library which is a CLI for easily creating reusable react libraries. This CLI has a bunch of featuresand will help us in generating a boilerplate for our plugin.


To use create-react-library, we’ll need to install it globally:

npm install -g create-react-library

The above command will install create-react-library globally and we can generate a new module from any directory. To generate a new directory, type the following command in the directory where you want to bootstrap the plugin:

create-react-library

The above command will ask some basic prompts about your module and once you answer them, a boilerplate for the plugin will be generated.


Now, you need to run the plugin (for watching any changes that you make to it) and the example. In one tab, you can run:

cd react-search-box && yarn start

And, in another tab, you need to run the example app:

cd react-search-box/example && yarn start

The last command will run a create-react-app project which imports your plugin. If you make any changes to your plugin, it will get reflected in the example app. You can view the current status of your plugin by visiting http://localhost:3000.


Designing the input box

Let’s add the first basic functionality: an input box which would let the users type in it.


import React, { Component } from 'react'
import PropTypes from 'prop-types'
import styles from './styles.css'
export default class ReactSearchBox extends Component {
  static propTypes = {
    /**
     * value: The default value for the input box.
     * placeholder: The placeholder text for the input box.
     */
    value: PropTypes.string,
    placeholder: PropTypes.string
  }
  state = {
    value: ''
  }
  componentDidMount() {
    const { value } = this.props
    this.setState({
      value: value
    })
  }
  handleInputChange = e => {
    const { value } = e.target
  this.setState({
      value: value
    })
  }
  inputNode = () => {
    /**
     * This function is responsible for rendering the input box.
     * The input box acts as a source of entry for the data from the user.
     */
    const { placeholder } = this.props
    const { value } = this.state
    return (
      <input
        className={styles.input}
        type='text'
        placeholder={placeholder}
        value={value}
        onChange={this.handleInputChange}
      />
    )
  }
  render() {
    return <div className={styles.container}>{this.inputNode()}</div>
  }
}

In the above code, we’re creating an input element which has a classNameattribute, a type attribute, a placeholder attribute, a value attribute and an onChange handler. Most of these are very basic props. The only interesting prop is the onChange prop which is triggered whenever the user types in the input box.

Whenever there is a change in the input box, we’re calling the handleInputChange function. handleInputChange function gets the event as an argument to it. We’re using an ES6 arrow function here. So, we don’t need to explicitly bind this with the handleInputChange function. You can read When should I use arrow functions with React by James K Nelson.

Since we have a value state which we’re passing to the input box as an attribute, we are updating that value state whenever there is a change in the input box through the handleInputChange function.

handleInputChange = e => {
  const { value } = e.target
  this.setState({
    value
  })
}

If you visit http://localhost:3000, you’ll see an input box on the screen. You can type in the input box and the value will get updated.


If you check in React Developer Tools, you’ll see that the value of the input box is getting updated.

That’s all the functionality we need for the input box. Next, we’ll design a dropdown which will appear once the string that the user types in the input box, matches with any record that’ll be supplied to our plugin through the data prop.

Designing the dropdown

In this section, we’re going to implement a dropdown, which will appear with an array of records which matches with the string that the user types in the input box. The initial array of records will be supplied using the data prop which we will implement first.


import React, { Component } from "react";
import ReactSearchBox from "react-search-box";
export default class App extends Component {
  data = [
    {
      key: "john",
      value: "John Doe"
    },
    {
      key: "jane",
      value: "Jane Doe"
    },
    {
      key: "mary",
      value: "Mary Phillips"
    },
    {
      key: "robert",
      value: "Robert"
    },
    {
      key: "karius",
      value: "Karius"
    }
  ];
  render() {
    return (
      <div className="container">
        <ReactSearchBox
          placeholder="Placeholder"
          value="Doe"
          data={this.data}
        />
      </div>
    );
  }
}

Our plugin should be imported and defined like the above block of code. You import ReactSearchBox and then you pass an array of objects (the data array in this case) to ReactSearchBox.

For now, we will render the dropdown if a value prop is passed to our plugin. Later, we will refactor our component to show the dropdown if any record from the data prop matches with the supplied value prop.

Our plugin would now look something like the following:

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import styles from './styles.css'
export default class ReactSearchBox extends Component {
  static propTypes = {
    /**
     * value: The default value for the input box.
     * placeholder: The placeholder text for the input box.
     * data: An array of objects which acts as the source of data for the dropdown.
     */
    value: PropTypes.string,
    placeholder: PropTypes.string,
    data: PropTypes.array.isRequired
  }
  static defaultProps = {
    /**
     * Set data prop as an empty array in case it's not passed.
     */
    data: []
  }
  state = {
    value: ''
  }
  componentDidMount() {
    /**
     * This function is the same as before
     */  
  }
  handleInputChange = e => {
    /**
     * This function is the same as before
     */  
  }
  inputNode = () => {
    /**
     * This function is the same as before
     */
  }
  dropdownNode = () => {
    /**
     * This function is responsible for rendering the dropdown.
     */
    const { data } = this.props
    return (
      <div className={`react-search-box-dropdown ${styles.dropdown}`}>
        <ul className={styles.dropdownList}>
          {data.map(record => {
            return (
              <li
                key={record.key}
                className={`react-search-box-dropdown-list-item ${
                  styles.dropdownListItem
                }`}
              >
                {record.value}
              </li>
            )
          })}
        </ul>
      </div>
    )
  }
render() {
    return (
      <div className={styles.container}>
        {this.inputNode()}
        {this.dropdownNode()}
      </div>
    )
  }
}

The code for the dropdown is present in the dropdownNode function. Based on the data prop which is supplied to our plugin, we are creating a list of liitems and rendering inside the dropdown.

If we visit http://localhost:3000/, we will see a dropdown along with an input box.

That’s all the functionality we need for the dropdown. Next, we’ll refactor our plugin to render dropdown only when any record matches with the query that the user will type in the input box.

Refactoring our plugin to render dropdown only when any record matches with the query

This is the last step of our development process.


First, we need to add a package named fuse.js which is a lightweight fuzzy-search library. It’ll help us to check if the query that the user types in the input box matches with any records from the data prop which is supplied to our plugin.

Let’s add it to our list of dependencies using the command below:

yarn add fuse.js

Now, we would refactor our plugin to check if the query matches with any of the records.

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Fuse from 'fuse.js'
import styles from './styles.css'
export default class ReactSearchBox extends Component {
  static propTypes = {
    /**
     * This is same as before
     */
  }
  static defaultProps = {
    /**
     * This is same as before
     */
  }
  state = {
    /**
     * 'matchedRecords' stores the items when the input box's value
     * matches with any item from the 'data' prop.
     */
    value: '',
    matchedRecords: []
  }
  constructor(props) {
    super(props)
    const { data } = props
    /**
     * These options are from Fuse plugin. Check out http://fusejs.io/
     * for more details.
     */
    const options = {
      /**
       * At what point does the match algorithm give up. A threshold of 0.0
       * requires a perfect match (of both letters and location), a threshold
       * of 1.0 would match anything.
       */
      threshold: 0.05,
      /**
       * Determines approximately where in the text is the pattern expected to be found.
       */
      location: 0,
      /**
       * Determines how close the match must be to the fuzzy location
       * (specified by location). An exact letter match which is distance
       * characters away from the fuzzy location would score as a complete
       * mismatch. A distance of 0 requires the match be at the exact
       * location specified, a distance of 1000 would require a perfect
       * match to be within 800 characters of the location to be found
       * using a threshold of 0.8.
       */
      distance: 100,
      /**
       * When set to include matches, only the matches whose length exceeds this
       * value will be returned. (For instance, if you want to ignore single
       * character index returns, set to 2).
       */
      minMatchCharLength: 1,
      /**
       * List of properties that will be searched. This supports nested properties,
       * weighted search, searching in arrays of strings and objects.
       */
      keys: ['value']
    }
    this.fuse = new Fuse(data, options)
  }
  componentDidMount() {
    const { value } = this.props
    /**
     * If any 'value' is passed as prop, find if it matches with any item
     * from teh 'data' prop. If there is any record, which matches with
     * the query, update 'matchedRecord' state with the matched object(s).
     *
     * Also, update the 'value' state with the 'value' prop.
     */
    const matchedRecords = this.fuse.search(value)
    this.setState({
      value: value.trim(),
      matchedRecords,
      /**
       * Control the showing and hiding of the dropdown when there is any value
       * in the input box. But, close the dropdown once any dropdown item is
       * clicked.
       */
      showDropdown: !!value.trim()
    })
  }
  handleInputChange = e => {
    /**
     * This function is responsible for checking if any items from the input
     * box's value matches with any item form the 'data' prop. If any item matches,
     * then that matched object is pushed into the 'matchedRecords' state. That
     * state is responsible for populating the dropdown.
     */
    const { value } = e.target
/**
     * Check all the values from 'data' array whose 'value' matches with
     * 'value' using Fuse plugin.
     */
    const matchedRecords = this.fuse.search(value)
/**
     * Update 'value' state with the value from the input box
     * Update 'matchedRecords' state with the matched records from the data array.
     */
    this.setState({
      value: value.trim(),
      matchedRecords,
      /**
       * Show the dropdown onChange of the input
       */
      showDropdown: true
    })
  }
  inputNode = () => {
    /**
     * This function is the same as before
     */
  }
  handleDropdownItemClick = record => {
    /**
     * This function is responsible for updating the value inside the
     * input box when any dropdown item is clicked.
     *
     * The 'value' state is updated with the clicked record's value.
     */
  const { value } = record
  this.setState({
      value,
      /**
       * Hide the dropdown once any dropdown item is clicked
       */
      showDropdown: false
    })
  }
  dropdownNode = () => {
    /**
     * This function is responsible for rendering the dropdown.
     * When any value from the input box matches with any value from the
     * 'data' prop, that matched object from the 'data' array shows up
     * in the dropdown's li. The matched values are stored in the
     * 'matchedRecords' state.
     */
    const { matchedRecords, showDropdown } = this.state
/**
     * If there is no value present in the input box, then the dropdown
     * shouldn't appear.
     */
    if (!showDropdown) return false
  return (
      <div className={`react-search-box-dropdown ${styles.dropdown}`}>
        <ul className={styles.dropdownList}>
          {matchedRecords.map(record => {
            return (
              <li
                key={record.key}
                className={`react-search-box-dropdown-list-item ${
                  styles.dropdownListItem
                }`}
                onClick={() => this.handleDropdownItemClick(record)}
              >
                {record.value}
              </li>
            )
          })}
        </ul>
      </div>
    )
  }
  render() {
    /**
     * This function is the same as before
     */
  }
}

I’ve added comments inside every function which state what that particular function does. The basic functionality that we get out of the above code is the following:

  1. The user types in the input box (We would call the text that user types in as query).
  2. onChange of the input box, the plugin would check if the current value of the input box matches with any record supplied to our plugin through the data prop.
  3. If any record matches with the query, we will render a dropdown with a list of the matched records.
  4. If no records match with the query, we won’t render the dropdown.

If you visit http://localhost:3000, you can see that dropdown appears with a list of matched records. The dropdown will hide if the input box is empty.


That’s all the code that we need. Next, we will push our changes to a Githubrepository.

Pushing our code to Github

In this section, we would create a Github repository and push our code to Github.


If you’re new to Github, you can follow this article to know how to create a repository. Once you’re done creating a new repository, you need to add remote to your plugin.

git remote add origin https://github.com/ghoshnirmalya/react-search-box

In my case, I’m adding https://github.com/ghoshnirmalya/react-search-boxbecause I want my code changes to be available on that repository. For your case, it’ll be a different url.

Once that’s done, you can push your changes to the Github repository:

git push origin master

You code is now available on your Github repository.

Publishing our plugin to npm

In this section, we will publish our code to npm. npm is the package manager for JavaScript.


create-react-library already has a feature through which we can publish our plugin to the npm registry. You just need to run the following command:

yarn publish


Deploying an example application to Github pages

In this section, we will deploy a sample application which will use our plugin to Github pages.


create-react-library already has a feature through which we can deploy the example folder to Github pages. You just need to run the following command:

yarn deploy

Now, you can view your application available at https://your-username.github.io/your-repository-name/. For me, it’s https://ghoshnirmalya.github.io/react-search-box since the url to my repository is https://github.com/ghoshnirmalya/react-search-box.


Closing notes

One last thing that you should remember is that I’ve made a bunch of changes to React Search Box on top of the changes that I mentioned here. I just wanted to create a simple autocomplete React plugin and thought that my learnings would help others who want to contribute to React but are not sure how to start.


I hope that this article will help others. I’m curious to know what great plugins you guys build with the help of this articles. Please let me know in the comments below.


By : Nirmalya Ghosh


npm and the Future of JavaScript

npm started out as a back-end tool for node.js developers writing server-side applications, but has become the tool of choice for front-end developers writing rich web applications.

More than 80% of npm users are writing front-end code! This was a big change, so npm 5 was a big change to meet the needs of this new type of user. Now with npm 6, we’re refining that focus. This talk covers best practices for npm 6, including ways to dramatically improve your build times, how to use our new security features, and talk about what’s coming up for npm. In the second half, I cover what npm knows about JavaScript developers based on our survey of over 16,000 developers, what that means for the future of JavaScript, and the tooling and language choices the data suggests you should make as a developer today.

Thanks for reading ❤

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

Learn More

The Complete JavaScript Course 2019: Build Real Projects!

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

JavaScript Bootcamp - Build Real World Applications

The Web Developer Bootcamp

JavaScript: Understanding the Weird Parts

Building a Simple URL Shortener With Just HTML and Javascript

The JavaScript Developer’s Guide To Node.JS

From Javascript to Typescript to Elm

Google’s Go Essentials For Node.js / JavaScript Developers

3 things you didn’t know about the forEach loop in JavaScript

A new thing for Javascript and Node.js. What’s wrong with NPM?

A new thing for Javascript and Node.js. What’s wrong with NPM?

Why does the world need another package manager / what’s wrong with npm? JavaScript is an exemplar of a larger problem: code reuse via artifacts with dependency metadata delivered by a registry that controls namespaces and versioning

Why does the world need another package manager / what’s wrong with npm? JavaScript is an exemplar of a larger problem: code reuse via artifacts with dependency metadata delivered by a registry that controls namespaces and versioning. Registries are poised to provide functionality for communities: security assurances, static analysis, invariants around version availability, user support. JS is special because it has the largest registry and the most code reuse in the wild, but other communities need this too.

Docker. Rust. Ruby. Python. This is a problem that communities keep solving and re-solving. There hasn’t been a satisfactory answer to the problem of funding. Money is ultimately what supports these gossamer webs of packages. Without money, that web disintegrates. At JavaScript’s scale, the money it takes to support the web is enormous. Further, there’s value in expanding this web, and that means more language communities will contribute to this web over time, making it yet more expensive to support. We could give this web to a company with deep pockets, but we’re placing a lot of trust in an entity that’s not entirely incentivized to keep our best interests at heart.

So, the question is: how do we make this web of packages less expensive as it gets bigger? How do we preserve community control of that web? How do we earn the trust of other language communities, so we can solve the problem of artifact dependencies once and reap the benefits across all languages? We think Entropic is the answer: federated registries and distributed trust recast this ephemeral web of packages in diamond, adamant and self-supporting.

Speaker: Chris Dickinson

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!