Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
For loop is stopping when rest of the block is added

I wrote a simple for loop, to understand charCodeAt() and fromCharCode() better and to solve the odin project the Caesar cipher exercise where you have to write function to encode a string.

It stops at the first iteration and I don´t know why. When I console log str.charCodeAt(i) it loops, but when I add the rest of the function it stops.

function uniCode(str, num) {
    for(let i = 0; i < str.length;i++) {
        //console.log(str.charCodeAt(i) + num);
        let charCode = str.charCodeAt(i) + num;
        let newStr = String.fromCharCode(charCode);
        return newStr;
    }        
        
}
uniCode("Help!", 3);
'K'

Glad for any help!

Thanks!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

with your code you loop through all characters of a given string in parameter

but you have return newStr; in the loop it will stop the loop iteration

function uniCode(str, num) {
    var newStr = "";
    for(let i = 0; i < str.length;i++) {
        console.log(str.charCodeAt(i) + num);
        let charCode = str.charCodeAt(i);
        newStr += String.fromCharCode(charCode);
    }        
    console.log(newStr);
    return newStr;
        
}
uniCode("Help!", 3);

about 4 years ago · Juan Pablo Isaza Relatório

0

It's stopping because you've told it to, by using return newStr;, which immediately terminates the function and returns newStr.

For what you're doing, you want to build up the new string and then return it at the end:

function uniCode(str, num) {
    let newStr = "";

    for (let i = 0; i < str.length; i++) {
        let charCode = str.charCodeAt(i) + num;
        let newChar = String.fromCharCode(charCode);
        newStr += newChar;
    }        
        
    return newStr;
}

Live Example:

function uniCode(str, num) {
    let newStr = "";

    for (let i = 0; i < str.length; i++) {
        let charCode = str.charCodeAt(i) + num;
        let newChar = String.fromCharCode(charCode);
        newStr += newChar;
    }        
        
    return newStr;
}

console.log(uniCode("Help!", 3)); // "Khos$"

Beware, though, that when you loop through a string like that, you're working in code units, not code points, which may make your results quite odd if there are code points requiring multiple code units to process. (See my blog post here if these terms are unfamiliar.) You might want to use for-of instead, since it works in code points:

function uniCode(str, num) {
    let newStr = "";

    for (const char of str) {
        const codePointValue = char.codePointAt(0) + num;
        const newChar = String.fromCodePoint(codePointValue);
        newStr += newChar;
    }        
        
    return newStr;
}

Live Example:

function uniCode(str, num) {
    let newStr = "";

    for (const char of str) {
        const codePointValue = char.codePointAt(0) + num;
        const newChar = String.fromCodePoint(codePointValue);
        newStr += newChar;
    }        
        
    return newStr;
}

function oldUniCode(str, num) {
    let newStr = "";

    for (let i = 0; i < str.length; i++) {
        let charCode = str.charCodeAt(i) + num;
        let newChar = String.fromCharCode(charCode);
        newStr += newChar;
    }        
        
    return newStr;
}

console.log("New: " + uniCode("Help!😀", 3));    // "New: Khos$😃"
console.log("Old: " + oldUniCode("Help!😀", 3)); // "Old: Khos$𠈃"

about 4 years ago · Juan Pablo Isaza Relatório

0

The problem here is the return statement at the end of the loop that causes the problem.

You can create a variable and append newStr to it and after the loop, return the string value

function uniCode(str, num) {
    let finalStr = ""
    for(let i = 0; i < str.length;i++) {
        let charCode = str.charCodeAt(i) + num;
        let newStr = String.fromCharCode(charCode);
        finalStr = finalStr + newStr;
    }        
 return finalStr       
}

uniCode("Help!", 3);
'Khos$'

You can make the code better by using reduce function like:

function uniCode(str, num) {
  return str
    .split('')
    .map(x=>x.charCodeAt(0))
    .reduce((total, curr) => (total + String.fromCharCode(curr + num)), "")
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda