Top 50 React Interview Questions You Must Prepare In 2019

Top 50 React Interview Questions You Must Prepare In 2019

Here are the Top React Interview Questions which an aspiring front end developer must prepare in 2019 for React interviews.

Here are the Top React Interview Questions which an aspiring front end developer must prepare in 2019 for React interviews.

If you are an aspiring front end developer and preparing for interviews, then this blog is for you. This blog on Top 50 React Interview Questions is the perfect guide for you to learn all the concepts required to clear a React interview. But before starting with the React Interview Questions, let’s take a quick look at React’s demand and status in the market.

Hottest job roles, precise learning paths, industry outlook & more in the guide. Download now.

Slowly and steadily, the JavaScript tools are firming their roots in the marketplace and the demand for React certification is increasing exponentially. Selecting the right technology for developing an application or website is becoming more challenging. Among all, React is considered as the fastest growing Javascript framework.

As of today, there are about 1,000 contributors on Github. Unique features like Virtual DOM and reusable components grab the attention of front end developers. Despite being just a library for ‘View’ in MVC (Model-View-Controller), it’s giving strong competition to full-blown frameworks like Angular, Meteor, Vue, etc. Check out the belo2w graph which shows the trend of popular JS frameworks:

React Interview Questions

So, here are the Top 50 React Interview Questions and Answers which are most likely to be asked by the interviewer. For your ease of access, I have categorized the React interview questions namely:
General React Interview QuestionsReact Component Interview QuestionsReact Redux Interview QuestionsReact Router Interview Questions
General React – React Interview Questions

1. Differentiate between Real DOM and Virtual DOM.

Real DOM vs Virtual DOM

Real DOMVirtual DOM1. It updates slow.1. It updates faster.2. Can directly update HTML.2. Can’t directly update HTML.3. Creates a new DOM if element updates.3. Updates the JSX if element updates.4. DOM manipulation is very expensive.4. DOM manipulation is very easy.5. Too much of memory wastage.5. No memory wastage.

2. What is React?

React is a front-end JavaScript library developed by Facebook in 2011.It follows the component based approach which helps in building reusable UI components.It is used for developing complex and interactive web and mobile UI.Even though it was open-sourced only in 2015, it has one of the largest communities supporting it.### 3. What are the features of React?

Major features of React are listed below:
It uses the virtual DOM instead of the real DOM.It uses server-side rendering.It follows uni-directional data flow or data binding.### 4. List some of the major advantages of React.

Some of the major advantages of React are:
It increases the application’s performanceIt can be conveniently used on the client as well as server sideBecause of JSX, code’s readability increasesReact is easy to integrate with other frameworks like Meteor, Angular, etcUsing React, writing UI test cases become extremely easy### 5. What are the limitations of React?

Limitations of React are listed below:
React is just a library, not a full-blown frameworkIts library is very large and takes time to understandIt can be little difficult for the novice programmers to understandCoding gets complex as it uses inline templating and JSX### 6. What is JSX?

JSX is a shorthand for JavaScript XML. This is a type of file used by React which utilizes the expressiveness of JavaScript along with HTML like template syntax. This makes the HTML file really easy to understand. This file makes applications robust and boosts its performance. Below is an example of JSX:

render(){
    return(       
          
 
 
<div>
             
 
 
<h1> Hello World from Edureka!!</h1>
 
 
 
         </div>
 
 
 
    );
}

7. What do you understand by Virtual DOM? Explain its working.

A virtual DOM is a lightweight JavaScript object which originally is just the copy of the real DOM. It is a node tree that lists the elements, their attributes and content as Objects and their properties. React’s render function creates a node tree out of the React components. It then updates this tree in response to the mutations in the data model which is caused by various actions done by the user or by the system.

This Virtual DOM works in three simple steps.
Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.Then the difference between the previous DOM representation and the new one is calculated.Once the calculations are done, the real DOM will be updated with only the things that have actually changed. ### 8. Why can’t browsers read JSX?

Browsers can only read JavaScript objects but JSX in not a regular JavaScript object. Thus to enable a browser to read JSX, first, we need to transform JSX file into a JavaScript object using JSX transformers like Babel and then pass it to the browser.

9. How different is React’s ES6 syntax when compared to ES5?

Syntax has changed from ES5 to ES6 in following aspects:
require vs import

// ES5
var React = require('react');
 
// ES6
import React from 'react';

 2. export vs exports
// ES5
module.exports = Component;
 
// ES6
export default Component;

3. component and function
// ES5
var MyComponent = React.createClass({
    render: function() {
        return
 
 
<h3>Hello Edureka!</h3>
 
 
 
;
    }
});
 
// ES6
class MyComponent extends React.Component {
    render() {
        return
 
 
<h3>Hello Edureka!</h3>
 
 
 
;
    }
}

  1. props
// ES5
var App = React.createClass({
    propTypes: { name: React.PropTypes.string },
    render: function() {
        return
 
 
<h3>Hello, {this.props.name}!</h3>
 
 
 
;
    }
});
 
// ES6
class App extends React.Component {
    render() {
        return
 
 
<h3>Hello, {this.props.name}!</h3>
 
 
 
;
    }
}

5. state
// ES5
var App = React.createClass({
    getInitialState: function() {
        return { name: 'world' };
    },
    render: function() {
        return
 
 
<h3>Hello, {this.state.name}!</h3>
 
 
 
;
    }
});
 
// ES6
class App extends React.Component {
    constructor() {
        super();
        this.state = { name: 'world' };
    }
    render() {
        return
 
 
<h3>Hello, {this.state.name}!</h3>
 
 
 
;
    }
}

10. How is React different from Angular?

React vs Angular

TOPICREACTANGULAR1. ARCHITECTUREOnly the View of MVCComplete MVC2. RENDERINGServer-side renderingClient-side rendering3. DOMUses virtual DOMUses real DOM4. DATA BINDINGOne-way data bindingTwo-way data binding5. DEBUGGINGCompile time debuggingRuntime debugging6. AUTHORFacebookGoogle

React Components – React Interview Questions

11. What do you understand from “In React, everything is a component.”

Components are the building blocks of a React application’s UI. These components split up the entire UI into small independent and reusable pieces. Then it renders each of these components independent of each other without affecting the rest of the UI.

12. Explain the purpose of render() in React.

Each React component must have a **render() **mandatorily. It returns a single React element which is the representation of the native DOM component. If more than one HTML element needs to be rendered, then they must be grouped together inside one enclosing tag such as , ,

etc. This function must be kept pure i.e., it must return the same result each time it is invoked.

13. How can you embed two or more components into one?

We can embed components into one in the following way:

class MyComponent extends React.Component{
    render(){
        return(         
             
 
 
<div>
               
                 
 
 
<h1>Hello</h1>
 
 
 
                <Header/>
            </div>
 
 
 
        );
    }
}
class Header extends React.Component{
    render(){
        return
 
 
<h1>Header Component</h1>
 
 
 
    
   };
}
ReactDOM.render(
    <MyComponent/>, document.getElementById('content')
);

14. What is Props?

Props is the shorthand for Properties in React. They are read-only components which must be kept pure i.e. immutable. They are always passed down from the parent to the child components throughout the application. A child component can never send a prop back to the parent component. This help in maintaining the unidirectional data flow and are generally used to render the dynamically generated data.

15. What is a state in React and how is it used?

States are the heart of React components. States are the source of data and must be kept as simple as possible. Basically, states are the objects which determine components rendering and behavior. They are mutable unlike the props and create dynamic and interactive components. They are accessed via this.state().

16. Differentiate between states and props.

States vs Props

ConditionsStateProps1. Receive initial value from parent componentYesYes2. Parent component can change valueNoYes3. Set default values inside componentYesYes4. Changes inside componentYesNo5. Set initial value for child componentsYesYes6. Changes inside child componentsNoYes

17. How can you update the state of a component?

State of a component can be updated using this.setState().

class MyComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            name: 'Maxx',
            id: '101'
        }
    }
    render()
        {
            setTimeout(()=>{this.setState({name:'Jaeha', id:'222'})},2000)
            return (             
                    
 
 
<div>
                   
                      
 
 
<h1>Hello {this.state.name}</h1>
 
 
 
                 
                      
 
 
<h2>Your Id is {this.state.id}</h2>
 
 
 
                   </div>
 
 
 
            );
        }
    }
ReactDOM.render(
    <MyComponent/>, document.getElementById('content')
);

18. What is arrow function in React? How is it used?

Arrow functions are more of brief syntax for writing the function expression. They are also called ‘fat arrow‘ (=>) the functions. These functions allow to bind the context of the components properly since in ES6 auto binding is not available by default. Arrow functions are mostly useful while working with the higher order functions.

//General way
render() {   
    return(
        <MyInput onChange={this.handleChange.bind(this) } />
    );
}
//With Arrow Function
render() { 
    return(
        <MyInput onChange={ (e) => this.handleOnChange(e) } />
    );
}

19. Differentiate between stateful and stateless components.

Stateful vs Stateless

Stateful ComponentStateless Component1. Stores info about component’s state change in memory1. Calculates the internal state of the components2. Have authority to change state2. Do not have the authority to change state3. Contains the knowledge of past, current and possible future changes in state3. Contains no knowledge of past, current and possible future state changes4. Stateless components notify them about the requirement of the state change, then they send down the props to them.4. They receive the props from the Stateful components and treat them as callback functions.

20. What are the different phases of React component’s lifecycle?

There are three different phases of React component’s lifecycle:
Initial Rendering Phase: This is the phase when the component is about to start its life journey and make its way to the DOM.*Updating Phase: *Once the component gets added to the DOM, it can potentially update and re-render only when a prop or state change occurs. That happens only in this phase.*Unmounting Phase: *This is the final phase of a component’s life cycle in which the component is destroyed and removed from the DOM.### 21. Explain the lifecycle methods of React components in detail.

Some of the most important lifecycle methods are:
componentWillMount() **Executed just before rendering takes place both on the client as well as server-side.componentDidMount() **Executed on the client side only after the first render.***componentWillReceiveProps() ***– Invoked as soon as the props are received from the parent class and before another render is called.shouldComponentUpdate() **Returns true or false value based on certain conditions. If you want your component to update, return true else return false. By default, it returns false.*componentWillUpdate() *– Called just before rendering takes place in the DOM.componentDidUpdate() **Called immediately after rendering takes place.*componentWillUnmount() *– Called after the component is unmounted from the DOM. It is used to clear up the memory spaces.### 22. What is an event in React?

In React, events are the triggered reactions to specific actions like mouse hover, mouse click, key press, etc. Handling these events are similar to handling events in DOM elements. But there are some syntactical differences like:
Events are named using camel case instead of just using the lowercase.Events are passed as functions instead of strings.
The event argument contains a set of properties, which are specific to an event. Each event type contains its own properties and behavior which can be accessed via its event handler only.

23. How do you create an event in React?

class Display extends React.Component({   
    show(evt) {
        // code  
    },  
    render() {     
        // Render the div with an onClick prop (value is a function)       
        return (           
           
 
 
<div onClick={this.show}>Click Me!</div>
 
 
 
        );   
    }
});

24. What are synthetic events in React?

Synthetic events are the objects which act as a cross-browser wrapper around the browser’s native event. They combine the behavior of different browsers into one API. This is done to make sure that the events show consistent properties across different browsers.

25. What do you understand by refs in React?

Refs is the short hand for References in React. It is an attribute which helps to store a reference to a particular React element or component, which will be returned by the components render configuration function. It is used to return references to a particular element or component returned by render(). They come in handy when we need DOM measurements or to add methods to the components.

class ReferenceDemo extends React.Component{
     display() {
         const name = this.inputDemo.value;
         document.getElementById('disp').innerHTML = name;
     }
render() {
    return(       
          
 
 
<div>
            Name: <input type="text" ref={input => this.inputDemo = input} />
            <button name="Click" onClick={this.display}>Click</button>           
             
 
 
<h2>Hello <span id="disp"></span> !!!</h2>
 
 
 
        </div>
 
 
 
    );
   }
 }

26. List some of the cases when you should use Refs.

Following are the cases when refs should be used:
When you need to manage focus, select text or media playbackTo trigger imperative animationsIntegrate with third-party DOM libraries### 27. How do you modularize code in React?

We can modularize code by using the export and import properties. They help in writing the components separately in different files.

//ChildComponent.jsx
export default class ChildComponent extends React.Component {
    render() {
        return(          
              
 
 
<div>
              
                 
 
 
<h1>This is a child component</h1>
 
 
 
            </div>
 
 
 
        );
    }
}
 
//ParentComponent.jsx
import ChildComponent from './childcomponent.js';
class ParentComponent extends React.Component {   
    render() {       
        return(          
             
 
 
<div>              
                <App />         
            </div>
 
 
 
        
        ); 
    }
}

28. How are forms created in React?

React forms are similar to HTML forms. But in React, the state is contained in the state property of the component and is only updated via setState(). Thus the elements can’t directly update their state and their submission is handled by a JavaScript function. This function has full access to the data that is entered by the user into a form.

handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
}
 
render() {
    return (       
         
 
 
<form onSubmit={this.handleSubmit}>
            <label>
                Name:
                <input type="text" value={this.state.value} onChange={this.handleSubmit} />
            </label>
            <input type="submit" value="Submit" />
        </form>
 
 
 
    );
}

29. What do you know about controlled and uncontrolled components?

Controlled vs Uncontrolled Components

30. What are Higher Order Components(HOC)?

Higher Order Component is an advanced way of reusing the component logic. Basically, it’s a pattern that is derived from React’s compositional nature. HOC are custom components which wrap another component within it. They can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components. You can say that HOC are ‘pure’ components.

31. What can you do with HOC?

HOC can be used for many tasks like:
Code reuse, logic and bootstrap abstractionRender High jackingState abstraction and manipulationProps manipulation### 32. What are Pure Components?

*Pure *components are the simplest and fastest components which can be written. They can replace any component which only has a **render(). **These components enhance the simplicity of the code and performance of the application.

33. What is the significance of keys in React?

Keys are used for identifying unique Virtual DOM Elements with their corresponding data driving the UI. They help React to optimize the rendering by recycling all the existing elements in the DOM. These keys must be a unique number or string, using which React just reorders the elements instead of re-rendering them. This leads to increase in application’s performance.

React Redux – React Interview Questions

34. What were the major problems with MVC framework?

Following are some of the major problems with MVC framework:
DOM manipulation was very expensiveApplications were slow and inefficientThere was huge memory wastageBecause of circular dependencies, a complicated model was created around models and views### 35. Explain Flux.

Flux is an architectural pattern which enforces the uni-directional data flow. It controls derived data and enables communication between multiple components using a central Store which has authority for all data. Any update in data throughout the application must occur here only. Flux provides stability to the application and reduces run-time errors.

36. What is Redux?

Redux is one of the hottest libraries for front-end development in today’s marketplace. It is a predictable state container for JavaScript applications and is used for the entire applications state management. Applications developed with Redux are easy to test and can run in different environments showing consistent behavior.

37. What are the three principles that Redux follows?

***Single source of truth: ***The state of the entire application is stored in an object/ state tree within a single store. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.***State is read-only: ***The only way to change the state is to trigger an action. An action is a plain JS object describing the change. Just like state is the minimal representation of data, the action is the minimal representation of the change to that data. Changes are made with pure functions: In order to specify how the state tree is transformed by actions, you need pure functions. Pure functions are those whose return value depends solely on the values of their arguments.### 38. What do you understand by “Single source of truth”?

Redux uses ‘Store’ for storing the application’s entire state at one place. So all the component’s state are stored in the Store and they receive updates from the Store itself. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.

39. List down the components of Redux.

Redux is composed of the following components:
Action – It’s an object that describes what happened.**Reducer **– It is a place to determine how the state will change.Store – State/ Object tree of the entire application is saved in the Store.View – Simply displays the data provided by the Store.### 40. Show how the data flows through Redux?

41. How are Actions defined in Redux?

Actions in React must have a type property that indicates the type of ACTION being performed. They must be defined as a String constant and you can add more properties to it as well. In Redux, actions are created using the functions called Action Creators. Below is an example of Action and Action Creator:

function addTodo(text) {
       return {
                type: ADD_TODO,   
                 text   
    }
}

42. Explain the role of Reducer.

Reducers are pure functions which specify how the application’s state changes in response to an ACTION. Reducers work by taking in the previous state and action, and then it returns a new state. It determines what sort of update needs to be done based on the type of the action, and then returns new values. It returns the previous state as it is, if no work needs to be done.

43. What is the significance of Store in Redux?

A store is a JavaScript object which can hold the application’s state and provide a few helper methods to access the state, dispatch actions and register listeners. The entire state/ object tree of an application is saved in a single store. As a result of this, Redux is very simple and predictable. We can pass middleware to the store to handle the processing of data as well as to keep a log of various actions that change the state of stores. All the actions return a new state via reducers.

44. How is Redux different from Flux?

Flux vs Redux

FluxRedux1. The Store contains state and change logic1. Store and change logic are separate2. There are multiple stores2. There is only one store3. All the stores are disconnected and flat3. Single store with hierarchical reducers4. Has singleton dispatcher4. No concept of dispatcher5. React components subscribe to the store5. Container components utilize connect6. State is mutable6. State is immutable

45. What are the advantages of Redux?

Advantages of Redux are listed below:
**Predictability of outcome – **Since there is always one source of truth, i.e. the store, there is no confusion about how to sync the current state with actions and other parts of the application.**Maintainability – **The code becomes easier to maintain with a predictable outcome and strict structure.Server-side rendering – You just need to pass the store created on the server, to the client side. This is very useful for initial render and provides a better user experience as it optimizes the application performance.**Developer tools – **From actions to state changes, developers can track everything going on in the application in real time.**Community and ecosystem – **Redux has a huge community behind it which makes it even more captivating to use. A large community of talented individuals contribute to the betterment of the library and develop various applications with it.**Ease of testing – **Redux’s code is mostly functions which are small, pure and isolated. This makes the code testable and independent.**Organization – **Redux is precise about how code should be organized, this makes the code more consistent and easier when a team works with it.
React Router – React Interview Questions

46. What is React Router?

React Router is a powerful routing library built on top of React, which helps in adding new screens and flows to the application. This keeps the URL in sync with data that’s being displayed on the web page. It maintains a standardized structure and behavior and is used for developing single page web applications. React Router has a simple API.

47. Why is switch keyword used in React Router v4?

Although a

is used to encapsulate multiple routes inside the Router. The ‘switch’ keyword is used when you want to display only a single route to be rendered amongst the several defined routes. The ** **tag when in use matches the typed URL with the defined routes in sequential order. When the first match is found, it renders the specified route. Thereby bypassing the remaining routes.

48. Why do we need a Router in React?

A Router is used to define multiple routes and when a user types a specific URL, if this URL matches the path of any ‘route’ defined inside the router, then the user is redirected to that particular route. So basically, we need to add a Router library to our app that allows creating multiple routes with each leading to us a unique view.

<switch>
    <route exact path=’/’ component={Home}/>
    <route path=’/posts/:id’ component={Newpost}/>
    <route path=’/posts’   component={Post}/>
</switch>

49. List down the advantages of React Router.

Few advantages are:
Just like how React is based on components, in React Router v4, the API is ‘All About Components’. A Router can be visualized as a single root component () in which we enclose the specific child routes ().No need to manually set History value: In React Router v4, all we need to do is wrap our routes within the component.The packages are split: Three packages one each for Web, Native and Core. This supports the compact size of our application. It is easy to switch over based on a similar coding style.### 50. How is React Router different from conventional routing?

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!