Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right syntax of lambda javascript

I´m trying to set some values within a object using forEach lambda:

 var row = {title: "", attribute:"", width: ""};
 list.forEach( list =>
                 row.title = list.label |
                 row.attribute = list.label |
                 row.width = "300px"    
              );

Works fine only with a statement row.title = list.label when I add the rest of parameters does not work fine.

What is the right syntax?

like image 204
Juan Reina Pascual Avatar asked Nov 21 '16 13:11

Juan Reina Pascual


People also ask

How do you write lambda in JavaScript?

3) JavaScript Lambda Function Can Duplicate Codelet global = "something" let foo = (input) => { global = "somethingElse" } let bar = () => { if (global === "something") { //... } }

What is the syntax of lambda?

The syntax of a lambda function is lambda args: expression . You first write the word lambda , then a single space, then a comma separated list of all the arguments, followed by a colon, and then the expression that is the body of the function.

What is a lambda expression JavaScript?

A lambda expression is the code you type to define a short function. It is source code text that goes into the compiler and is recognized with a particular syntax. (In Javascript, technically they are called arrow function expressions/declarations.) The expression evaluates at run time to a lambda function in memory.

What does () => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.


2 Answers

Try:

 var row = {title: "", attribute:"", width: ""};
 list.forEach( list => {
                 row.title = list.label;
                 row.attribute = list.label;
                 row.width = "300px"    
              });

Notice the curly braces.

like image 192
Nathan Montez Avatar answered Sep 21 '22 15:09

Nathan Montez


You need curly brackets, as the part after the => is a function body:

 var row = {title: "", attribute:"", width: ""};
 list.forEach( list => {
   row.title = list.label;
   row.attribute = list.label;
   row.width = "300px";
 });

(Be advised that if this is the code you are actually running, the values in row will be set to the values of the last entry in list.)

like image 32
Digitalkapitaen Avatar answered Sep 20 '22 15:09

Digitalkapitaen