Using parentheses to call a function

What the difference between calling a function like this

someFunction();
function someFunction() {
somecode;
}

and calling it without the parentheses like this?

someFunction;
function someFunction() {
somecode;
}

The second one doesn’t call the function, it just names it. In order to call (or invoke) a function, you need the parentheses. There may be times when you want to just name the function without calling it, most often when you’re passing that function as a parameter in another function - but you’ll get into that later.

So in a case like this

window.addEventListener(“load”, function() {
     document.getElementById(“someId”).onclick = someFunction;
}
function someFunction() {
     somecode;
}

the click event on that element is named the function?

It sets it to that function, without calling the function. The function is then called whenever that element is clicked.

Example:

function log42() {
  console.log(42);
}

document.body.onclick = log42;
// every time you click the `body` element, `42` is logged

document.body.onclick = log42();
// `42` is immediately logged...
// but when you click the `body` element, nothing happens,
// because the return value of `console.log` (`undefined`)
// is not a valid function.
1 Like

Thank you! I get it now. :grin:

I should also mention that setting <element>.onclick isn’t quite the same as simple assignment — setting it to something other than a valid function simply resets it to having no click handler. This is in contrast to something like the following:

const notAFunction = undefined;

notAFunction(); // throws Uncaught TypeError: notAFunction is not a function
1 Like

I would also further clarify, if we were to look inside the code inside that click handler, we might see something where that function gets invoked by putting the parentheses on it, using whatever name that code uses to that function you passed in.

Yeah, it’s kind of weird how functions get passed around like this. It’s also incredibly powerful.

1 Like