0
<!DOCTYPE html>
<html>
    <body>

        <p>Creating a JavaScript Object.</p>

        <p id="demo"></p>

        <script>
            var person = {
                firstName : "John",
                "lastName"  : "Doe",
                age       : 50,
                "eyeColor"  : "blue"
            };

            document.getElementById("demo").innerHTML =
                person.firstName + " " + person.lastName + " is " + person.age + " years old.";
        </script>
    </body>
</html>

result is ---> John Doe is 50 years old. here whether the property firstName,"lastName" is enclosed in quotes or not the code still works.but what is the technical difference and in which cases it won't work for example in JSON the person object's firstName property is invalid json syntax unless the quotes are present. but javascript allows either syntax to work

JoriO
  • 1,050
  • 6
  • 13
  • In JSON the the quotes are required. In js object literals, they're not. Don't quote property names in js unless you have a reason. – Ilia Choly Oct 30 '14 at 04:46
  • 1
    JSON is a subset of js and is much stricter. This just means in JSON is stricter and requires property names to be quotes. Inline js notation is looser and does not require the quotes. This being said, any json should be generated using serializer. – Martin Oct 30 '14 at 04:52
  • serializing methods using stringify is not possible though – prognovice Oct 30 '14 at 05:05

1 Answers1

0

Javascript object may have key names enclosed in quotes or without quotes. This feature has more significance when the key name contains a special character like -, white space etc.

Foe example

var person = {
   first Name : "John", // Will not work
  "last Name"  : "Doe", // Will work
  age       : 50,
  "eyeColor"  : "blue"
};
Gilsha
  • 14,431
  • 3
  • 32
  • 47