Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between assigning a variable value with functionName() and just functionName?

const heightOutput = document.querySelector('#height');
const widthOutput = document.querySelector('#width');

function reportWindowSize() {
  heightOutput.textContent = window.innerHeight;
  widthOutput.textContent = window.innerWidth;
}

window.onresize = reportWindowSize;

why not window.onresize = reportWindowSize() ? it's function call, I want to trigger it. but when I add the () it's not working.

like image 791
Shachar Avatar asked Jun 27 '20 12:06

Shachar


People also ask

What is the difference between a function and a variable in JavaScript?

A variable is something, which stores data. A function is a bunch of code, which can be executed, if you call.

What is the difference between function declaration and function expression?

The main difference between a function expression and a function declaration is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as an IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined.

What is the difference between LET and VAR?

let is block-scoped. var is function scoped. let does not allow to redeclare variables. var allows to redeclare variables.

How do you assign a function to a variable?

Method 1: Assign Function Object to New Variable Name A simple way to accomplish the task is to create a new variable name g and assign the function object f to the new variable with the statement f = g.


Video Answer


1 Answers

When you have the statement as reportWindowSize(), what this does is it invokes the function reportWindowSize. After the invocation, it returns some value which in this case is undefined. So, window.onresize will be assigned value undefined.

Now, let's talk about window.onresize. It is an event handler that gets triggered when certain events occur, in this case when window size is changed. More on events: Events API.

What this means is, when a window is resized some native code will call the handler window.onresize like this window.onresize(). If it is undefined then it won't work. It must be a function, so we either pass a reference of a function to it, which is exactly what you are doing or pass function value. Passing reference won't call the function but instead point it to the function you are passing. And finally, when the event is triggered the function reportWindowSize gets called.

Some resources that might be helpful:

  • Functions in javascript
  • First-class Function
like image 167
Subesh Bhandari Avatar answered Oct 31 '22 08:10

Subesh Bhandari