Working on JavaScript Arrays Interview Question - Find Flight at index

We need to get the output for this piece of code. There is a JavaScript array called flights containing 6 flights. Then, we add to flights array on index 8 a new flight “Virgin Australia” Finally we want to log the value at index 7 in flights. So..let’s understand at what happens when we run this code.

Code

let flights = ["Air Canada", "American Airlines", "Emirates",
"Air France", "Air Asia", "China Southern"];
flights[8] = "Virgin Australia"
console.log(flights[7])

Full Transcript

00:00 We need to get the output for this piece of code. There is a JavaScript array called flights containing six flight names. Then we add to flights array on index 8 a new flight Virgin Australia. Finally, we want to log the value in flights array at index 7. So let's understand what happens when we run the code. When the add a new flight, Virgin Australia to flights array at index 8, the flights array looks like this in memory. Virgin Australia is added to index 8 but arrays are non-contiguous memory allocations in JavaScript, so they allow these empty slots. Now when we tried to access the element in flights array at index 7, it returns undefined. Let's quickly run this code in the editor to validate our understanding. When we run this code, we get the answer undefined, which is actually the correct answer. Thanks for watching this video. If you would like to take your JavaScript knowledge to the next level and want to know and understand how browsers execute JavaScript and the role of event loop, check out our new course which is live. I've added the link in the description below and friends keep learning and share your knowledge.