Help with global variables

function rot13 which should give me final outcome works only when invoked once. After for example invoking by console.log three times i get three times exact same output as in first invokation

let arr = [];
let output = [];
let incrementedBy13 = [];
let wynik = [];
const alphabet = (charA, charZ) => {

    let i = charA.charCodeAt()
    let j = charZ.charCodeAt()
    for(i; i <= j; i++) {
        arr.push(String.fromCharCode(i).toUpperCase())
    }
    return arr
}
alphabet("a", "z")
console.log(arr)

function rot13(str) {
  let ciphered = str.split("")
  ciphered.forEach((letter) => {
    if (arr.indexOf(letter) === -1) {
      output.push(letter)
    }
  output.push(arr.indexOf(letter))
  for (let i = 0; i < output.length; i++) {
    if (output[i] === -1) {
      output.splice(output[i], 1)
    }
  }
  })
  for (let j = 0; j < output.length; j++) {
  if (typeof output[j] === "number") {
    incrementedBy13.push(output[j] + 13)
  }
  if (typeof output[j] === "string") {
    incrementedBy13.push(output[j])
  }
}
  wynik.push(incrementedBy13.map((item) => {
    if (typeof item === "string") {
      return item
    }
    if (typeof item === "number" && item >= 26) {
      return arr[item - 26]
      }
    if (typeof item === "number" && item < 26) {
      return arr[item]
      }
  }
  ))
  
  return wynik[0].join(" ")
}

  console.log(rot13("SERR CVMMN!"));
  console.log(rot13("SERR PBQR PNZC!!"));
  console.log(rot13("SERR PBQR PNZC!!"));

I moved this into a separate topic so you don’t hyjack someone else’s topic.


Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2

Thank you Jeremy.
Function should have been placed inside local scope.

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