0

I have the following code:

var myObj = {apples:"five", pears:"two"};

function myFunction(x) {
    alert(myObj.x);
};

When I run myFunction(apples) I don't get an alert saying five, but I get an alert saying undefined.

How do I get the result I want by using the function parameter x with the object myObj

The result I want is it to say 'five' instead of 'undefined'.

1
  • Use brackets like so: myObj[x] Commented Oct 3, 2015 at 18:05

3 Answers 3

2

For getting a property with a string, you need to use brackets myObj["name"]

Look at this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

Correct code:

var myObj = {apples:"five", pears:"two"};

function myFunction(x) {
    alert(myObj[x]);
};
Sign up to request clarification or add additional context in comments.

Comments

2

Use [] notation:

var myObj = {apples:"five", pears:"two"};

function myFunction(x) {
    alert(myObj[x]);
};

myFunction('apples')

Comments

1

You have to pass the property name as a string. And within a function use bracket notation ([]) for access instead of using a dot (.).

var myObj = {apples:"five", pears:"two"};

function myFunction(x) {
    alert(myObj[x]);
};

myFunction("apples");

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.