mr-woot
mr-woot

Reputation: 88

undefined gets outputted instead of object properties

Why the undefined gets outputted instead of the object properties.

Created a function, defined setters for the parameters and function to output the string consisting of the parameters.

Below is the snippet for the app.js file.

// app.js

function Fruit(theColor, sweetness, theName, theOrigin) {
	
	//properties
	this.theColor 	= theColor;
	this.sweetness 	= sweetness;
	this.theName 	= theName;
	this.theOrigin 	= theOrigin;
	
	//functions
	this.showName = function () {
		console.log("This is a " + this.theName);
	};

	this.showLand = function () {
		this.theOrigin.forEach(function (arg) {
			console.log("Grown in: " + arg);
		});
	};
}

var mango = new Fruit("Yellow", 9, "Mango", ["India", "Central America"]);

console.log(mango.showName() + " " + mango.showLand());

Upvotes: 1

Views: 68

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

This line:

console.log(mango.showName() + " " + mango.showLand());

calls those functions, then outputs their return values with a space between them. Neither showNames nor showLand returns anything, and so calling them gives you the result undefined.

If you just want to call those, just call them, without using console.log to output their result. E.g., replace:

console.log(mango.showName() + " " + mango.showLand());

with

mango.showName();
mango.showLand();

If you want them to return, rather than display, their result, edit them to do so. You'll have to decide how you want showLand to separate lines (e.g., with a \n, or by returning an array, etc.).

For instance, this showName will return a string, and showLand will return an array:

//functions
this.showName = function () {
    return "This is a " + this.theName;
};

this.showLand = function () {
    return this.theOrigin.map(function (arg) {
        return "Grown in: " + arg;
    });
};

which you could then call like this:

console.log(mango.showName() + ". " + mango.showLand().join(", "));

Live Example:

function Fruit(theColor, sweetness, theName, theOrigin) {

    //properties
    this.theColor   = theColor;
    this.sweetness  = sweetness;
    this.theName    = theName;
    this.theOrigin  = theOrigin;

    //functions
    this.showName = function () {
        return "This is a " + this.theName;
    };

    this.showLand = function () {
        return this.theOrigin.map(function (arg) {
            return "Grown in: " + arg;
        });
    };
}

var mango = new Fruit("Yellow", 9, "Mango", ["India", "Central America"]);

console.log(mango.showName() + ". " + mango.showLand().join(", "));

Upvotes: 6

Related Questions