5

Yesterday I started learning JavaScript. I am using the system Codecademy, but I'm stuck. When I say "stuck", I mean I have assignment with which I cannot see what is wrong.

The assignment is:

Create an array, myArray. Its first element should be a number, its second should be a boolean, its third should be a string, and its fourth should be...an object! You can add as many elements of any type as you like after these first four.

This is the code I made:

var myObj = {
    name: 'Hansen'
};

var myArray = [12,true, "Steen" ,myObj.name];

The error:

Oops, try again. Is the fourth element of myArray an object?

Hope you can help me.

1
  • @Kevin I rolled back your edit to the question because it completely changed the question and the answers no longer made sense. I see that it was a follow-up question to your original one. Stack Overflow works best if you keep to one problem per question. You can link to previous questions for context if needed. Commented Nov 23, 2012 at 18:58

3 Answers 3

4

The problem with your fourth element is you are passing a string because myObj.name is defined as Hansen. Pass the object instead:

var myArray = [12,true, "Steen" ,myObj];
Sign up to request clarification or add additional context in comments.

1 Comment

THanks! Should have asked before :)
1

I don't know that site, but you can do:

var myArray = [
    12,
    true,
    "Steen",
    {name: 'Hansen'}
];

What you are passing to the array is the value of the name property of your object instead of the object itself.

Comments

0

Your passing in the name property instead of the object for the fourth array parameter as you probably already know from the other anwers.

As your learning here are a few ways to do exactly the same thing as your accomplishing here.

Your way corrected:

var myObj = {
    name: 'Hansen'
};

var myArray = [12, true, "Steen", myObj];

Other ways:

// Method 1
var myArray = [12, true, "Steen", {name: 'Hansen'}];

// Method 2
var myObj = new Object();
myObj.name = "Hansen";
var myArray = new Array(12, true, "Steen", myObj);

// Method 3
var myObj = {};
myObj['name'] = 'Hansen'
var myArray = [
    12, true, 'Steen', myObj
]

Each method shows a few different ways to do the same thing, you can mix and match the equivalent parts of code to get the same job done. It's basically inter changing between the normal JavaScript syntax and object literal syntax.

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.