Learn Basic JavaScript by Building a Role Playing Game - Step 37

This is the code:

let xp = 0;
let health = 100;
let gold = 50;
let currentWeaponIndex = 0;
let fighting;
let monsterHealth;
let inventory = ["stick"];

const button1 = document.querySelector('#button1');
const button2 = document.querySelector("#button2");
const button3 = document.querySelector("#button3");
const text = document.querySelector("#text");
const xpText = document.querySelector("#xpText");
const healthText = document.querySelector("#healthText");
const goldText = document.querySelector("#goldText");
const monsterStats = document.querySelector("#monsterStats");
const monsterName = document.querySelector("#monsterName");
const monsterHealthText = document.querySelector("#monsterHealth");

// initialize buttons
button1.onclick = goStore;

function goStore() {
  console.log("Going to store.");
}

function goCave() {
  console.log("Going to cave.");
}

function fightDragon() {
  console.log("Fighting dragon.");
}

What is the difference between calling the function and referencing it in this case?

button1.onclick = goStore;
button1.onclick = goStore();

Wouldn’t it basically do the same thing? Which is printing “Going to store.” when the button is clicked in the console…
I understand the general difference between calling a function and referencing it, but I don’t understand what difference would it make in this case…

Hi. That is the particular syntax to call a function when the button is clicked (ie to access the onclick property of the button element). Step 36 explains it. That is how the function is stored when doing this. It won’t work by adding brackets.

This stack overflow explains it javascript - What is the difference between a function call and function reference? - Stack Overflow

Adding the brackets there:
“immediately executes the function (because of the ()), and assigns its return value to onclick. Unless the return value is a function, this isn’t what you want.”

1 Like