Easy Javascript Question - Looking for Answer

Hey everyone, fairly new to Javascript.

Can I please get an explanation why object property of displayMyList when accessed with dot notation logs as ‘undefined’ but when put in a function it works fine.

Here’s the code.



var toDoList = {
// Holding the List 
myList: ['List1', 'List2', 'List3', 'List4', 'List5'],
// Displaying the List
displayMyList: console.log(this.myList)
}


This will display it as ‘undefined’ when I try to access the object property displayMyList with dot notation. However when a method is used it displays the list fine. I am wondering why is that?



// Displaying the List

displayMyList: function(){

  console.log(this.myList)

}



In your first code snippet you are creating an object called toDoList with two keys in it (myList and displayMyList). You are setting those keys to values. JS will look at the value you set each to and evaluate it. For the myList key you have an array initialized with five items. There is nothing more to evaluate here, you provided a literal array. It’s the same thing as if you had put a number or string instead.

For the displayMyList value you didn’t use a literal value but rather put a function call in there, so JS will call the function and use the return value of the function as the value. console.log returns undefined and thus the value for displayMyList is set to undefined.

In your second code snippet now you are setting displayMyList to a value that is a function (remember, in JS, functions are first class objects, meaning they can be passed around just like any other data type). So there is nothing further to evaluate here, JS sets the value of displayMyList to a function and then you can call that function.

1 Like

Maybe I didn’t explain that to well. Its the same block of code for both. I just didn’t include the array and the full object in the second picture. I just showed the code in a function and how that works for me. I am just wondering why console.log doesn’t return the list. It just shows undefined. I am wondering why that is opposed to when passed through a function it does work. Sorry for poor explanation I’m just wondering why it is that way that I see undefined, when I think looking at displayMyList: console.log(this.myList) and I pass toDoList.displayMyList I would think it would than console.log the list.

You may also want to try and log out this inside the object.

var toDoList = {
  // Holding the List
  myList: ["List1", "List2", "List3", "List4", "List5"],
  // Displaying the List
  displayThis: this,
  displayMyList: function() {
    return this.myList;
  }
};

console.log(toDoList.displayThis)
console.log(toDoList.displayMyList())

https://javascript.info/task/object-property-this

1 Like