If statement at the end brings up funny results


#1


https://www.codecademy.com/en/courses/javascript-beginner-en-XEDZA/0/6?curriculum_id=506324b3a7dffd00020bf661

Hi everyone, I had a funny issue with this exercise which made me thinking how the IF function of javascript works in general. You can see the if/else statement at the end of my code? This is how it sould look.

Funny thing is, I made an error before realising i did it wrong, it looked like this

if (hits = 0)
{console.log("Your name wasn't found!")}

else

{console.log(hits)}

I realise what I did wrong. Instead of checking if the length of hits equals 0, i set the variable hits to be equal to 0. In the end the programm printed out just "0".

However I am curious why the programm would print out "0" if i did it like this. Should it not print out "Your name wasn't found"? I mean if I do it this way, hits will be equal to 0, so the first condition should be fullfilled and it should NOT use the ELSE case? Or am I wrong?


var text ="Hey how are you \
doing? My name is Emily.";

var myName ="Emily";

var hits = [];

for (i = 0; i < text.length; i++)
{
    if (text[i] === myName[0])
    {
        for(var j = i; j < (i + myName.length); j++)
        {
            hits.push(text[j]);
        }    
    }
}

if (hits.length === 0)
{console.log("Your name wasn't found!")}

else

{console.log(hits)}


#2

shouldn't it print []? Either way, if you use a single equal sign, hits.length become 0, which mean if evaluates to false, which means eise will run and [] should be printed, 0 might also happen because the codecademy console echoes the last value


#3

Thank you for your response.

But what I still dont understand is, why does the if statement evaluate to false if I use the code like

if (hits = 0)
{console.log("Your name wasn't found!")}

?


#4

well, hits get assigned a value of zero, and then hits is zero, and zero is considered false