Home > OS >  Js FOR loop returning 'undefined'
Js FOR loop returning 'undefined'

Time:11-16

Im trying to add asterisks at the beginning and end of each word but I keep getting undefined at the end of my new string. Thanks for the help in advance.

function solution(s) {
var asterisks = "*"
var newString = ""
for(let i = 0; i <= s.length; i  ){
    if(s === ""){
        return "*";
    }else{
    newString  = asterisks   s[i];} 
}
return newString;
}

CodePudding user response:

I think your for loop should be

for(let i = 0; i < s.length; i  )

Cause in the last time of your for loop, i = s.length.

And s[s.length] = undefined

CodePudding user response:

Your issue is for(let i = 0; i <= s.length; i ) the <= should just be < the undefined is coming from the last "length" character not existing.

You can get around adding the final * and the end of the last letter by add this code to the for loop:

if (i == (s.length -1)){
    return newString  = asterisks;
    }

Working example:

function solution(s) {
var asterisks = "*"
var newString = ""
for(let i = 0; i < s.length; i  ){
    if(s === ""){
        return "*";
    }else{
    newString  = asterisks   s[i];} 
    
    if (i == (s.length -1)){
    return newString  = asterisks;
    }
}
return newString;
}

document.getElementById("test").innerHTML = solution('hello');
<div id="test"></div>

  • Related