What is the right time to use parentheses when calling functions - and when should you leave them

Currently, I am following along with a tutorial at this link and I've come across some syntax that is confusing to me.

The goal is to have "hello" logged to the console every time I scroll.

function moveCamera() {
  console.log("hello");
}

document.body.onscroll = moveCamera()
function moveCamera() {
  console.log("hello");
}

document.body.onscroll = moveCamera

In the first scenario, "hello" is logged once but does not repeat with further scrolling.

On the other hand, in the second scenario, "hello" is logged every time there is a scroll event.

I realize that in the second scenario, moveCamera is passing a copy of the function, essentially creating a function that looks like this:

document.body.onscroll = function () {
  console.log("Hello");
}

Yet, I'm still puzzled as to why calling moveCamera() with parentheses does not function as expected and produces unwanted results.

UPDATE: I've come up with a simple way to distinguish when to use parentheses and when not to. I'm sharing it here even though my question was marked as a duplicate.

Examples Without Parentheses

// Example 1: Use reference when assigning
document.body.onscroll = moveCamera;
// Example 2: Use reference when event listening
document.body.addEventListener("scroll", moveCamera);

Examples With Parentheses

// Example 1: Use call when executing on a single line alone
...
moveCamera()
...
// Example 2: Use in a loop or an animate() function for repeated calls
// Note: This example is specific to THREE.js
function animate() {
  requestAnimationFrame(animate);
  moveCamera()
  renderer.render(scene, camera);
}

Answer №1

It is recommended to pass a string with the function, not the function itself, as it will return whatever the function returns. Utilizing the setAttribute() function is also advisable:

document.body.setAttribute("onscroll", "moveCamera()");

  • If you have the following function and use moveCamera() without quotation marks:

function moveCamera() {
  return "console.log('Hello')";
}

document.body.setAttribute("onscroll", moveCamera());
body {
  height: 200vh;
}
<body></body>

  • When using moveCamera() with quotation marks as a string:

function moveCamera() {
  console.log("Hello");
}

document.body.setAttribute("onscroll", "moveCamera()");
body {
  height: 200vh;
}
<body></body>

Answer №2

When you use the moveCamera function, you are actually setting a variable to the result of the function, not the function itself.

This concept is exemplified in the code snippet below:

function exampleFunction(){
  return "example value";
}
var x = exampleFunction;
var y = x();

console.log("x = "+x);
console.log("y = "+y);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering the functionality of detecting the pressing of the "enter" key within an input field that triggers the next button in Internet Explorer versions 8 through 10

My current challenge involves detecting Internet Explorer's behavior when the Enter key is pressed in an input box with a button element beside it, especially when they are not enclosed within a form element. This unique feature of IE is intriguing b ...

What is the best method for calculating the total of a mongoose attribute?

I am attempting to calculate the sum of schema using reduce. However, the current code is not adding the items together but rather placing them next to each other. For example, 20 + 30 should result in 50, but instead it gives me 02030. Is there an issue w ...

Transform a dynamic web page into a static one using Next.js

Utilizing Next.js and React.js, I create dynamic web pages. Specifically, I generate user-related web pages that need to be updated when there are changes in the user data. How can I generate static HTML pages from this updated data within Next.js? Are the ...

A guide on accessing objects from an array in Vue.js

Wondering how to choose an object from an array in Vue.js: When the page loads, the selectTitle() function is triggered. I simply want to select a specific object (for example, i=2) from my 'titleList' array. However, at the moment, I am only re ...

Error: The 'filename' property of undefined cannot be read when attempting to upload a user profile photo using multer

I am facing an issue while attempting to upload a user profile photo using express.js server and Multer. I keep receiving the error message "TypeError: Cannot read property 'filename' of undefined." Below is the code snippets for both the server- ...

What is the best way to preserve an apostrophe within a variable in JavaScript without it being replaced?

How can I send the value of NewText in its original form from .cs code using an ajax call? **var NewText ="D'souza";** $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: " ...

Safari experiences occasional failures with pre-signed post uploads to S3 when using multipart/form-data for file uploads

Lately, I've encountered issues with pre-signed post uploads to S3 that seem to be unique to Mobile Safari browsers. Interestingly, the error has also shown up occasionally on Desktop Safari. Whenever this error occurs, it triggers a response from S3 ...

Is there a way to adjust the text color based on whether a value is negative?

I am currently developing a web application that performs addition operations on integers. Within this application, I have implemented two functions named num1() and num2() to retrieve the integers provided by the user for calculation. My objective is to m ...

Reverse playback of fragment shader

I stumbled upon an interesting fragment shader on shadertoy.com and now I want to integrate it into my project using three.js. However, my main challenge lies in controlling the "time" aspect of the shader. I aim to be able to play the shader, reverse its ...

Why does my event dispatch only run once upon form submission in Svelte JS?

My code successfully fetches data and puts it in a card when new data is added to the input. However, the issue arises when more than one data entry is made - although the data gets added to the database, it does not reflect in the data list. Can anyone he ...

Using ReactJS and JavaScript to transform an array into a fresh array

I am working with an array that looks like this: var oldArray = [ {number: '12345', alphabet: 'abcde'}, {number: '54321', alphabet: 'abcde'}, {number: '67891', alphabet: 'abcde'}, ...

Troubleshooting a Blank Screen Issue when Deploying React and Ruby on Rails on Heroku

My Heroku test environment features a Ruby on Rails backend and React frontend combination. After pushing out some changes, the test environment is now displaying either a blank screen with a JavaScript error message or another error related to certain p ...

The error message "TypeError: usert.addItem is not a function" indicates that

Currently in the process of developing a discord bot using discord.js, sequelize, and sqlite for database management. Encountering an issue with a custom function that is not being recognized as defined by the terminal, despite me confirming its definition ...

Setting a cookie within an Angular interceptor

My angular interceptor function includes a request object. intercept(req: HttpRequest<any>, next: HttpHandler) { return next.handle(req); } I am looking to set my token in the request cookie under the name my-token. How can I achieve this? I ...

Where to Locate a String Excluding <a> Tags?

I'm in the process of writing a JavaScript code that will scan an HTML document and identify all occurrences of a specific keyword that are NOT contained within a link, meaning not under an <a> tag. To illustrate this, let's examine the fol ...

The HTML5 camera feature remains active even after navigating to a different page in an AngularJS application

I am currently exploring the video capabilities of HTML5. Using a directive userMedia, I have successfully activated my camera on my MacBook through navigator.getUserMedia() (using an adapter for cross-browser compatibility with supported browsers). Howev ...

Material UI select field box not displaying the chosen option

After implementing a select component with Mui, I encountered an issue where although the selected option gets stored correctly in the defined state, it does not display within the select box itself. Below is the JSON object used: const DataExample = [ { ...

Tips for properly invoking an asynchronous function on every rerender of a component in Vue.js

Situation: An analysis module on a website that needs to display three different data tables, one at a time. Approach: The module is a component containing three buttons. Each button sets a variable which determines which table to render. Depending on the ...

The process of authenticating route parameters in Nuxt

I'm having trouble validating route parameters in my page component using the following code: async validate({ params, store }) { await store.dispatch(types.VALIDATE_PARAMS_ASYNC, params.id) } And here's the corresponding code in the store: ...

Is it possible to determine if child_process has finished in node.js?

I'm currently in the process of developing a cakefile with node.js and I need to determine whether a child_process has completed before proceeding to the next one. {exec} = require 'child_process' exec 'casperjs test.js', (err, s ...