WhaleTalk Exercise in JS

Hello,

I’m working on WhaleTalk exercise and I was able to figure out after several tries and troubleshooting on my code BUT one thing that is not clear to me is the use of semi-colon ; on line 8 below:

Correct Output:

let input = 'turpentine and turtles';
const vowels = ['a', 'e', 'i', 'o', 'u'];
const resultArray = [];
for (i = 0; i < input.length; i++) {
  // console.log('i is ' + i);
  for (j = 0; j < vowels.length; j++) {
     // console.log('j is ' + j);
    if (input[i] === vowels[j]) // NO SEMI-COLON, BUT CORRECT OUTPUT
      resultArray.push(input[i]);
    }
  if (input[i] === 'e') {
    resultArray.push(input[i])
  };
  if (input[i] === 'u') {
    resultArray.push(input[i])
  };
}
  console.log(resultArray.join('').toUpperCase());

What’s the difference from above?

let input = 'turpentine and turtles';
const vowels = ['a', 'e', 'i', 'o', 'u'];
const resultArray = [];
for (i = 0; i < input.length; i++) {
  // console.log('i is ' + i);
  for (j = 0; j < vowels.length; j++) {
     // console.log('j is ' + j);
    if (input[i] === vowels[j]); // SEMI-COLON IS HERE
      resultArray.push(input[i]);
    }
  if (input[i] === 'e') {
    resultArray.push(input[i])
  };
  if (input[i] === 'u') {
    resultArray.push(input[i])
  };
}
  console.log(resultArray.join('').toUpperCase());

Thanks!

The semicolon in your second code segment ends the statement, so there is no code included in the if block. That means that resultArray.push(input[i]); will be executed for each iteration of the inner for loop.

Aside:
You’ve stumbled upon a bad practice. In you examples, you are missing the curly braces that should encompass the code for the if statement in question. You’ve also omitted the let in your for loops which in some environments will throw an error, and in others will give your iterator variable global scope. Your use of semicolons is also somewhat inconsistent which seems to have led to your original issue.

That part should arguably be formatted like this:

for (j = 0; j < vowels.length; j++) {
  if (input[i] === vowels[j])
    ;
  resultArray.push(input[i]);
}

Except, there’s no reason ever to write that.

And I think this is a good reason to always put braces around if’s body.
It should go without saying that indentation should match your braces as well, otherwise you’re better off not indenting at all, at least then you know you have to refer to the braces to figure out what belongs to what. Is that horrible? Yes it is, so the better option is to indent properly.

If you don’t know where semi-colons are supposed to go then you’re better off not using them at all. I leave them out if given the choice since they do not have an effect, they’re dead data, prune it.

Do this instead:

for (let j = 0; j < vowels.length; j++) {
  if (input[i] === vowels[j]) {
    resultArray.push(input[i])
  }
}

Oh and your i/j variables are global. Not so great.

1 Like