Home > database >  How do I add numbers following a string in JavaScript
How do I add numbers following a string in JavaScript

Time:09-29

I want to console.log a string but also add numbers inside of it. For example if I use the following code:

for (let i = 0; i < 5; i  ) {
  coinFlip = Math.round(Math.random());
  if (coinFlip === 1) {
    console.log("#"   i   1   " Heads");
  } else {
    console.log("#"   i   1   " Tails");
  }
}

Since what I want to console.log starts with a string I can't seem to add numbers right after it. They become strings.

I want to get: "#2 Tails"

But I get: "#11 Tails"

How do I get "#2 Tails" instead of "#11 Tails"?

CodePudding user response:

You need to wrap your addition in brackets.

console.log("#"   (i   1)   " Heads");

or use string interpolation

console.log(`#${i 1} Heads`);

CodePudding user response:

Simply wrap the numbers you want to add with () which will first add the numbers and later will be concatenated with the string:

for(let i = 0; i < 5; i  ) {
  coinFlip = Math.round(Math.random());
  if ( coinFlip === 1 ) {
    console.log( "#"   (i   1)   " Heads" );
  }
  else {
    console.log( "#"   (i   1)   " Tails");
  }
}

CodePudding user response:

You can first sum up the value of i and 1 to num before the concatination

1)

for (let i = 0; i < 5; i  ) {
  coinFlip = Math.round(Math.random());
  const num = i   1;
  if (coinFlip === 1) {
    console.log("#"   num   " Heads");
  } else {
    console.log("#"   num   " Tails");
  }
}

2)

for (let i = 0; i < 5; i  ) {
  coinFlip = Math.round(Math.random());
  if (coinFlip === 1) {
    console.log("#"   (i   1)   " Heads");
  } else {
    console.log("#"   (i   1)   " Tails");
  }
}

3)

for (let i = 0; i < 5; i  ) {
  coinFlip = Math.round(Math.random());
  if (coinFlip === 1) {
    console.log(`#${i   1} Heads`);
  } else {
    console.log(`#${i   1} Tails`);
  }
}

  • Related