Interview Question - JavaScript Arrays - Find City

This is an interview question on JavaScript Arrays. You will make use of indexOf method on arrays to find the output of the code

Code

let cities = ["Vancouver", "Boston", "New York", "Victoria", "San Francisco"]
let updatedCities = cities.map(city => city + 2)
console.log(updatedCities.indexOf("Victoria"))

Full Transcript

00:00 So we have bunch of cities in the cities array and we are performing some computation on this array. And finally we want to know what happens when we find indexOf Victoria city. Let's work together to find the right answer. In the first line, we create an array with five cities. In the second line, we're using map method on arrays. This means that the result of this expression will produce a new array. But what will this area contain? That is defined by the implementation inside the map method. For each city that is available in cities, we are adding number two, so the value of updatedCities will be a new array that contains all the cities from the cities array, but number two added to the each city. Now in the final console.log we are trying to find the string Victoria in the updatedCities array. And as you can see, Victoria does not exist in the array.

00:50 The indexOf method returns -1 for the element that does not exist in the array, which is the correct answer for this question. Let's run this in editor and confirm that our understanding is correct. For the same code, when I go and hit run, we can see that the final output is -1. And that's it. If you work with JavaScript or any other frameworks such as jQuery, angular, or react, you have executed JavaScript on the browser. So the new course that we have launched is relevant for you. It's called Browser JavaScript and event loop. This course educates on how JavaScript is executed behind the scenes, and we'll cover various topics such as ExecutionContext and event loop. You will have the opportunity to visually see every step of JavaScript code execution. Check out the course link in the description below o learn more about the course and let us know if you have any questions. Keep learning and see you next time.