1

I have a really rookie question....

If I define a JS object, and I use a function to generate a property value, why does the property value return a function instead of the generated value?

Example:

var object = {
  bla: 1,
  days: [],
  test : function(){
    return 'bla';
  }
}

console.log(object.test);

I would expect object.test to be 'bla'. Instead it's function(){ return 'bla'; }... Why?

2 Answers 2

6

you have to execute that function, in this way: console.log(object.test());
or, as pointed out by @YuriiKovalenko, you can write the function like this:

var object = {
  bla: 1,
  days: [],
  test : (function(){ return 'bla'; })()
}

and then console.log(object.test); will give you "bla"

Sign up to request clarification or add additional context in comments.

3 Comments

Ok, great. And how can I rewrite it so that object.test will become 'bla'? Like, is it possible to automatically execute the function when looking up the value?
if you want that, you could simply write: object.test = "bla", so when you access it like object.test it will return its value ("bla")
@Henk , (function(){ return 'bla'; })()
1

Cause you set the value of object.test as a function in

var object = {
  bla: 1,
  days: [],
  test : function(){
    return 'bla';
  }
}

if you want to do so you have to get the value you have to execute object.test()

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.