First class function javascript

What is meant by ‘first class object’?

In a recent question, I received suggestions to talk on, amongst other things, the aspect of JavaScript where functions are ‘first class’ objects. What does the ‘first class’ mean in this context, as opposed to other objects? EDIT (Jörg W Mittag): Exact Duplicate: «What is a first class programming construct?»

11 Answers 11

In computer science, a programming language is said to support first-class functions (or function literal) if it treats functions as first-class objects. Specifically, this means that the language supports constructing new functions during the execution of a program, storing them in data structures, passing them as arguments to other functions, and returning them as the values of other functions.

This page also illustrates it beautifully:

Really, just like any other variable

  • A function is an instance of the Object type
  • A function can have properties and has a link back to its constructor method
  • You can store the function in a variable
  • You can pass the function as a parameter to another function
  • You can return the function from a function

also read TrayMan’s comment, interesting.

Quoting wikipedia is nice and dandy, but the description is written in a language for scientists and not for geeks. What the heck does all that mean anyway? The last sentence in that quote is vagu.

Читайте также:  Скрипт пароль на javascript

Conveniently a language that has first-class functions also has higher-order functions, as opposed to being limited to first-order functions, which would rule out first-class functions. (Though higher-order, not first-class is possible.)

The notion of «first-class functions» in a programming language was introduced by British computer scientist Christopher Strachey in the 1960s. The most famous formulation of this principle is probably in Structure and Interpretation of Computer Programs by Gerald Jay Sussman and Harry Abelson:

  • They may be named by variables.
  • They may be passed as arguments to procedures.
  • They may be returned as the results of procedures.
  • They may be included in data structures.

Basically, it means that you can do with functions everything that you can do with all other elements in the programming language. So, in the case of JavaScript, it means that everything you can do with an Integer, a String, an Array or any other kind of Object, you can also do with functions.

More complete approval of Strachey-Sussman-Abelson’s formulation. So if your language supports such a construct then you’ve got a function as a first-class language 🙂

var men = function (objectOfAdmiration) < return objectOfAdmiration(); >; men.isSweetHeart = true; var women = function (objectOfAdmiration) < return objectOfAdmiration(); >; women.isSweetHeart = true; var aliens = function (objectOfAdmiration) < return objectOfAdmiration(); >; function like(obj)< if (obj.isSweetHeart) < return function ()< return "Holy TRUE!">; > else < return function ()< return "Holy CRAP!">; > > alert("Men like women is " + men(like(women))); // -> "Holly TRUE!" alert("Women like men is " + women(like(men))); // -> "Holly TRUE!" alert("Men like aliens is " + men(like(aliens))); // -> "Holly CRAP!" alert("Aliens like women is " + aliens(like(women))); // -> "Holly TRUE!" :) //women(like(aliens)); // Who knows? Life is sometimes so unpredictable. :) 

In short, anything is a first-class object if it acts in the language as a state manipulation sort of object or type of object. Simply something you can operate on and pass around statements and evaluate in expressions at the same time. Or even shorter: when you can think of a function as an object that can be additionally invoked.

Источник

First-class Function

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.

Examples

Assigning a function to a variable

const foo = () =>  console.log("foobar"); >; foo(); // Invoke it using the variable // foobar 

We assigned an Anonymous Function in a Variable, then we used that variable to invoke the function by adding parentheses () at the end.

Note: Even if your function was named, you can use the variable name to invoke it. Naming it will be helpful when debugging your code. But it won’t affect the way we invoke it.

Passing a function as an argument

function sayHello()  return "Hello, "; > function greeting(helloMessage, name)  console.log(helloMessage() + name); > // Pass `sayHello` as an argument to `greeting` function greeting(sayHello, "JavaScript!"); // Hello, JavaScript! 

We are passing our sayHello() function as an argument to the greeting() function, this explains how we are treating the function as a value.

Note: The function that we pass as an argument to another function is called a callback function. sayHello() is a callback function.

Returning a function

function sayHello()  return () =>  console.log("Hello!"); >; > 

In this example, we are returning a function from another function — We can return a function because functions in JavaScript are treated as values.

Note: A function that returns a function or takes other functions as arguments is called a higher-order function.

See also

Found a content problem with this page?

This page was last modified on Jun 8, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Understanding First-Class Functions in JavaScript

JavaScript is a programming language with First-class Functions.

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 assigned as a value to a variable, can be passed as an argument to other functions and can be returned by another function.

Assign a function to a variable

// Assign an Anonymous Function to a variable const greeting = () =>  console.log('Hi Mikaela!'); >; // Invoke the function using the variable greeting(); 

Pass a function as an argument

const sayHi = () =>  return 'Hi '; >; const greeting = (hiFn, name) =>  console.log(hiFn() + name); >; // Pass `sayHi` as an argument to `greeting` function greeting(sayHi, 'Mikaela!'); 

Return a function

const greeting = () =>  return () =>  console.log("Hi Mikaela!"); >; >; // invoke the inner function greeting()(); // or var hi = greeting(); hi(); 

Let’s try another example

Create a function that is called addTwoNumbers. This function takes one number as parameter and it returns another function that takes again one number as parameter and finally returns the sum of these two numbers.

 function addTwoNumbers(num1)  return (num2) =>  return num1 + num2; >; >; // Invoke the function const add = addTwoNumbers(10); // 15 console.log(add(5)); 

Conclusion

First-class functions are a very important part of the JavaScript ecosystem, using them you can work on powerful design patterns such as higher-order functions, partial function application, callbacks, and much more.

Resources

Источник

First-class functions in JavaScript

First-class functions in JavaScript

In programming, a first-class function is when a function is treated as a variable. This is special because it means that a function can be passed into another function as an argument.

Not all languages support a first-class function idea, and these are usually natively imperative languages like C. Java and C++ also didn’t use to support first-class based ideas.

Imperative programming tells a computer how to do something — it’s a set of linear instructions that are executed in order. Declarative programming follows a generalized what should happen sequence. The control flow in a declarative language is not as strict and code can be executed asynchronously when required.

JavaScript is declarative by design and nature. The order of execution isn’t as vital towards arriving at the desired end-state for declarative programming.

When it comes to first-class functions, you can assign a function to a variable but the actual value of the variable will not be set until it gets called. It’s a fuzzy area because the assignment does not happen instantly. Imperative programming requires clarity and first-class functions introduces a level of uncertainty.

Take a look at the following JavaScript code:

In JavaScript, functions are not invoked until they are called. The above code is valid but catName is not set until it is called. The invocation will execute the function attached to it and assign catName with the value Tibbers .

When you assign a function directly to a variable, it’s called an anonymous function and you can call the variable by adding a pair of parentheses at the end. So to invoke (and therefore assign) the above variable, you’ll need to write catName()

To use a function as an argument, you need to pass in the function name.

let catName = function() < return "Tibbers"; >function greet(name) < console.log("hello " + name); >greet(catName()); 

catName is passed in as an argument for the greet() function. If you use catName without the parenthesis () , JavaScript will pass the contents of the function rather than execute it. This allows the function to be treated as a value.

The flow of execution looks something like this:

With first-class functions, you can also have a function return another function. This is called a higher-order function.

In JavaScript code, it can look something like this:

This is valid JavaScript code because a function returned is treated as a value. You can also write the same thing using a variable.

const calculateCart = function() < //do something here return cartTotal(); >

Why is the above set to const and not let or var ? const ensures that the structure of the function cannot be changed later down the track, making it immutable by default. In JavaScript, immutability refers to the inability to change the values assigned. In the above example, a function is assigned as an immutable thing, which means that the process cannot be changed but the values being processed and passing through it can.

The return can also be in the form of an anonymous function. For example:

const calculateCart = function() < //do something here return function()< //do something here >> let myCart = calculateCart(); myCart(); 

When you have higher-order functions, you need to invoke each level manually. If you don’t do this, it will return the function itself rather than the final expected return.

Why is this? Because functions are not executed unless they are called. This call has to be explicit.

That’s why for calculateCart to work properly, you need to assign it to another value first before invoking the chain.

Here’s what the execution chain looks like in a diagram:

Alternatively, you can also execute the nested function through double parenthesis.

const calculateCart = function() < //do something here return function()< //do something here >> calculateCart()(); 

Or if you’ve got more than two nested levels, you just need to add the same amount of parenthesis to ensure that the inner functions get invoked.

const calculateCart = function() < //do something here return function()< //do something here return function()< //do something here >> > calculateCart()()(); 

That’s basically first-class functions in a nutshell for JavaScript.

Источник

Оцените статью