Noob JS question: if condition in "emphasis on aim"


#1

Hail ye wise and mighty!

I’m new to programming JS and not very experienced in other languages either (Logo and Turbo Pascal in school - way back) and I have a fundamental question concerning the workings of the if-condition.

While playing “emphasis on aim” I went crazy because
if (unit.team == “ogres”) {xyz}
didn’t cut it. Why?

Why does it demand
if (unit && unit.team === “ogres”)?

My understanding was that as long as there is no unit in range the if statement is not true and we (should) jump straight to “else”. What’s the flaw here? What does unit.team return if there is no unit in range?
I get the error message “Cannot read property team of null”. Fair enough. But so what? Surely that means that whatever unit.team is, it is NOT “ogres”. Why doesn’t the code come around once there is a unit?

Sorry if this is a dumb question to ask.
And thank you for getting me excited about programming again!


#2

Hey @Barbarossa!

It’s not unit.team that is null; it’s that unit is null, so asking what its team is causes an error, because you can’t read properties of null variables. And in this system (like most systems), the code stops running once it has hit an error, so it doesn’t go long enough to hit the point where there is a unit within range.