Implementing BFS in JavaScript

Photo by Reuben Juarez on Unsplash

In my previous blog I have introduced how to implement the graph data structure in JavaScript. Now, let’s see how to implement BFS (Breadth-first search) in JavaScript.

When we implement BFS, we need to use queue, also as known as FIFO(first-in, first-out).

Now we want to see if there is friendship between two people. Below is an example we want to know if Viv is friend with Carlos:

We check the console we will know:

In the first step, we started with ‘Viv’ and it is the only person in the queue for now, and visit all Viv’s friends who are Peter and Diane. Then we pushed them in the queue and marked Viv as visited. Then in our queue, now we have Peter and Diane, we found Peter’s friend is Viv, because we have been visited Viv, so we take out Peter from our queue and marked as visited. Then starting explore Diane’s friends who are Carlos and Viv. Therefore we found our target Carlos.




Full-Stack Web Developer, Flatiron School Grad

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Migrations and Seeding Made Easy in Node JS Using Sequelize

nodejs - sequelize ORM many to many setup - bjdejong BLOG

Test REST APIs using Jest and Supertest

Blog Post Class 8

Angular Elements a Complete Guide

How to Shake Up a React Game using onKeyPress

Step by step instructions to Utilize Google Spot Autocomplete With Respond Without an Outsider…

Cloning Shopper Stop website in 7 days using HTML, CSS and JavaScript

Part 7: JavaScript Functions → Currying

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


Full-Stack Web Developer, Flatiron School Grad

More from Medium

Promises in Javascript ES6

Using Objects for Lookups in Javascript

this keyword in JavaScript

Basic points of JavaScript