Rocking JS data structures!

Rocking JS data structures!

<strong>JavaScript's development has been quite stubborn up to 2015. Yeah, that's the magic time ES6was announced and the whole web-development-thing really took off and grew in popularity exponentially. 📊 But, that's something every JS fan probably knows - the year, the exact moment has been repeatedly referenced in many, many JS resources around the world. So, let's be innovative and do the same again, shall we?</strong>

JavaScript's development has been quite stubborn up to 2015. Yeah, that's the magic time ES6was announced and the whole web-development-thing really took off and grew in popularity exponentially. 📊 But, that's something every JS fan probably knows - the year, the exact moment has been repeatedly referenced in many, many JS resources around the world. So, let's be innovative and do the same again, shall we?

ES6 has brought a great number of new goodies to JS. Not only now-must-have arrow functionspromises, and syntactic sugar, but also new data structures. 🔢 That’s right, I’m talking about things like Sets, WeakMaps and etc. (if you already know them). These little, but very interesting features have been pushed into the background, mainly because of how long it took for modern browsers to fully embrace new specification. As time passed ⏳, people started using new syntax and some really desired new functionalities, but these structures became less relevant. Of course not to all, but taking even as obvious example as myself - I hardly ever used them. I just stuck with old-school arrays and object and lived within that limited scope. But, don’t worry, because in this article we’ll explore how good and useful these structures can really be. With new possibilities they provide and their current support… just why not? 😃

TypedArrays

I guess you know arrays, cause who doesn’t? All methods they provide, functional programming possibilities and more are just so impressive. But, if so, then what TypedArrays are and why do we need them?

TypedArrays instead of having a single class on their own, is a name used to reference different types of these specific structures. They basically serve as custom, array-like views to binary data buffers, which I guess require a bit more explanation. 😉

ArrayBuffer

ArrayBuffer is a class used to contain fixed-length raw binary data. 💾 You can create one by using its constructor with a length argument, indicating the number of bytes for your buffer.

const buffer = new ArrayBuffer(8);

ArrayBuffers don’t have many properties of their own. Most notable being byteLength and slice() - one for retrieving the length of the buffer in bytes (like the provided one) and other for slicing the specified part of the buffer and creating the new one. The only way you can interact with ArrayBuffers is through so-called view - either TypedArray or DataView (but that’s a story for another day).

The importance of ArrayBuffers comes from the way in which they represent your data - raw binary. Such form is required by some low-level API, like WebGL, because of its efficiency 🏎 and integration 🤝 with other parts of code, like e.g. shaders.

TypedArray[s]

Now, that we know that TypedArrays serve as a view for ArrayBuffer, let’s first list 'em all!

  • Int[8/16/32]Array - for interpreting buffers as arrays of integer numbers with the given number of bits for representing each;
  • Uint[8/16/32]Array - unsigned integer numbers with the given number of bits for each;
  • Float[8/16/32/64]Array - floating-point numbers with the given number of bits for each;
  • BigInt64Array - integer numbers (bigint) with 64 bits for each;
  • BigUint64Array - unsigned integer (bigint) numbers with 64 bits for each;

Each of the above types of TypedArrays has the same set of methods and properties, with the only difference being in the way of representing the data. TypedArray instance can be created with a given length (creating ArrayBuffer internally), another TypedArrayan object (with length and values for given indexes as keys) or previously instantiated ArrayBuffer. 👨‍💻

Usage

Now, as you have your TypedArray ready, you can freely edit it with methods similar to a normal array. 👍

const typedArr = new Uint8Array([0,1,2,3,4]);
const mapped = typedArr.map(num => num * 2); // Uint8Array [0,2,4,6,8]

One thing to note though, because, as under-the-hood you’re operating on the ArrayBuffer’s data, your TypedArray has fixed size. Furthermore, all methods that can be found in normal arrays, that edit their size (removing, adding, cutting, etc.) have limited possibilities or are completely unavailable. 🤐

const typedArr = new Uint8Array([0,1,2,3,4]);
typedArr.push(5) // Error! You must be kidding me!

You can also iterate on these and convert them to standard arrays back and forth, whenever you want.

const typedArr = new Uint8Array([0,1,2,3,4]);
for(const num of typedArr){
// code
}
const arr = Array.from(typedArr); // [0,1,2,3,4]

TypedArrays provide certain functionalities related to its binary-side too! You can e.g. access the underlying ArrayBuffer instance with buffer property and read its byte length and offset using byteLength and byteOffsetrespectively. 🙂

Use-cases

As I mentioned before, ArrayBuffers have big potential because of the way they represent data. Such compact form can be easily used in many, many places. It can be e.g. vector 🎨 or other compressed data 📦 sent from a server, packed for maximum speed and performance at all stages - compression, transfer, and decompression. In addition, as I said earlier, some Web APIsmake good use of the efficiency this format brings. 👌

With TypedArrays on top of ArrayBuffers, it’s so much easier to manipulate the data inside (definitely better than setting bits themselves 😅). Beyond one and only limit of fixed size, you can interact with this compact data pretty much the way you would with everyday arrays.

Sets

Continuing our research of array-like structures, we’re getting to Sets. 🗃 These are extremely similar to arrays - they can be used to store data in a similar way, with only one important difference. All of Set’s values must be unique(there are some weird cases tho 😵) - whether we’re talking about primitive values or object references - doubles are automatically removed.

Usage

Creating Sets is easy - you just need to use the right constructor with an optional argument to provide data from the start.

const dataSet = new Set([1, 2, 3, 4, 5]);

Sets provide pretty expressive API of their own. Most important being methods like:

  • add() - appends given value to the end of the Set;
  • delete() - removes given value from the Set;
  • has() - checks if given value is present in the Set;
  • clear() - removes all values from the Set;

They can also be converted to standard arrays and iterated at will.

const dataSet = new Set([1,2,3]);
const values = [0,1,2,3,4];
for(const value of values) {
if(dataSet.has(value)){
dataSet.delete(value)
} else {
dataSet.add(value);
}
}
const result = Array.from(dataSet); // [0,4];

Use-cases

Most use cases of Sets are clearly based on their ability to store unique values only. ⚡ Using such a technique with mere arrays would require some additional boilerplate. Therefore unique values can be especially useful when storing IDs and alike.🆔

Second, removing elements in Sets is much more convenient. Just providing the value to delete instead of doing whole find-index-and-splice procedure, is just much more convenient. 👍 This, of course, wouldn’t be possible so-easily with repetitive values that standard arrays allow.

WeakSets

Now, let’s talk about different kind of sets - WeakSets. 🤨 WeakSets are special - they store values differently, but also have some additional limitations, like much smaller API.

Memory

First, a word about how WeakSets store their values. Only objects can be used as WeakSets’ values. No primitives allowed. 🛑 This is very important because of the “weak” way in which WeakSets store their data. “Weak” means that if there is no other reference to a given object (object are accessed by reference), they can be garbage-collected 🗑 - removed at any moment. Thus, a good understanding of references and how objects are interacted with is required to properly utilize the potential of weak structures.

Because WeakSets are still… sets, all values they store must be unique. But, as you might know, it’s not a big deal with objects - the only possible type of WeakSets’ values. As all of them are stored by 👉 reference, even objects with exactly the same properties, are considered different.

Usage

API of WeakSets is greatly limited when compared to normal Sets. Probably most important is the fact that they’re not iterable. They don’t have any properties (Sets have e.g. size indicating number of values they store) and only 3 major methods - add()delete() and has(). Constructor method looks the same, only that optional array argument needs to store objects only. However, the use of such an argument doesn’t have much sense, as all objects you store need to be referenced in some other place in your code.

const weakDataSet = new WeakSet();
const obj = {a: 10};
weakDataSet.add(obj);
weakDataSet.add({b: 10}); // Pointless - will be removed soon
weakDataSet.has(obj); // True
weakDataSet.has({a: 10}); // False - objects are stored by reference

Use-cases

It might be quite hard to find good use-cases for WeakSets actually. That’s because, in reality, there aren’t many, and they’re really specific. The most popular and probably the best one is called object tagging. You can use your WeakSets to group and thus tag specific object when they’ve been referenced somewhere else in your code. Tagging or grouping as some might like to call it can be a very useful technique if used properly. ⚠

You need to be cautious, however. Remember that all objects that aren’t referenced anywhere else, will be garbage-collected. But, it doesn’t mean that they’ll be removed immediately, but on the next cycle ⭕ of the garbage collector. You should keep that fact in mind, and don’t trust WeakSets too much - some values can be removed sooner or later.

Maps

Maps, IMHO are structures that make the best of both worlds - arrays and object. Inside them, all data is stored in key-value pairs. 🤝 The difference between such method and usual objects can be further noticed in the API. What’s more, in Maps, keys and values are treated equally, meaning you can do even something as creative as setting an object (but remember that you need a reference to it for later access) as an actual key for your value! Also, unlike in objects, pairs stored in Maps have a specific order and are easily iterable. 🔄

Usage

You can create your Map instance with straight-forward constructor call. You can optionally provide an array of key-value arrays upfront as starting values for your Map.

const map = new Map([["key1", 10], [10, "value2"]]);

It’s when it comes to API where Maps really shine. It allows you to make specific operations faster and in a much more readable way.

There’s one special property called size (available in Sets too) that can give you a quick note about the number of key-value pairs at the given moment. What’s special about that is the fact that there’s no similar, easy enough way to do the same in old-school objects. 😕

And the benefits of this intuitive API don’t end here! If you already like the API of Sets, you might be happy to know that it shares many similarities with the API of Maps. All methods used to edit Maps values can feel like modified to new key-value schema, methods of Sets. Only the add()method has been transformed to set() for obvious, rational-thinking-related reasons. 😅 Other than that, to change and access Maps data, you operate mainly with keys instead of values.

Also, just like Sets and objects (it might not be as relevant when it comes to more array-like Sets), Maps provide 3 methods for reading specific groups of their data:

  • entries() - returns Map’s key-value pairs in form of an array of arrays;
  • values() - returns all of Map’s values in an array;
  • keys() - returns all of Map’s keys in an array;

These methods (especially if you’re practicing functional programming), were most likely extensively used when interacting with object, as there was no other, convenient way. It shouldn’t be the case at all with Maps. With Maps’ API and fine data structure, you should definitely feel your life being a bit easier. 🌈

const map = new Map([['key', 10], ['key2', 10]])
map.forEach((value,key) => {
map.delete(key);
map.set(key, 10);
});

Use-cases

As you can see, Maps give you a great alternative for standard objects. Whenever you need to access both key and its value at the same time and be able to iterate over them, Maps might be your best option.

This nice combination of iterable and object-like form clearly can has many implementations. And, while you can quite easily create the same effect with a normal object - why bother at all? 🤔 The convenience behind this brilliant APIand the fact that it’s an industry standard makes Maps a good choice for a lot of different cases. 👍

WeakMaps

WeakMaps are the second weak structures that we’ve met. Many facts from WeakSets apply here too! This includes the way of storing data, object-only rule, limited API and no iteration (there’s no method giving you the list of these weakly-stored keys).

As you know, Maps (as well as WeakMaps) store data in the key-value schema. This means that there are in fact two collections of data in this one structure - keys and values. The “weak” part of WeakMaps applies only to keys, because it is them who are responsible for allowing us to access values. Mentioned values are stored in normal or if you like the name, strong way. 💪 So, as weird as it may feel, in WeakMaps, only objects can be used as valid keys.

Usage

Just like with WeakSets, WeakMaps API is severely limited. All methods you can used are get()set()delete() and has(). Again, no iteration. 😭 But, if you consider the possible use-cases and how such structures work, you’ll begin to better understand these limits. You cannot iterate over something that’s weakly stored. You need references to your keys and so these 4 basic methods are the best way to go. Etc., etc. 😏

Of course, the constructor takes additional, but a not-so-much-useful argument for initiating data.

const weakMap = new WeakMap();
const value = {a: 10}
weakMap.set({}, value); /* Key will be garbage-collected, but value
will still be accessible through variable. */
weakMap.set(value, 10) // Values don't have to be object-only

Use-cases

WeakMaps have similar use-cases to WeakSets - tagging. All this stuff is happening on the side of keys. Values, however, as strongly-stored data of different types don’t have to be garbage-collected together with the specific key. If saved to a variable earlier, it can still be freely used. This means that you can tag not only one (keys) but also the other side (values) of data and depend on the relations between the two. 🙌

Is that all?

For now - yes. 🤯 I hope that this article helped you learn something new or at least remind some basics. Your JS code doesn’t have to be dependent only on objects and arrays, especially with modern browsers taking more and more market share. 📊 Also, apart from weak structures and their internal behavior, all structures above have pretty simple and nice polyfill options. In this way, you can freely use them, even if it’s only for their fine API.

So, what do you think of this post? Share your opinion below with a reaction or a comment. It really helps me write better articles - you know, the ones you like to read! 😀 Oh, and share the article itself for better reach! Also, follow me on Twitter 🐦, or on my Facebook page and check out my personal blog to keep up-to-date with the latest content from this blog. Again, thank you for reading my content and hope I’ll catch you in the next one! ✌

Originally published by Areknawo https://areknawo.com/rocking-js-data-structures/

Follow great articles on Twitter

Learn More

☞ The Complete JavaScript Course 2019: Build Real Projects!

☞ Become a JavaScript developer - Learn (React, Node,Angular)

☞ JavaScript: Understanding the Weird Parts

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

☞ The Full JavaScript & ES6 Tutorial - (including ES7 & React)

☞ JavaScript - Step By Step Guide For Beginners

☞ The Web Developer Bootcamp

☞ MERN Stack Front To Back: Full Stack React, Redux & Node.js

☞ Visual Studio Code Settings and Extensions for Faster JavaScript Development

☞ Vue.js Authentication System with Node.js Backend

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!

Learn JavaScript in 60 Minutes | JavaScript Crash Course | JavaScript Tutorial |

This video on "JavaScript" will help you learn JavaScript basics and fundamental concepts in 60 minutes. This will provide you in-depth knowledge about the JavaScript fundamentals that will help you write your own code in JavaScript and build a website. This JavaScript tutorial covers following topics..

==================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

Svelte.js - The Complete Guide

The Complete JavaScript Course 2019: Build Real Projects!

Advanced CSS and Sass: Flexbox, Grid, Animations and More!

CSS - The Complete Guide (incl. Flexbox, Grid & Sass)

CSS Bootcamp - Master CSS (Including CSS Grid / Flexbox)

Build Responsive Real World Websites with HTML5 and CSS3

Become a JavaScript developer - Learn (React, Node,Angular)

JavaScript: Understanding the Weird Parts

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

The Full JavaScript & ES6 Tutorial - (including ES7 & React)

JavaScript - Step By Step Guide For Beginners

Javascript | How To Covert Javascript Array To JSON

Javascript | How To Covert Javascript Array To JSON

In this example, we will see How To Covert Javascript Array To JSON. We can convert Javascript array to json using JSON.stringify() method. At some point in your time, whatever developer you are, you need to deal with JSON data. JSON stands for Javascript Object Notation. Exchange data between client and server is straightforward using JSON.

In this example, we will see How To Covert Javascript Array To JSON. We can convert Javascript array to json using JSON.stringify() method. At some point in your time, whatever developer you are, you need to deal with JSON data. JSON stands for Javascript Object Notation. Exchange data between client and server is straightforward using JSON.

How To Covert Javascript Array To JSON

Javascript JSON.stringify() method converts Javascript array to json, and then we can send the string to the server.

Javascript JSON.stringify() is the inbuilt function in which it allows us to take the JavaScript Object or Array and create a JSON string out of it.

JSON.stringify() converts the value to JSON notation representing it:

If a value has the toJSON() method, it’s responsible for defining what data will be serialized.

See the following example.


// app.js

let data = [
  'krunal',
  'ankit',
  'rushabh'
]
jsonData = JSON.stringify(data)
console.log(jsonData)
console.log(typeof jsonData === 'string')

Output


➜  es git:(master) ✗ node app
["krunal","ankit","rushabh"]
true
➜  es git:(master) ✗

In the above code, we have defined a Javascript array with three values and then convert it into a JSON string using JSON.stringify() method.

Then we have printed JSON data in the console and check if the typeof jsondata is a string or not. Of course, it will return true because it is now JSON string ready to send the server via AJAX request. You can use the Axios library to send a network request.

JavaScript Object to JSON

We can use the same JSON.stringify() function to convert the Javascript object to json.

// app.js

let obj = {
  name: 'Krunal',
  rollno: 10,
  site: 'AppDividend'
}
jsonData = JSON.stringify(obj)
console.log(jsonData)
console.log(typeof jsonData === 'string')

Output

➜  es git:(master) ✗ node app
{"name":"Krunal","rollno":10,"site":"AppDividend"}
true
➜  es git:(master) ✗

We have defined an object and then pass to JSON.stringify() method, and it converts from Javascript object to json string.

Often, you need to convert the JavaScript values like string, array, or object into JSON before AJAX POST request.

The JSON object is now part of most modern web browsers (IE 8 & above).

Conclusion

We can convert Javascript datatypes like Number, Array, Object to JSON with just one function, and it is beneficial when exchanging data between client and server.