If-Else Statement

I am currently taking the Javascript course. I’m doing exercise 2 of the array section. I have been having trouble with when to use brackets vs when not to etc. And currently I’m getting caught up on an if-else statement. For some reason my code works when I drop the “else” in my if-else statement. Any ideas/explanation?

When I add the “else” it doesn’t work

Your Below code In First Image

for (let n of array) {
    if (n === value) {
        // your code
    }
    {
        // this block of code will never executed 
        console.log(your_message)
    }
}

IS SAME AS

for (let n of array) {
    if (n === value) {
        // your code
    }
}

yes, understood. But why doesn’t it work when the “else” word is added?

see first reply screenshot with red outlines

Pretty much. You instinctively added the braces for the if which are not in the original code. But the explanation is correct. When you do not delimit an if with curly braces, it deals with the next statement only. It happens that the next statement has a body so multiple lines are executed.

Now for the other part it is just like the curly braces around the console.log are not there.

When you add the else you go through your array value by value. So you go with -2 first which differs from 25. The return instruction exits the for loop.

When the else is not there, it will simply go on until it reaches the value. So it will work as intended without else but not with. This could be discouraged to write the code that way.

Ultimately your code is equivalent to this which is OK. There is no more misleading curly braces and the intent is more explicit.

const numbers = [-2, 5, 9, -8, -10, 10, 11, 25];

let myIncludes = (array, value) => {
    for (let n of array) {
        if (n === value) {
            console.log(value + " is part of this array! :)");
            return true;
        }
    }

    console.log(value + " is not part of this array, sorry! :(");
    return false;
};

console.log(myIncludes(numbers, 25));

Many argue not putting curly braces around one-liners if, for, etc… statements is not a good practice and I wouldn’t agree most of the time. But in this scenario I would put them.

On the other hand I see nothing wrong with something like

if (condition)
   console.log("I am actually nicer and more readable.");

:100: Pro Tip

Learn to use the debugger. Either in any IDE, code editor capable of it or a web browser.
You can just stop the execution and go step by step to observe and understand the behaviour of your code.

image

3 Likes