Q: Concatenation of HTML string in javascript with ternary operator I am trying to concatenate a HTML string using + operator and I am using ternary operator to check the condition and use appropriate class name in the div element, however the ternary operator is giving me wrong output. I don't know what I am missing out here. Can anyone please explain?
My code looks like this :
            fetch("./data/projects.json")
                .then(res => {
                    return res.json();
                })
                .then(jsonResponse => {
                    var carouselItem = ''

                    jsonResponse.data.map((image, index) => {
                        carouselItem += '<div class="carousel-item ' + index === 0 ? 'a' : 'b' + '">'
                    })

                    console.log(carouselItem);
                })
                .catch(err => {
                    console.log(err);
                })

I get the following output when I run this code
b">b">b">b">b">

I expect the output should be 
<div class="carousel-item a"><div class="carousel-item b"><div class="carousel-item b"><div class="carousel-item b"><div class="carousel-item b">


A: + has higher operator precedence (14) than the conditional operator (4). Your current code is equivalent to
carouselItem += ('<div class=carousel-item>' + index === 0) ? 'a' : 'b'

Not only is the comparison wrong, so is the assignment. Change to:
carouselItem += '<div class="carousel-item ' + (index === 0 ? 'a' : 'b') + '"> </div>';

so that the conditional is grouped properly. You also probably want to end the <div you started. Also, .map should only be used when you want to create a new array. When you want side-effects only, use forEach.
jsonResponse.data.forEach((image, index) => {
  carouselItem += '<div class="carousel-item ' + (index === 0 ? 'a' : 'b') + '"> </div>';
});

You can use .map here if you wanted, but if so, return the <div> you want, then join it together:
const carouselItem = jsonResponse.data.map((image, index) => (
  '<div class="carousel-item ' + (index === 0 ? 'a' : 'b') + '"> </div>'
))
  .join('');


A: Enclose the ternary in parentheses to make it a separate statement and prevent + take precedence (see @CertainPerformance's answer), or use a template string:


const strA = "hello";
const strB = " world";
console.log(strA + 1 === 1 ? strB : "nope");
console.log(strA + (1 === 1 ? strB : "nope"));
console.log(`${strA}${1 === 1 ? strB : "nope"}`);



A: The problem is because its not able to parse correctly.
replace your 
carouselItem += '<div class=carousel-item>' + index === 0 ? 'a' : 'b'

with brackets like below
carouselItem += '<div class=carousel-item>' + ((index === 0) ? 'a' : 'b')

