I am currently practicing while loops and then turning loops into recursion below is an example of code that produces the result but I am unsure why I am getting a type error:
const frenchie = {
name: "Lokys",
friend: {
name: "Benken",
friend: {
name: "Weller"
}
}
}
let currentFrench = frenchie
while(currentFrench !== null){
console.log(currentFrench.name)
currentFrench = currentFrench.friend
}
Above code will produce the output I want in regards to the name but the error message I see is:
Uncaught TypeError: Cannot read properties of undefined (reading 'name') at script.js:13:31
However, if I change the code to this:
const frenchie = {
name: "Lokys",
friend: {
name: "Benken",
friend: {
name: "Weller"
}
}
}
let currentFrench = frenchie
while(currentFrench != null){
console.log(currentFrench.name)
currentFrench = currentFrench.friend
}
It produces the same result but with no type error. I THOUGHT !==
using a strict bang operator (i think this is the right term I am still learning) like this would be the best route. Similar to house I try to use const
vs let
when it makes sense to not produce side effects or ==
vs ===