0

Problem with expected solutions can be found here : https://www.codewars.com/kata/58287977ef8d4451f90001a0/train/javascript

I have played around with console results and can see that whatever I set as my variable in the 2nd line of code let allSame = true; is what the end result returns. As I understand the for loop HAS to play out and so the IF statement then MUST play out - So one way or the other the variables should be updated. Maybe I have missed something out when it comes to global/local variables?

Please include an explanation with answer as I am trying to learn -- Thanks!


function isSameLanguage(list) {
  let allSame = true;
  for(let i = 0; i<list.length-2; i++)
    if(list[i]["language"] == list[i+1]["language"]){
      let allSame = true;      
    }else{
      let allSame = false;
    }
  return allSame;
  
  
}

DCoderT
  • 65
  • 8
  • 1
    Remove the `let`s on the lines within the if and else, and then go and read about the concept of "scope" as it relates to variables. – ADyson Dec 02 '21 at 11:28
  • Remove `let` from all except first declaration. Now you re-declare same var in different scopes – Justinas Dec 02 '21 at 11:28
  • `As I understand the for loop HAS to play out`...not necessarily. If there are 2 or fewer items in `list` then it won't run, according to your criteria. – ADyson Dec 02 '21 at 11:29
  • 2
    BTW your actual logic is wrong too...once you find a non-matching item you need to quit the loop, otherwise "allSame" might get reset to true on the next iteration. And I don't know why you're telling it not to process the whole list? Even in a larger list (i.e. 3 or more items) where the loop would actually be executed, it will stop two items before the end of the list. – ADyson Dec 02 '21 at 11:29

1 Answers1

0
function isSameLanguage(list) {
  var allSame = true;
  for(let i = 0; i<list.length-2; i++)
    if(list[i]["language"] == list[i+1]["language"]){
      allSame = true;      
    }else{
      allSame = false;
    }
  return allSame;
 
}

Global decclartion of allsame variable is required. if you create in between each if ladder is will become local scope.

Daniel Paul
  • 495
  • 1
  • 6
  • 13