-1

What is the difference between parameter with quotation and parameter without quotation in Template literals in JavaScript

Why when I put quotation >> ('${key}') it does the function >> fun('${key}') while when I delete quotation >> (${key}) it doesn't do the function >> fun(${key}) what different between parameter with quotation and parameter without quotation in Template literals with JavaScript

for ( let key in states) { 
console.log(key);
var n =states[key].name;
var cur = states[key].currency;
console.log()

con.innerHTML += `<div> <span>name : "  ${n}
     " </span> <br> <span>cur : "  ${cur}
     " </span> </div><br> <span>cur : "  ${key}
     " </span>  <button onclick= fun('${key}')> select </button><hr> `
}

function fun(o) { 
alert(states[o].name);
alert(states[o].currency);
}

the code above run the function >> fun('${key}')

for (let key in states) {
  console.log(key);
  var n = states[key].name;
  var cur = states[key].currency;
  console.log()

  con.innerHTML += `<div> <span>name : "  ${n}
         " </span> <br> <span>cur : "  ${cur}
         " </span> </div><br> <span>cur : "  ${key}
         " </span>  <button onclick= fun(${key})> select </button><hr> `
}

function fun(o) {
  alert(states[o].name);
  alert(states[o].currency);
}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
memo_o
  • 37
  • 1
  • 3
  • 1
    If you look at the generated code, it will be `fun('foo')` vs `fun(foo)`. `'foo'` is a string literal, `foo` is a variable reference. – Felix Kling Mar 01 '22 at 20:01
  • Notice that your code doesn't work when `key` contains an apostrophe `'` or angle bracket `>`. Do not construct code as a string - neither with plain concatenation nor with template literals - but instead [use the DOM to attach a function as an event handler](https://stackoverflow.com/q/6941483/1048572) – Bergi Mar 01 '22 at 20:22

1 Answers1

1

It just adds ' in the final string.

The reason why this works in your example, but when you omit them it doesn't is because you are using that to generate js code inside an HTML handler.

Your keys are strings, so in js they need to be enclosed in either ' or ". When you omit them they are treated as variables and most likely you don't have variables (or constants) with that name(s).

Radu Diță
  • 13,476
  • 2
  • 30
  • 34