CodeWars "xMarksTheSpot" challenge

My code so far

function xMarksTheSpot(input){
  var result = [];
 for(let i = 0; i < input.length; i++){
 	for(let j = 0; j < input[i].length; j++){
        if (input[i][j] == 'x' &&  result == []) result = [i, j];
  return result;

// xMarksTheSpot(([['x', 'o'],['o', 'o']]) returns [], not [0, 0] as expected

For the first iteration of the nested for loop, isn’t result indeed equal to , therefore it should then be set to [0, 0]? When I remove the && result == [], it works as expected.

This doesn’t mean what you think it means. Reference types (objects, arrays, functions, etc.) are stored by reference (memory address). So that code is asking the question, “Is the memory address of the array result the same as the memory address of the empty array literal I created for this comparison?” That will never be true - the address of that empty array literal will never match the address of any other.

1 Like

I see. What about the address of the ‘x’ in input[i][j] == 'x'? Does this work as expected because ‘x’ is a string which is isn’t a reference type?

input is a reference because it is an array (of arrays). input[i] is a reference because if is an array (of strings). input[i][j] is a string. Strings are primitives so comparisons work as expected.

1 Like

Very clear. Thank you

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.