0

I read this sentence, as trying to understand better anonymous functions.

Because functions are values, you can pass a function as an argument into another function.

I can't grasp the "functions are values" idea.
If I had to define precisely what functions are, I would say functions return values, or functions are blocks of code. Or function name is a value.
What does it mean "functions are values"?

Thanks

Manaus
  • 431
  • 5
  • 17
  • Functions don't require names. They can also be assigned to a variable as a value. Functions can return a function (a value). – evolutionxbox Jun 01 '21 at 11:07
  • I think the best way to think of it is that you can put them on the right-hand side of an assignment. As in "a=b" and b can be any value - which can be a function. They also return values, and can indeed return functions. – Chris Lear Jun 01 '21 at 11:07
  • It means functions are [first-class-citizens](https://en.wikipedia.org/wiki/First-class_function) in javascript. You can treat them the same as e.g. a number or a string, in the way that you can pass them as arguments, store them to variables or properties, etc. They are "just another value you can store and read". – ASDFGerte Jun 01 '21 at 11:07
  • "*Or function name is a value.*" and what is the value of a function name? If you have `function foo() {}` what would `foo` be? Answer is it's *the function*. So, functions *are* values. – VLAZ Jun 01 '21 at 11:54

1 Answers1

1
var x = 1

The variable x has a value which is a primitive number 1.

var y = { foo: 1 };

The variable y has a value which is an object.

var z = function () { return 1; }

The variable z has a value which is a function.

And you can treat that function like any other value.

var z = function () { return 1; }

var a = function (an_argument) {
    console.log("Log an_argument", an_argument);
    console.log("Call an_argument", an_argument());
}

a(z);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Ok so I have two states of a function: as a _potential_ and _executed_. "Function as a value" always falls in the first case right? – Manaus Jun 01 '21 at 12:49
  • 1
    No. A function is always a function, which is a type of value. It can be called multiple times and it will return its return value. There is no "called function" and "uncalled function" state. – Quentin Jun 01 '21 at 12:50
  • @Manaus when you call a function, you get its return result. You don't get the function back with a different state. Nor is the existing function changed by being called. A function is a value that can be *called*. As opposed to, say, a number or a string: `str = "hello"; str()` will fail because it's not callable. – VLAZ Jun 02 '21 at 09:03