Template literals - the $ sign

Hi, please could someone explain to me what these two together do?

${property}: ${object[property]}
const object = { a: 1, b: 2, c: 3 };

for (const property in object) {
  console.log(`**${property}: ${object[property]}**`);

// expected output:
// "a: 1"
// "b: 2"
// "c: 3"

what you put inside ${ and } is evaluated before the string is built, it is the syntax choosen for the template literals, so you can put a variable or whatever in that, it makes things more clear instead of using string concatenation

making a string without template literals it would have been property + " " + object[property]

1 Like

Ok. What the square brackets are for? object[property]

that’s to get the property, nothing unusual

1 Like

To expand on the object[property]}, does this make it clearer what is happening?

for (const property in object) {
  const value = object[property];
  console.log(`**${property}: ${value}**`);
1 Like

(in your example) It’s accessing objects property value (string or number) inside of for...in statement? (ES6).

Right, as ilena was saying, there is nothing magical here, this is just bracket notation.

On the first iteration, we want to access object.a, But we don’t have “a”, that is stored in the variable property. We can’t do object.property because that would be undefined. Instead we use bracket notation like object[property]. Since (on the first iteration at least) the value “a” is stored in the variable property, this is the same as object[“a”] which is functionally equivalent to object.a. We generally use dot notation instead of bracket notation unless the property name is stored in a variable (as in this case) or if the property name is not a valid JS identifier (like if it has a space or a “-” in it).

Check out this and this.

1 Like

Thank you for letting me understand this easier. After reading back and forth on here, links and MDN I finally sorted it out. Don’t know why but when i went thru those copuple days ago it was much simpler to understnd. Again i want to thank you both !

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.