-4

I wrote.

let const = 10;

and got error.and for objects everything works

let x = {const:10}

What is the difference.

Edgar
  • 6,022
  • 8
  • 33
  • 66

2 Answers2

1

Variables can be used in the same places as you can use the const keyword. If you could use const as a variable name it would be hard to distinguish between the two.

That is not the case for property names; the syntax will always be clear that it refers to a property name.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

const is a reserved keyword you cannot use as variable name, so the first one is invalid syntax,

let const = 10

In second example you're using const as key which can be any string

let x = {const:10}

console.log(x)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • Property names in object literals can be strings or identifiers, and you're using an identifier there. Reserved keywords can be used as identifiers. – Quentin Aug 25 '19 at 10:03
  • @Quentin reserved keyword not as a variable name ( this is what i mean by my first line in answer), key is always strings in object literal isn't it ? – Code Maniac Aug 25 '19 at 10:08
  • Variable names are always identifiers. Identifiers are not always variable names. In an object literal (if we ignore computed property names) then the *syntax* is either a string literal or an identifier and the name resulting from that is a string). – Quentin Aug 25 '19 at 10:10
  • @Quentin yeah true, but does my answer contradict with the point your stating here ?? pardon if i missed something in answer, let me know happy to get things right and learn more :) – Code Maniac Aug 25 '19 at 10:16
  • You said you can't use `const` as an identifier, then you give an example (`let x = {const:10}`) where you use `const` as an identifier. – Quentin Aug 25 '19 at 10:17
  • @Quentin but there's a line before example, which says in `In second example` and only that line is meant for this example, first line refer to `let const = 10` – Code Maniac Aug 25 '19 at 10:18
  • 1
    That doesn't change the fact that the statement "const is a reserved keyword you cannot use as identifier" is wrong. You can (and you are!) use reserved keywords as identifiers. You just can't use them as variable names. – Quentin Aug 25 '19 at 10:20
  • @Quentin oh yeah makes sense, thanks for you valuable feedback :) – Code Maniac Aug 25 '19 at 10:23