Object property called with dot notation showing console.log 'undefined'

Viewed 205

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. Why does it show undefined with just the console log? Why doesn't it get displayed and why does it need a function to do so.

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?

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

First of all, check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this


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

There are a couple problems here with your first example above.

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

This fixes those, you are:

  • Assigning displayMyList to be a FUNCTION that you will run later in the context of toDoList being this.

Note how the use of function keyword here rebinds this to the containing object.

// Won't work
const x = toDoList.displayMyList;
x();

// Won't work
toDoList.displayMyList.call(globalThis);

// Won't work
toDoList.displayMyList.apply({});

You'll want to use an object method to log your list

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


toDoList.displayMyList()

Related