0

Code Academy says there are 2 ways to create objects in JavaScript.

1. object literal notation

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

2. object constructor approach

var myObject = new Object();

Keys can then be added thus:

myObj["name"] = "Charlie"; 
myObj.name = "Charlie"; //shorthand for the first

Being asked to create 3 objects, I tried different ways to produce the objects with the same values but I am getting an error using the template provided above. My code is pasted below:

var object1 = {
    1: 2,
    7: 3,
    4: 5
};

var object2 = new Object();
object2['1'] = 2;
object2['7'] = 3;
object2['4'] = 5;

var object3 = new Object();
object3.1 = 2;
object3.7 = 3;
object3.4 = 5;

Code Academy gave me an error and to figure out where exactly it was, I used Chrome's console. Tying each object creation separately on Chrome's console, object1 and object2 could be created but not object3 which produces the error: Uncaught SyntaxError: Unexpected number

Changing object3's code to (changing keys from numbers to strings):

var object3 = new Object();
object3.'1' = 2;
object3.'7' = 3;
object3.'4' = 5;

produces the error: Uncaught SyntaxError: Unexpected string

Is it possible to create object3 using this template/layout to produce values of object1 or can the key never be a number or string? A string but not a number for the key worked in creating object2.

1
  • 1
    A property name can't start with a number using 'dot' syntax. object3._1 will work, however because underscores (as well as $ and alphabetical characters) are legal syntax. Commented Feb 16, 2017 at 22:05

1 Answer 1

2

When using the dot notation, the keys should be named in the same way variables are (starts with a letter or _ and contains only letters, numbers and _).

If the key is not valid to be used as dot notation then it can be used using bracket notation like this:

obj["key goes here"];

Since 1, 7 and 4 are not valid for dot notation, the only way to use them as key is like this: obj["4"] ...

Here is an MDN page about the basics of objects.

Example:

These keys are valid for dot notation:

abc;
_a;
R2D2;
_;
_0;
a________a;

Thes are not:

k-ey;
a b a;
99;
k.e.y;
@@;
Sign up to request clarification or add additional context in comments.

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.