Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

124
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda