Reggie
Reggie

Reputation: 15

How to access the value of a property of an object using a function in Javascript?

Just learning JS and I'm working through some tutorials. I've ran into a question that I have not been able to solve. The question is:

Write a function called getValue(). It should take two inputs: an object and a key. It should return the corresponding value for that key within the object. Keep in mind that this should be a one-line function.

I know you can access this with objectName.property but I haven't been able to figure out how to do this within a function.

Again, very new to JS. Any help would be greatly appreciated!

Upvotes: 1

Views: 176

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386604

Basically, you need a function with a name, which is

function getValue() {
}

Then you need the parameters, like object and key, which are written in the head of the function.

function getValue(object, key) {
}

After that, you need to return something. This stops the function as well.

function getValue(object, key) {
    return;
}

At last, you need the value from the object with a property accessor with bracket notation, it take the object and a variable, or a value for the key, like

object[key]

and together in the function, you get then

function getValue(object, key) {
    return object[key];
}

In the case, you supply a key, which is not in the object, you get undefined as result.

Upvotes: 5

Related Questions