Write JavaScript Function


#1

Hi,

I'm learning JavaScript and I'm trying to understand objects. I'm learning from a site that doesn't really explain things well (or I'm just oblivious to the examples given) and need some help.

I need to edit this function such that it takes in an object as a parameter. Return the 'abc' property from that object.

function getABC() {}

any help would be greatly appreciated.Thanks.


#2

Hi @tml and welcome to the forums.

I think the following is what you're after:

function getABC(obj) {
	return obj.abc;
}
var myObject = {
	abc: 'someValue';
};
var abc = getABC(myObject);

Hope it helps,

Andres


#3

I will give that a shot. Thank you, @Andres_Vaquero


#4

That worked. Thank you for your help.

Another question @Andres_Vaquero... if I edit this function such that it takes in an object as a parameter.

Add a property to the object with a key 'abc' and a value of true.

Return the object.

How do I change this;

function addABC(obj) {
  return obj.abc;
}
var myObject = {
  key: 'abc',
  value: true
};
var abc = addABC(myObject);

to not return undefined, but return the object?


#5

I think you are not understanding the object notation syntax or what a "key" and "value" pair are.

Compare Andres' myObject with yours.


#6

Well you are taking this too literally here. :-) The "key" usually refers to the name of the object property, and "value" to the value that property holds. So what you are after is most probably this:

var myObject = { abc: true }

You can also add properties later on:

var myObject = {}

myObject.abc = true

You can read all you need to know in the article Working with objects over at the MDN.


#7

Way too literal :wink:

Thank you for the clarification.


closed #8

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.