Understanding Order

If I have an array. Will doing this for-loop get my end result which is ‘yo’?

var list = ['words', 'three', 'yo', 'up']

function tieBreaker(array) {
  var first = '';
  for(var i = 0; i < list.length; i++) {
    if(list[i].length <= first.length) {
      first = list[i];
    } else if(list[i].length === list[i].length) {
     first = list[0];
    }
  return first;
  }
}

Response to your question, I did try to execute the code and when it comes to ‘yo’ and ‘up’, the code returns back ‘up’ when in fact that ‘yo’ should be the correct response.

Your code is a mess.

  1. You use return in for loop - which means it will stop during first iteration.
  2. You use array parameter in your function, but never use it within function.
  3. Code list[i].length === list[i].length will always return true.

Try to rewrite your function in that way:

  1. It compares every item in an array with variable first.
  2. First should have assigned initial value already - try first index.
  3. When item from current iteration is smaller that first, reassign current item to first else do nothing.
  4. After for…loop return first.
1 Like

Thank @wawraf for setting me straight. I really appreciate it