3

I'm learning Javascript track in codecademy.com. And I'm confused about creating object by using "Object Literal Notation".

Here syntax1, in the hint section the syntax is:

var friends = {
    bill: {},
    steve: {}
};

We need those curly braces to contain keys' values within the object's curly brace.

BUT, in syntax2, the syntax is:

var myObject = {
    key: value,
    key: value,
    key: value
};

See, no need for curly braces container within the object's curly brace. As I did the exercise we only required to: direct input for numbers and functions, or within quotation for strings, or within square brackets for arrays.

Can someone kindly share their knowledge and time to tell me why we have the difference or which one is the correct syntax?

2
  • It's clearly stated: "Use your friends' names as the keys for the empty objects." Commented Jul 29, 2014 at 0:30
  • @all: Thanks guys, for all your fast respond. I need some time to understand and try'em. Commented Jul 29, 2014 at 0:41

3 Answers 3

3

The "Object Literal Notation" just means the following format:

var myObject = {
    key1: <value1>,
    key2: <value2>,
    // ...
    keyN: <valueN>
};

where <valueX> can be any JS value, like a boolean, a number, a string or even another Object (which is indicated by the same { key1: <value1> ... } syntax).

An empty object is just one that has no keys (properties) and thus looks like { } (space is optional).

Sign up to request clarification or add additional context in comments.

Comments

1

It depends on what will be the content of your variables:

synthax1:

var obj = {
    name: "Thiago",
    currentYear : 2014
};

synthax2:

    var obj = {
        name: "Thiago",
        skills: {
           key: "JS",
           value: 1
        }

};

you can initialize with [] and it will be an array.

2 Comments

In your haste, you made a syntax error with your "syntax1" example.
Is the error is equal sign in "currentYear = 2014", Greg ? Sorry, but i'm happy to know a bit here and there as my learning goes onward.
0

It depends what you want the values to be.

{} is an empty object; other literals are other values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.