1

I'm learning about objects and constructors so created an object for a book.

It works fine after some tests with one element (book OR author OR pages OR read) but when I add more than 1 it only returns the final value.

For example, the below is only returning "nope" when I want it to return the title, author, pages, read (as I thought my function "bookInfo" declares?

What am I missing here as I've checked my code against some examples and can't see any issues?

function Book(title, author, pages, read) {
    this.title = title
    this.author = author
    this.pages = pages
    this.read = read
    this.bookInfo = function() {
        return (title, author, pages, read)
    }

}

const LOTR = new Book('lord of the rings', 'JRR', '366', 'nope');

console.log(LOTR.bookInfo());

// should print 'lord of the rings', 'JRR', '366', 'nope') but only returns 'nope' (or whatever the last value is?)
2
  • 1
    (title, author, pages, read) isn’t a tuple, it’s the comma operator in parentheses. Did you mean [title, author, pages, read]? Commented Nov 24, 2021 at 20:54
  • 2
    @Ry- Note that uses the direct passed parameters, it wont work properly if any of them are changed past the constructor. Commented Nov 24, 2021 at 20:57

1 Answer 1

4

You can return the assigned values in an array:

this.bookInfo = function() { 
  return [this.title, this.author, this.pages, this.read]; 
}

or object:

this.bookInfo = function() { 
  return {title:this.title, author:this.author, pages:this.pages, read:this.read}; 
}

or string:

this.bookInfo = function() { 
  return `${this.title} ${this.author} ${this.pages} ${this.read}`; 
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.