user1607991
user1607991

Reputation: 29

function variable undefined

Why does the top version not work and the lower function works? Learning about how to create and use objects and this baffles me. I assume it has to do with the fact I am using an object in the top part?

var slot1 = {
  coffee: '1',
  tea: '2',
  espresso: '3'
}

function findItem( obj, prop ){
  var item = obj + '.' + prop;
  console.log(item);
}
findItem( slot1, coffee );


function addNumbs(num1,num2){
	var answer = num1+num2;
  console.log(answer);
}
addNumbs(4,3);

Right when I think I am getting the hang of it I get completely slapped in the face!

Upvotes: 0

Views: 94

Answers (4)

brk
brk

Reputation: 50346

The upper version does not work because of these two lines

var item = obj + '.' + prop; & findItem( slot1, coffee );

When retrieving an object a.b or a['b'] is enough where a is the object and b is key

Doing a +'.'+b will result in concatenation ,instead of retrieving the value.

In function pass coffee as string otherwise it will pass as undefined value because it will presume coffee is declared somewhere which is not

Make this change

var slot1 = {
  coffee: '1',
  tea: '2',
  espresso: '3'
}

function findItem( obj, prop ){
  var item = obj[prop];
  document.write('<pre>'+item+'</pre>')
}
findItem( slot1,'coffee' );

DEMO

Upvotes: 2

shramee
shramee

Reputation: 5099

When you have property name in a variable use object like an array myObject[property] where property is a variable which contains a name of property of object you wanna get the value of.

Also, coffee is not to be used as variable but a string "coffee" or 'coffee'

var slot1 = {
  coffee: '1',
  tea: '2',
  espresso: '3'
}

function findItem( obj, prop ){
  var item = obj[prop]; // You need to access object property as if object was an array when you have property name in variable.
  console.log(item);
}
findItem( slot1, 'coffee' ); // You need coffee as a string here, variable coffee was never defined


function addNumbs(num1,num2){
	var answer = num1+num2;
  console.log(answer);
}
addNumbs(4,3);

Upvotes: 1

DJAy
DJAy

Reputation: 330

Try to use slot1.coffee instead of coffee

findItem( slot1, slot1.coffee );

Upvotes: 1

irimawi
irimawi

Reputation: 368

The problem is that coffee is not defined in any scope as a variable, you can use the notation of obj['coffee'] passing coffee as a string in order for this to work. Or you can call it as slot1.coffee in order for you to get to it.

Upvotes: 2

Related Questions