How to build a React App from scratch

How to build a React App from scratch

React is an awesome way to build web UIs. This post will show you how to build a React application from scratch using the Stormpath React SDK to add features that allow people to sign up, login, and even view their own user profile.

React is an awesome way to build web UIs. This post will show you how to build a React application from scratch using the Stormpath React SDK to add features that allow people to sign up, login, and even view their own user profile.

Let's get started!

You'll first need to create a Stormpath account and application, which you can do here:

Table of Contents

  • Install the React + Express.js Application Stack
  • Set up the React + Express.js Project
  • How Does React Work?
  • Master Page
  • Index Page
  • Login Page
  • Registration Page
  • Profile Page
  • Home Route
  • Logout
  • User State in Components
  • Import Components
  • Run The Project
  • Wrapping Up
Install the React + Express.js Application Stack

Since we're building our application from scratch, we'll use ES6 and JSX to write as little code as possible, as well as the Stormpath React SDK for user features.

Here's an overview of what we'll be using:

  • React - Allows us to compose simple yet powerful UIs.
  • ReactRouter - Organizes the URL navigation in our React application.
  • ES6 - The next version of JavaScript. Allows us to write real JavaScript classes.
  • JSX - Allows us to place HTML in JavaScript without concatenating strings.
  • Stormpath - Allows us to store and authenticate users without having to create our own backend for it.
  • Stormpath React SDK - Integrates Stormpath into our React application with very little effort.
  • Express - Allows us to serve our HTML and JavaScript files.
  • Express Stormpath - Allows us to serve Stormpath's API through Express.
  • Webpack - Allows us to pack all of our JavaScript files into one bundle.
  • Babel - Allows us to transpile our ES6 and JSX into ES5.
  • Bootstrap - Because we want things to be pretty.
Set up the React + Express.js Project

Start by creating a new project directory and a package.json file for it.

$ mkdir my-react-app
$ cd my-react-app
$ npm init --yes

Now install Express and the Stormpath module for Express:

$ npm install --save express express-stormpath body-parser

We need a server to host our application, so create a new file named server.js and put the code below in it:

var express = require('express');
var stormpath = require('express-stormpath');

var app = express();

app.use(stormpath.init(app, {
  web: {
    produces: ['application/json']

app.on('stormpath.ready', function () {
  app.listen(3000, 'localhost', function (err) {
    if (err) {
      return console.error(err);
    console.log('Listening at http://localhost:3000');

Awesome. Now we can hook that up to a Stormpath Application by creating a new file named stormpath.yml with the following code in it. And yeah, you do have to replace those values in it with your own.

  href: <-- YOUR APP HREF

So far so good. Now try the server by running $ node server.js. If everything is set up correctly then you should see:

Listening at http://localhost:3000

If you saw that message, you've successfully configured your server to talk with Stormpath and expose a REST API for our React application to use.

Configuring Webpack

Before you get too excited, kill the server and install Webpack so that we can package all of our client-side scripts (we'll need this organization soon).

$ npm install --save webpack
$ npm install --save-dev webpack-dev-middleware

Configure Webpack by creating a new file named webpack.config.js and put the code below in it:

var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: [
  devtool: 'eval-source-map',
  output: {
    path: __dirname,
    filename: 'app.js',
    publicPath: '/js/'
  module: {
    loaders: []

What this will do is look in our /src/ directory (that we'll create shortly) and package all of the scripts and their dependencies under that directory as one module. Then use the file /src/app.js and its exports as the export of that module. Then finally when it has generated that module package, it will serve that through Express under the /js/app.js endpoint.

But in order for Express to serve webpack files, we have to open up server.js and add these lines to the top of it:

var webpack = require('webpack');
var config = require('./webpack.config');

Then immediately after the line var app = express(); add:

var compiler = webpack(config);

app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath

As I mentioned before, this will allow Webpack to intercept requests and serve our packaged /js/app.js file.

Configuring Babel

Since we'll be using ES6and JSX, we need to transpile these files into ES5 (for backwards compatibility with non-modern browsers). This is where Babel comes in. Babel can take our ES6/JSX files as input, and convert those to ES5.

To use Babel, start by installing some dependencies:

$ npm install --save babel-core babel-runtime babel-loader babel-plugin-react-transform \
  babel-preset-es2015 babel-preset-react babel-preset-stage-0

Now we'll instruct Babel on how to compile our files, so create a new file named .babelrc and add this code it:

  "presets": ["stage-0", "es2015", "react"]

Finally, in order to get Babel to work with Webpack, we need to edit webpack.config.js and add an entry to the module.loaders array, as shown below:

module: {
  loaders: [{
    test: /\.js$/,
    loaders: ['babel'],
    include: path.join(__dirname, 'src')

Index.html and Bootstrap

Now, before getting our hands dirty with React, we'll prepare the entry page for our app. This page will tell the browser what it must load before we initialize React and our application. So create a new directory named build, then within that, put a file named index.html. Our server will serve all of our static files from this folder.

$ mkdir build
$ cd build
$ touch index.html

Then within index.html, put the following:



Also, under the build directory, create a new directory named css and download Bootstrap to it. Name the file bootstrap.min.css.

$ mkdir css
$ cd css
$ curl -O
$ cd ../.. # return to /my-react-app

Now in order for our browser to be able to access these files we need to configure them so that they are served through Express. So open up server.js and at the top of the file add:

var path = require('path');

Then under the line app.use(stormpath.init(app, ...)); add:

app.get('/css/bootstrap.min.css', function (req, res) {
  res.sendFile(path.join(__dirname, 'build/css/bootstrap.min.css'));

app.get('*', function (req, res) {
  res.sendFile(path.join(__dirname, 'build/index.html'));
How Does React Work?

Now that we have the skeleton for our app done, we can focus on building our React app. But before we write any code, let's take a look at what React is and what it does for us.


In React, everything is built upon components. You can think of a component as something that renders a DOM node. A simple React component looks like this:

class HelloWorld extends React.Component {
  render() {
    return Hello World!;

That was simple. Now, if you wanted to render this component to a page, then all you'd have to do is import React and then call:


And React would render the component to that element.

There are, of course, more things to a React component, such as state. Below is an example of a counter component that starts counting when added to the DOM and stops when removed.

class Counter extends React.Component {
  state = {
    current: 0

  constructor() {
    this.intervalId = null;

  updateCounter() {
    this.setState({ counter: this.state.current + 1 });

  componentWillMount() {
    this.setState({ counter: this.props.from || 0 });
    this.intervalId = setInterval(this.updateCounter.bind(this), 1000);

  componentWillUnmount() {

  render() {
    return { this.state.current };

Notice the methods componentWillMount() and componentWillUnmount(). These are component life-cycle methods that will be executed at various points of a component's life-cycle (in this case, mount and unmount). These methods are usually used for setting up and tearing down a component and is necessary to use because React will error if you try to set the state of a component when it hasn't been mounted yet.

Also notice this.props.from. The member this.props is a collection of all the properties (inputs) passed to a component. Properties of a component can be set as shown below:

JSX Variables

Variables can easily be interpolated into your JSX DOM using { nameOfVariable }, e.g. as shown below:

render() {
  var myVariable = 123;
  return { myVariable };

JSX and Reserved JavaScript Identifiers

Since JSX is JavaScript, there are some caveats that you need to know when working with React. I.e. when setting properties of a React DOM component you cannot use neither for or class since those are considered reserved JavaScript identifiers. To get around this problem, React has come up with htmlFor and className that you should use instead.

To illustrate the issue, this won't work:

<label for="my-input" class="my-label">My Input</label>

But this will:

<label htmlFor="my-input" className="my-label">My Input</label>

Virtual DOM

Instead of working directly against the DOM, in React all components are kept in their own virtual DOM. You can think of the virtual DOM as a DOM implementation in JavaScript (because it actually is). This virtual DOM is then mapped to a real DOM element. So when you render your React component, React will look at the DOM output from the component, compare it to its representation in the virtual DOM, and then generate a patch for the real DOM.

What this means is that you never have to think of manually manipulating DOM elements again. All you have to do is tell React how you want your component to look like, and it will take care of transforming the DOM the ways necessary (with minimal effort).

Installing React Dependencies

Now when we are acquainted with React, we'll kick things off by installing some React dependencies:

$ npm install --save react react-dom react-router react-stormpath react-document-title history

Before we start coding, we need a place to put our React files, so create a new directory named src, and then use that as your working directory.

$ mkdir src
$ cd src

Now, let's start with the entry point of our app. This will be the place where we will set up our React application and its routing. So create a new file named app.js and enter this code:

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, IndexRoute, Route, browserHistory } from 'react-router';


So now we have a foundation for our application. Let's go ahead and import the Stormpath SDK and some things we'll need in it. At the top of your app.js file, add the import statement:

import ReactStormpath, { Router, HomeRoute, LoginRoute, AuthenticatedRoute } from 'react-stormpath';

As you can see in app.js there's now two conflicting Router imports. Since [ReactStormpath.Router]( extends from [ReactRouter.Router]( we won't be needing that anymore. So go ahead and remove the Router import from react-router. Important: Leave the other ReactRouter imports, we'll be needing those later.

Now, we'll initialize the Stormpath SDK. Add the following line right above [ReactDOM.render()](


That was easy! We're now ready to start building our pages.

Master Page

Before we create our pages, we have to set up our router. The router is what determines how we'll be able to navigate around in our application. We'll start by creating a shared root route. This will act as our "master page". I.e. all routes under this route will all share the same master component (header). So place the codebelow inside the `` tag in your app.js so that it looks like:


As you can see, we have referenced MasterPage. Something that doesn't exist yet. So let's go ahead and create that in a new directory that we'll name pages, in our src folder.

$ mkdir pages
$ cd pages

Now create a new file named MasterPage.js and add this code to it:

import React from 'react';
import { Link } from 'react-router';
import { LoginLink } from 'react-stormpath';
import DocumentTitle from 'react-document-title';

import Header from './Header';

export default class is extends React.Component {
  render() {
    return (
          { this.props.children }

As you can see, we don't have a Header component yet, so let's go and create a new file named Header.js in the same directory with the following content:

import React from 'react';
import { Link } from 'react-router';
import { LoginLink, LogoutLink, Authenticated, NotAuthenticated } from 'react-stormpath';

export default class Header extends React.Component {
  render() {
    return (
            * Home

Index Page

In our MasterPage notice the property this.props.children. This will contain the components of the child routes that our router match. So if we had a route that looked like:


And we tried to access /hello. The this.props.children array would be populated with a HelloPage component and for that reason that component would be rendered in our master page.

Now imagine the scenario where you try to access /. Without any this.props.children, this would only render your master page but with empty content. This is where [IndexRoute]( comes into play. With an [IndexRoute]( you can specify the component that should be rendered when you hit the path of the master page route (in our case /).

But before we add our [IndexRoute]( to our router, let's create a new file in our pages directory named IndexPage.js and add the following to it:

import { Link } from 'react-router';
import React, { PropTypes } from 'react';
import { LoginLink } from 'react-stormpath';

export default class IndexPage extends React.Component {
  render() {
    return (
        ## Welcome!

* * *

            **To my React application!**
Ready to begin? Try these Stormpath features that are included in this example:

          1. Registration
1. Custom Profile Data


Now let's add our [IndexRoute]( Open up app.js and inside the tag `` add your [IndexRoute]( so that it looks like the following:


Login Page

We now have an application that shows a header with a default page. But we don't have any place to login yet. So let's create a new file named LoginPage.js and add some content to it:

import React from 'react';
import DocumentTitle from 'react-document-title';
import { LoginForm } from 'react-stormpath';

export default class LoginPage extends React.Component {
  render() {
    return (
              ### Login

* * *


Notice the [LoginForm]( component. This is all we have to add in order for us to have a fully working form in which people can sign up from.

But before we can use it, we need to open up app.js and add a route for the page in our router. So inside the tag `` add the following:

<LoginRoute path='/login' component={LoginPage} />

In order to be able to access the login page, we need to add this to our menu. So go ahead and open up Header.js and inside the element `` add the following:* As you can see we're using the [NotAuthenticated]( component. With this we'll only show a [LoginLink]( when the user isn't logged in yet.## Registration PageNow, let's add a page where people can sign up. We'll call it RegistrationPage. So create a new file named RegistrationPage.js and put the following content in it:``` import React from 'react'; import DocumentTitle from 'react-document-title'; import { RegistrationForm } from 'react-stormpath';export default class RegistrationPage extends React.Component {render() {return (### Registration

);} } Notice that we used the `[RegistrationForm](` component. As you might have guessed, this will render a Stormpath registration form. And once you've signed up it will point users to the login page where they'll be able to login.In order to access this page. We need to add a route. So go ahead and open up `app.js` and inside the tag `` add: ```We now have a route, but people won't be able to find the page unless we link to it, so open up Header.js and add the following right before the closing tag () of :

    Create Account

Notice the use of the [NotAuthenticated]( component. With this we'll only show the /register link when the user isn't logged in.

Profile Page

Once a user is logged in, we want to be able to show them some personalized content (their user data). So create a new file named ProfilePage.js and put the following code in it:

import React from 'react';
import DocumentTitle from 'react-document-title';
import { UserProfileForm } from 'react-stormpath';

export default class ProfilePage extends React.Component {
  render() {
    return (
              ### My Profile

* * *


Notice that we use the [UserProfileForm]( This is a simple helper form that allows you to edit the most basic user fields.

Though, in order to actually modify the user profile, we need to change a few things in our server. So open up server.js, add var bodyParser = require('body-parser'); to the top of the file and then add the following route underneath app.use(stormpath.init(app, ...));:'/me', bodyParser.json(), stormpath.loginRequired, function (req, res) {
  function writeError(message) {
    res.json({ message: message, status: 400 });

  function saveAccount () {
    req.user.givenName = req.body.givenName;
    req.user.surname = req.body.surname; =; (err) {
      if (err) {
        return writeError(err.userMessage || err.message);

  if (req.body.password) {
    var application ='stormpathApplication');

      username: req.user.username,
      password: req.body.existingPassword
    }, function (err) {
      if (err) {
        return writeError('The existing password that you entered was incorrect.');

      req.user.password = req.body.password;

  } else {

This will allow the form to change both the given name, surname, email and password of user. If you have additional fields that you wish to edit, then simply customize the [UserProfileForm]( form and add the fields that you wish to edit in the route above.

Now, in order for us to access this page from the menu, open up Header.js and right below Home add:


With this, using the [Authenticated]("( component, when we have a user session we'll render a link to the /profile page and allow our users to view their user profile.

In order for us to be able to access the page, we must as with the other pages add it to the router. Open up app.js and inside the tag `` add:

Notice that we're using [AuthenticatedRoute]( This is a route that can only be accessed if there is an authenticated user session. If there's no session, then the user will automatically be redirected to the path of the [LoginLink](

Home Route

Now when we've setup most of our routing. Let's look at a special route called the [HomeRoute]( This route itself doesn't do anything. But acts as a "marker", to indicate where to redirect to when logging in and logging out.

So in order to specify where we want to end up when we log out, open up app.js and change the:




Now when logging out, the Stormpath SDK will know that it should redirect to the '/' path. Now, to specify where to redirect when logging out, change the [AuthenticatedRoute]( that we created in the previous step:

<AuthenticatedRoute path='/profile' component={ProfilePage} />

So that it looks like:


Notice how the [AuthenticatedRoute]( wraps the [HomeRoute]( This is used to indicate the authenticated route that we want to redirect to after login.


Finally, once our users have signed up and logged in. We want to give them the option to logout. Fortunately, adding this is really simple.

So open up Header.js and inside `` add this code to the end:


Notice the [LogoutLink]( component. Once this is clicked, the user session will be automatically destroyed and the user will be redirected to the unauthenticated [HomeRoute](

User State in Components

Access user state in your components by requesting the authenticated and user context types:

class ContextExample extends React.Component {
  static contextTypes = {
    authenticated: React.PropTypes.bool,
    user: React.PropTypes.object

  render() {
    if (!this.context.authenticated) {
      return (
          You need to .

    return (
        Welcome {this.context.user.username}!
Import Components

To be able to reference our pages we need to import them. And in order to make importing easy, we'll put them all together in an index.js file so we only have to import it once. So let's create a new file named index.js in our pages directory and export all of our pages from it, as shown below:

export MasterPage from './MasterPage'
export IndexPage from './IndexPage'
export LoginPage from './LoginPage'
export RegistrationPage from './RegistrationPage'
export ProfilePage from './ProfilePage'

With this, we'll only have to do one import in order to have access to all of our pages.

So let's do that. Open up app.js file and at the top of the file, add the following import statement:

import { MasterPage, IndexPage, LoginPage, RegistrationPage, ProfilePage } from './pages';
Run The Project

Now we have an application where our users can sign up, login, and show their user data. So let's try it out!

As before, start our server by running the following:

$ node server.js

And if everything is running successfully you should be able to see this message:

Listening at http://localhost:3000

So, open up http://localhost:3000 in your browser and try it out!

Wrapping Up

As you have seen in this tutorial, React is a really powerful tool and when used together with ES6, JSX and Stormpath, building apps suddenly becomes fun again.

If you have questions regarding the Stormpath React SDK, be sure to check out its API documentation.

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;

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 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


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).


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=[];

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:



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:


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) {

Now let’s look at an example:

let numbers=[1,2,1,2,3,2,3,1];
if(numbers[0]==numbers[2]) {

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] {
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);

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);
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
case 2:
code block 2
code block 3

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!");
case "football":
console.log("I love football!");
case "cricket":
console.log("I'm a huge cricket fan!");
console.log("I like other games");

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!