Search code examples
javascriptfizzbuzz

FizzBuzz example in JavaScript


Working through some JS examples and I wrote this solution for a fizzbuzz question. It just prints 1..20 and str never gets the concat() value. Can someone please explain why this doesn't work?

for(i=1; i<=20; i++){
    var str = ''
    if(i%3===0){     
        str.concat('Fizz')
    }
    if(i%5===0){
        str.concat('Buzz')
    }
    if(str===''){
        console.log(i)
    } else {
        console.log(str)
    }
}

Update: Since the above question was a simple syntax error (don't want to start a new thread), was wondering if the following is good way to write the above answer succinctly in JS?

for(i=1; i<=20; i++){
    var str = ''
    i%3===0 ? str = str.concat('Fizz') : false
    i%5===0 ? str = str.concat('Buzz') : false
    str==='' ?  console.log(i) : console.log(str)
}

Solution

  • Because String.prototype.concat() returns contatenated string.

    You need to do str = str.concat("XYZ");