0

I am trying to run the following code:

function LCS(s1, s2) {
  let m = s1.length;
  let n = s2.length;

  let table = [];
  for (let i = 0; i <= m; i++) {
    table.push([]);
    for (let j = 0; j <= n; j++) {
      if (i === 0 || j === 0) {
        table[i][j] = 0;
      } else if (s1[i - 1] === s2[j - 1]) {
        // Both s1 and s2 have the same element on the previous index
        // so increase the length of common subsequence by 1 here
        table[i][j] = table[i - 1][j - 1] + 1;
      } else {
        table[i][j] = max(table[i - 1][j], table[i][j - 1]);
      }
    }
    // We've found the length here.
    let index = table[m][n];
    console.log(`The length of LCS between "${s1}" and "${s2}" is ${index}`);

    // Now to get the sequence we need to backtrack from the m, n th index back to start.
    let i = m;
    let j = n;
    let commonSubSeq = "";
    while (i > 0 && j > 0) {
      // If current character in both strings is same, then it is part of LCS.
      if (s1[i - 1] === s2[j - 1]) {
        commonSubSeq += s1[i - 1];
        i--;
        j--;
      } else if (table[i - 1][j] > table[i][j - 1]) {
        i--;
      } else {
        j--;
      }
    }
    return commonSubSeq
      .split("")
      .reverse()
      .join("");
  }
}

console.log(LCS("AGGTAB", "GXTXAYB"));

I'm getting the following error:

      if (i === 0 || j === 0) {
      ^

ReferenceError: i is not defined
    at LCS (C:\Users\LCS-new.js:9:7)

I'm not able to understand why would this variable not be available in the nested scope?

ayushgp
  • 4,891
  • 8
  • 40
  • 75

1 Answers1

1

This answer "this happens because of hoisting" is incomplete. The reason why i throws a ReferenceError happens because of hoisting**. The reason why JS doesn't look in your loop's header (where i has been declared and assigned to 0) is that because there are two different scopes. The first in your loop header, the second in your loop's body (between the brackets {}).

** let i = m; will declare the variable i at the top of the for loop. Because of "hoisting" of let and const is different from the hoisting used with all the other types of declarations, i will be declared be not assigned.`

Unlike var that gets assigned to undefined when declared, let variables remain unassigned.

leonardofed
  • 936
  • 2
  • 9
  • 24