Does a function have to be declared or can it be implied!?

Hi all, I’m working though JS Novice to Ninja 2nd edition, and I’ve come across code on pages 254 and 255 that really puzzle me. For some reason, there’s no function declarations. I would expect this or a function expression, but they don’t seem to be declared at all. No function keyword to be seen! The code still seems to work, but I can’t remember coming across this before. This is an example where the render helper function isn’t declared:

// View Object
const view = {
  score: document.querySelector('#score strong'),
  question: document.getElementById('question'),
  result: document.getElementById('result'),
  info: document.getElementById('info'),
  render(target,content,attributes) {
    for(const key in attributes) {
    target.setAttribute(key, attributes[key]);
    }
    target.innerHTML = content;
  }
};

Anybody got ideas on why this is? The entire code (to this point in the book) is below to give context:

const quiz = [
              { name: "Superman",realName: "Clark Kent" },
              { name: "Wonderwoman",realName: "Dianna Prince" },
              { name: "Batman",realName: "Bruce Wayne" },
            ];

const game = {
  start(quiz){
    this.questions = [...quiz];
    this.score = 0;
    // main game loop
    for(const question of this.questions){
      this.question = question;
      this.ask();
    }
    // end of main game loop
    this.gameOver();
  },
  ask(){
    const question = `What is ${this.question.name}'s real name?`;
    const response =  prompt(question);
    this.check(response);
  },
  check(response){
    const answer = this.question.realName;
    if(response === answer){
      alert('Correct!');
      this.score++;
    } else {
      alert(`Wrong! The correct answer was ${answer}`);
    }
  },
  gameOver(){
    alert(`Game Over, you scored ${this.score} point${this.score !== 1 ? 's' : ''}`);
  }
}

game.start(quiz);

Page 168 in the Object Literals section gives an example that uses a fly method, without using the word function, and says:

I find it to be a tricksy notation though. You can read up more about them at Method definitions

2 Likes

Tricksy Hobbit! Giving the newbie a run for his money. :smile: I thought that must be the case. I suspected it had to do with using methods, but didn’t think to search for method related answers… When I searched for ‘declare functions without the keyword’ I got nothing. That saves me a lot of frustration. Thanks Paul!

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.