Harke
Harke

Reputation: 1289

Javascript .call function returning extra 'undefined' value

In the following snippet:

function Product(name, price) {
  this.name = name;
  this.price = price;
  this.show = function() {
      console.log(this.name);
      console.log(this.price * 10);
      };
}

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

function Toy(name, price) {
  Product.call(this, name, price);
  this.category = 'toy';
}

var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);

console.log(fun.show());

The console output I am getting is:

robot
400
undefined

Why is the third output coming as undefined and from where is it coming?

Upvotes: 2

Views: 185

Answers (2)

gekkedev
gekkedev

Reputation: 593

Use return instead of logging to the console multiple times.

function Product(name, price) {
  this.name = name;
  this.price = price;
  this.show = function() {
      return this.name + " " + String(this.price * 10)
  };
}

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

function Toy(name, price) {
  Product.call(this, name, price);
  this.category = 'toy';
}

var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);

console.log(fun.show());

Produces: robot 400 (toy name and price)

Upvotes: 1

Tanner
Tanner

Reputation: 2411

By default, JS functions return undefined.

Since your show function isn't explicitly returning anything, it returns undefined.

Upvotes: 3

Related Questions