Getting started with Reason React and BuckleScript

This tutorial will introduce OCaml, Reason React, and BuckleScript, and explain their relevance. To wrap things up, we will take a look at a demo project built with ReasonReact. ReasonReact is a simpler and much safer way to build React components in Reason, and with the help of BuckleScript, we can have access to a JavaScript version of all code written in Reason. More about this later in the tutorial.

This tutorial will introduce OCaml, Reason React, and BuckleScript, and explain their relevance. To wrap things up, we will take a look at a demo project built with ReasonReact. ReasonReact is a simpler and much safer way to build React components in Reason, and with the help of BuckleScript, we can have access to a JavaScript version of all code written in Reason. More about this later in the tutorial.

Introduction

The importance of productivity in programming is very crucial to the success of any Software Engineer in particular, as it facilitates an implementation of features on time, working successfully with a very large team, and my favorite, being able to sleep at night without getting worried about the new code you just merged with the master branch.

There are many competing programming paradigms, each with their own approaches to application flow, syntax and other conventions.

Easy access to relevant tools, you will agree with me, will go a long way to not only make you productive as a Software Engineer but also enhance your current skill set.

The semantics

OCaml is an expressive and dynamic strictly typed general purpose programming language. It lays more emphasis on expressiveness and safety. Its been around for a while (over 20 years) now but its popularity has been on the lower side due to its small community. Most notable companies make use of it to minimize errors and improve speed. Facebook, for example, uses OCaml to developed type checkers like Hack for PHP and Flow for JavaScript.

The syntax

Reason on the other hand is not another programming language per say, but a new syntax and toolchain powered by OCaml. It provides a familiar, usable interface intended to make interoperation with JavaScript and adoption by JavaScript developers easier. In view of this, ReactReason was introduced to give JavaScript developers, especially the ReactJS community, to leverage the greater type system of Reason.

The compiler

BuckleScript compiles OCaml/Reason code down to plain JavaScript that can easily be shipped to virtually any browser in the world. One of the benefits of BuckleScript is the amazing speed at which it compiles down to human-readable JavaScript.

Getting started

Run the command below to globally install BuckleScript on your machine:

 $ npm install -g bs-platform 

Once the installation process is completed, we will now fully have access to the bsbcommand that would be used to easily initialize a quick Reason project.

Creating a basic project

By now, you should have BuckleScript installed successfully. To see it in action, let’s generate a lightweight Reason project template with:

 $ bsb -init reason-sample-project -theme basic-reason 

The boilerplate should have a similar project structure as shown here:

Next, run a command to build the project from the terminal in the root directory of the project:

 $ npm run build 

Did you notice a new file Demo.bs.js that was quickly generated for the project? The compiled version of Reason to JavaScript is housed by this file. Feel free to check and view it.

Lastly, type node src/demo.bs.js in your terminal to run the JavaScript output.

This will log a message Hello, BuckleScript and Reason! to the console. Now open the project with your favorite text editor and make a change to the message within the Js.log()method located in ./src/Demo.re , then proceed to build and see your changes.

Concepts overview

Reason introduces a new way of writing OCaml and still retains access to the beauty of static types. Let’s take a quick look at some basic concepts of Reason, such as variants, functions, and pattern-matching since we’ll be using it to build a demo.

Variants in Reason are data types and structures. It can be used to define sets of symbols and data structures. You can read more about variant here.

 /* ./src/Demo.re */ type animal = Cat(string) | Dog(string); 

We have the type of an animal which can either be a Cat or Dog and both will only accept a string as an argument.

Functions in Reason are declared with an arrow and a return expression. Declare one as shown here:

 /* ./src/Demo.re */ let speak = (animal) => switch (animal) { | Cat(name) => name ++ " says: meow" | Dog(name) => name ++ " says: woof" }; 

Here, what we have done is to declare a function speak and passed an argument using the type that was declared earlier. Within it, we used a switch expression and checked for every possible case of the animal variant, this is referred to as pattern-matching in Reason. One of the advantages of pattern-matching is that it is very exhaustive, you will get a warning in the console if you did not check for both cases.

Furthermore, for each of the variants, we passed a variable name and later concatenated it with a statement representing what we want each of the animal to say.

Now we can simply call the function and passed any of the types of animal into it:

 /* ./src/Demo.re */ Js.log(speak(Dog("Cooper"))); Js.log(speak(Cat("Buddy"))); 

Navigate to ./src/Demo.bs.js to see the equivalent JavaScript version of the functions declared in Reason above as compiled by BuckleScript.

Let’s build a todo app with Reason

To get a better grasp of the concept of building web applications with Reason, we’ll use Reason-scripts to build a simple todo list application. This will be a familiar experience for ReactJS users that are conversant with create-react-app. While building this app we will get a much better introduction to the syntax and type system of Reason.

Prerequisites

A basic understanding of React will be of great assistance with this tutorial. Before we get started, we need to install some required set of tools:

  1. We will be using create-react-app to create a boilerplate for this project. Run this command from your terminal to install it globally on your machine:
 $ npm i -g create-react-app 
  1. Finally head over to editor setup to get the Reason plugin for your favorite editor as this will help facilitate the development process.
Creating the Reason React project

We’ll create our project using the create-react-app command. Navigate to your project folder and run a command that will create a project named reason-bucklescript-todo:

 $ create-react-app reason-bucklescript-todo --scripts-version reason-scripts 

Next, change directory into the newly created project and first, run npm link bs-platformand start the application with npm start or yarn start:

ReasonReact components

Similar to a ReactJS application, ReasonReact supports the use of components to structure an application. By default, the create-react-app already generated a basic App component for us. Navigate to ./src/App.re and edit as follow:

 /* ./src/App.re */ [%bs.raw {|require('./App.css')|}]; [@bs.module] external logo : string = "./logo.svg"; let component = ReasonReact.statelessComponent("App"); let make = (~message, _children) => { ...component, render: _self => <div className="App"> <div className="App-header"> <img src=logo className="App-logo" alt="logo" /> <h2> {ReasonReact.string(message)} </h2> </div> <div className="App-intro"> <Todo /> </div> </div>, }; 

Since the structure of the file above is similar to what we would have for other components, let’s take a quick look at some of its parts.

First, we required a stylesheet with [%bs.raw {|require('./App.css')|}]; at the top of the file. BuckleScript allows us to include some raw JavaScript code by using [%bs.raw ] and wrapping the JavaScript code with {| |}.

Defining a component

Next, a component can either be stateless or stateful. In ReasonReact, there are different ways of defining them:

  1. Stateless components: defined as ReasonReact.statelessComponent("componentName")
  2. Stateful components: defined as ReasonReact.reducerComponent("componentName")

Furthermore, we declared a make function which takes in two different parameters. The first parameter has a symbol ~ indicating that it was passed into the App component as a propsand the second parameter has _, this is a more explicit way of showing that the parameter isn’t used and ignored.

In addition, the …component spread operator indicated that the make function declared is building upon the component that was just defined. We also declare a render function with a single argument _self that is not used at the moment.

Rendering a string in ReasonReact is a little bit different than what we have in ReactJS, here you will have to wrap the string with a function named ReasonReact.string().

Finally, we included and rendered a component <Todo /> without importing any file, interesting right? In ReasonReact, every component is a module and doesn’t need to be imported before it can be used in another module. We’ll create this Todo component in a bit.

Creating components

For a better folder structure, we will group all new components in the same directory that will be named components. For BuckleScript to detect the Reason files and compile them easily to JavaScript we’ll need to edit the BuckleScript configuration file. Open ./bsconfig.json and add a new source as shown below:

    // ./bsconfig.json
{
  "name": "reason-scripts",
  "sources": [
    "src",
    "src/components" // Add this line
  ],
  ...
}

With the configuration above, any .re file created within the components directory will be compiled down to JavaScript. Before we start creating the required files, locate the srcdirectory and create another directory named components inside of it.

Set up the todo component

First, let’s create a new file, TodoType.re in the components directory and paste the code below in it. This will define the data structure for the list of Todo items:

 /* ./src/components/TodoType.re / type item = { id: int, title: string, completed: bool, };

As pointed out earlier, every file in ReasonReact is a module and all the things defined at the top level of the file using the keywords let, type, and module are exposed to be used from other files. So in other components we will need to reference the TodoType component that we just created.

Todo component

Navigate to the src/components directory and create a new file Todo.re within it. Open the new file and paste in this code:

 / ./src/components/Todo.re / type state = { items: list(TodoType.item), inputText: string, }; type action = | InputText(string) | Toggle(int) | RemoveItem(int) | Submit; let component = ReasonReact.reducerComponent("Todo"); let make = children => { let handleSubmit = state => { let newId: int = List.length(state.items); let newItem: TodoType.item = { id: newId, title: state.inputText, completed: false, }; let newList = [newItem, ...state.items]; ReasonReact.Update({items: newList, inputText: ""}); }; { ...component, initialState: () => { items: [{id: 0, title: "Fix more bugs", completed: false}], inputText: "", }, reducer: action => switch (action) { | InputText(newText) => ( state => ReasonReact.Update({...state, inputText: newText}) ) | Toggle(id) => (state => ReasonReact.Update({ ...state, items: List.map((item: TodoType.item) => item.id == id ? { ...item, TodoType.completed: ! TodoType.(item.completed), } : item, state.items, ), }) ) | RemoveItem(id) => ( state => ReasonReact.Update({ ...state, items: List.filter( (item: TodoType.item) => item.id !== id, state.items, ), }) ) | Submit => (state => handleSubmit(state)) }, render: self => { let {items, inputText} = self.state; <div className="app"> <div className="app-header"> <div className="title"> {ReasonReact.string("Todo List")} </div> </div> <Input submit=( => self.send(Submit)) value=inputText onInputText=(text => self.send(InputText(text))) /> <div className="list"> ( ReasonReact.array( Array.of_list( List.map( (item: TodoType.item) => <Item key=(string_of_int(item.id)) item onRemove=(id => self.send(RemoveItem(id))) onToggle=(id => self.send(Toggle(id))) />, items, ), ), ) ) </div> </div>; }, }; };

The file above is an example of a stateful component in ReasonReact. And within it, first, we defined the state for the component and a set of actions that will be required to mutate the state of each item. And within the make function of the component, we defined a function named handleSubmit to handle the addition of new item and then update the existing todo list once created.

Next, we defined the initialState of the todo items and added a reducer method which takes the action as a parameter and used pattern-matching on the action type, returning a ReasonReact.Update which contains the new state.

Input component

This component will be used to add an item to a to-do list and therefore can be maintained as a stateless component since its main function is to emit an event that will trigger the handleSubmit function within the Todo component. Create this file within ./src/componentsand name it Input.re. Once you are done, paste the content below in it:

 / ./src/components/Input.re / let component = ReasonReact.statelessComponent("Input"); let make = (~value, ~onInputText, ~submit, _children) => { ...component, render: self => <div className="input"> <input value placeholder="Enter item and click add" onChange=( event => onInputText( ReactDOMRe.domElementToObj(ReactEventRe.Form.target(event))##value, ) ) /> <button onClick=( => submit())> (ReasonReact.string("Add")) </button> </div>, };

Item component

Finally, we will define a stateless component for rendering the items as they are being added. To do this, create a new file named Item.re within ./src/components directory and paste the code below:

 / ./src/components/Item.re / let component = ReasonReact.statelessComponent("Item"); let make = (~item: TodoType.item, ~onRemove, ~onToggle, _children) => { ...component, render: self => <div className="item"> <input type="checkbox" checked=item.completed onChange=( => onToggle(item.id)) /> <p> {ReasonReact.string(item.title)} </p> <button onClick=( => onRemove(item.id))> {ReasonReact.string("Remove")} </button> </div>, };
Stylesheet

Open ./src/App.css and paste the code below to add some styling to the application:

    / ./src/App.css */

  .App {
    text-align: center;
  }
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
    height: 80px;
  }
  .App-intro {
    font-size: large;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
  }
  .App-header {
    background-color: #222;
    height: 150px;
    padding: 20px;
    color: white;
  }
  .app {
    width: 500px;
    margin: 10px;
  }
  .app-header {
    margin: 10px;
  }
  .title {
    font-size: 25px;
    font-weight: 500;
  }
  .input {
    display: flex;
    justify-content: flex-start;
  }
  .input input {
    width: 80%;
    height: 30px;
    padding: 5px;
    font-size: medium;
  }
  .input button {
    background-color: green;
    color: white;
    font-size: medium;
    width: 30%;
    margin-left: 20px;
  }
  .list {
    margin-top: 25px;
  }
  .item {
    display: flex;
    border: #f5f5f5 2px solid;
    align-items: center;
    height: 30px;
    padding: 10px;
    margin-top: 5px;
    font-size: larger;
  }
  .item p {
    text-align: left;
    margin: auto;
  }
  .item button {
    padding: 10px;
    background-color: grey;
    font-size: 14px;
    opacity: 0.95;
  }
  @keyframes App-logo-spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

And that is it. You should have a functional todo app by now

Conclusion

I hope this very simple application was helpful enough to increase your enthusiasm for exploring Reason and its syntax.

We barely scratched the surface of some awesome features in Reason and BuckleScript. You can visit the documentation to learn more about it.

The source code for the todo app can be found here on GitHub.

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!