Alternating chars N times Write a function that returns a string length N of alternating strings: "A" and "B", starting with the 1st string. How could this be improved for be more performance or efficiency?

Eg: num = 5, should return "ABABA" &amp; given num = 2, should return "AB".



function solution(num) {
 const str1 = 'A', str2 = 'B';
 let res = [];

 for(let i = 1; res.length &lt; num; i++ ) { 
  res.push(i % 2 ? str1 : str2);
 }

  console.log(res.join(''))
}

solution(5) // return "ABABA"
A short code review;


Your code does not work, it should return something instead it calls console.log
Your for loop is icky, either update i and check i

for(let i = 0; i &lt; num; i++ )) 

or check res.length 

while(res.length &lt; num)
solution is too generic for this function name
console.log() is missing a semi-colon
Performance;


Checking whether i is odd every time seems like much, you can avoid that
RememberString.repeat(), you could repeat by calling "AB".repeat(num/2) and add an "A" if num is odd.



Obligatory rewrite

    //repeatAB(5) =&gt; "ABABA"
    function repeatAB(n) {
        return "AB".repeat(n/2) + (n%2 ? "A" : "");
    }

    console.log(repeatAB(5)) // returns "ABABA"


I ran this approach against the other approaches for the heck of it, this approach destroys the other approaches (at least visually):

http://jsbench.github.io/#11a2b8507a7f9290c6ef6cda596f8179