Home > Net >  JavaScript Array interview question; couldn't find the bug
JavaScript Array interview question; couldn't find the bug

Time:10-19

A friend of mine was asked the question below during a live interview and was given 4 minutes to answer it.

QUESTION: Without opening any other browser or using code editor, analyze the code below and give your verdict if it is correct and good to go, if not, debug the code and explain your answer.

const weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

for (let i = 0; i < weekDays.length; i  ){
    if (i === 'Wednesday'){
        console.log('Today is Wednesday, join board meeting by 10:00am');
        continue;
    }
    if (i === 'Saturday'){
        console.log("Today is Saturday, weekend is great!");
        break;
    }
    console.log(weekDays[i]);
}

CodePudding user response:

Just take a for ... of statement, because the array could have days in different order or start.

And for really good code, take a semantic name day instead of i.

const weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

for (const i of weekDays) {
    if (i === 'Wednesday') {
        console.log('Today is Wednesday, join board meeting by 10:00am');
        continue;
    }
    if (i === 'Saturday') {
        console.log("Today is Saturday, weekend is great!");
        break;
    }
    console.log(i);
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I know you provided your own answer, but this code could easily be cleaned up further to reduce bugs:

for (let i = 0; i < weekDays.length; i  ) {
    if (i === 3) {
        console.log('Today is Wednesday, join board meeting by 10:00am');
    } else if (i === 6) {
        console.log("Today is Saturday, weekend is great!");
    } else {
        console.log(weekDays[i]);
    }
}

Still not a fan of the magic numbers. Perhaps i === Day.Wednesday or weekDays[i] === Day.Wednesday depending on what's expected to change.

CodePudding user response:

for (let i = 0; i < weekDays.length; i  ){
    if (i === 3){
        console.log('Today is Wednesday, join board meeting by 10:00am');
        continue;
    }
    if (i === 6){
        console.log("Today is Saturday, weekend is great!");
        break;
    }
    console.log(weekDays[i]);
}

EXPLANATION: There are bugs in line 2 => (i === 'Wednesday') and line 6 => (i === 'Saturday'). The 'Wednesday' in line 2 should be changed to 3 while the 'Saturday in line' 6 should be changed to 6.

Reason: An array loops through its values by indexing, e.g 1, 2, 3,... and not by the name of the values. So the array, by looping through doesn't understand 'Wednesday' and 'Saturday' but its index which are 3 and 6 respectively.

  • Related