Search code examples
javascriptes6-modules

Can we use variable as a function?


I'm learning Destructuring Assignment in JS and encountered this code which I don't understand.
Isn’t half a variable, why could we use it as a function and pass an argument in console.log?
What would it look like if we write the same code in a basic way?
Thank you!

const stats = {
 max: 56.78,
 min: -0.75
};

const half = ({max,min}) => (max+min)/2.0;

console.log(half(stats));

const stats = {
  max: 56.78,
  min: -0.75
};

const half = ({max,min}) => (max+min)/2.0;

console.log(half(stats));


Solution

  • JavaScript allows you to use function definition and function assignment.

    function myFunction() {}
    

    On top of this, you can also assign your function to another variable (like an alias)

    const myAlias = myFunction
    

    You can also define this all in one line

    const myAlias = function myFunction() {}
    

    Since you would like to re-assign / rename your function, you can define an anonymous function (omit the function name) and assign it to a variable

    const myAlias = () => {}