skip to Main Content
for( var i = 0 ; i < 5 ; i++) {
  console.log("This is printing ${i} time") }

Is there any syntax error? because the output of this program is showing

This is printing ${i} time
This is printing ${i} time
This is printing ${i} time
This is printing ${i} time
This is printing ${i} time

I’m expecting something like

This is printing 1 time
This is printing 2 time
This is printing 3 time
This is printing 4 time
This is printing 5 time

4

Answers


  1. for(var i = 0 ; i < 5 ; i++) {
      console.log(`This is printing ${i} time`) 
    }
    

    When formatting variables inside strings in javascript, you need to use ` instead of " or ‘

    Login or Signup to reply.
  2. Use backticks

    for( var i = 0 ; i < 5 ; i++) {
      console.log(`This is printing ${i} time`) }
    
    Login or Signup to reply.
  3. To solve this use backticks instead of double quotes "".

    for (let i = 0; i < 5; i++) {
      console.log(`This is printing ${i} time`);
    }
    

    Avoid use of var as much as possible.
    For scoped code blocks use let instead of var.

    Login or Signup to reply.
  4. TL;DR: You need to use backticks (`) – not quotes – around the string.

    for(var i = 0 ; i < 5 ; i++) {
      console.log(`This is printing ${i} time`) // <- Note the backticks
    }
    

    What you are trying to use is called a template literal.

    According to MDN (emphasis mine):

    Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, string interpolation with embedded expressions, and special constructs called tagged templates.

    So, they have to be delimited with backticks. However, you are using plain double quotes.

    Regular quotes will only generate regular string literals, while backticks signal that you want the behavior and capabilities of template literals.

    As per MDN, they are sometimes called template strings, but they are capable of much more than just simple strong templating. Hence the name template literals.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search