James
James

Reputation: 1485

How does a variable declaration work as a function?

the following script uses a Greensock utility to map values and the script is set within a resize function. In the function I don't understand how getPercent is used as if it was called as a function bu it is declared as a variable

const maxRot = 10;
const setRot = gsap.quickSetter("h1", "rotationY", "deg");

gsap.set("h1", {transformOrigin: "center center"});

let getPercent;
function resize() {
  getPercent = gsap.utils.mapRange(0, innerWidth, -1, 1);
}

window.addEventListener("mousemove", e => {
  const percent = getPercent(e.pageX);
  setRot(percent * maxRot);
});

window.addEventListener("resize", resize);
resize();


But the syntax of getPercent seems to be written as a variable

getPercent= gsap.utils.mapRange(0,innerWidth, -1, 1)

but then its called as a function

const percent= getPercent(e.pageX)

I don't understand why getPercent is not written as for example

function getPercent(value){
return gsap.util.mapRange(0,innerWidth,-1,1,value)
}

I hope this makes sense

Upvotes: 1

Views: 54

Answers (1)

Rahul
Rahul

Reputation: 2617

A programming language is said to have First-class functions when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function, and can be assigned as a value to a variable.

You can do

let sayHello = function() {
   return function() {
      console.log("Hello!");
   }
}
const myFunc = sayHello();
myFunc();

There might be the similar implementation of mapRange.

You should read docs or implementation of mapRange.

Upvotes: 1

Related Questions