TypeError: Cannot read property 'Mike' of undefined

Hi everybody, why my code have typeError? I could not understand. Thanks for helping

function Dictionary(){
	this.add = add;
	this.datastore = new Array();
	this.find = find;
	this.remove = remove;
	this.showAll = showAll;

function add(key, value){
	this.datastore[key] = value;

function find(key){
	return this.datastore[key];

function remove(key){
	delete this.datastore[key];

function showAll() {
    Object.keys(this.datastore).forEach( function(key, index) {
       console.log(key + "->" + this.datastore[key]);

var pbook = new Dictionary();
pbook.add("Mike", "123");
pbook.add("David", "345");
pbook.add("Cynhia", "456");
console.log("David's extension: " + pbook.find("David"));

Your datastore is an array, wrong data structure.

1 Like

In the line above, this does not correspond to the Dictionary function. Inside the forEach, this refers to Object.keys(this.datastore) which is an array of keys.

You could assign this.datastore to a temp variable and refer to it inside your forEach callback function.

function showAll() {
    var datastore = this.datastore;
    Object.keys(this.datastore).forEach( function(key, index) {
       console.log(key + "->" + datastore[key]);

Thanks so much ! thankful for answer :slight_smile: