Parsing the javascript reduce documentation [duplicate] - javascript

This question already has answers here:
What does this mean in documentation: square bracket followed by comma ( [, ) [duplicate]
(2 answers)
Closed 5 years ago.
In Mozilla's Reduce docs page I found the syntax below:
arr.reduce(callback[, initialValue])
The square brackets throw me off.
I have code like this that works:
const selectedItems = selectedItemsList.reduce((itemObject, item) => {
return {
...itemObject,
[item]: this.props.areasList.find(area => area.id === item)
};
}, {});
I do not use square brackets. I provide a callback and an initial value, separated by a comma. Can anyone elaborate on why the doc shows the syntax that it does for reduce? I only figured out the code in this post that I have by looking at other examples.

The square brackets mean that the initialValue parameter is optional, i.e. you don't have to provide it. You shouldn't actually place these brackets in your code.

Related

JavaScript Arrow Function throws Undefined [duplicate]

This question already has an answer here:
Why doesn't my arrow function return a value?
(1 answer)
Closed 2 years ago.
Below is my code for move all characters forward by one for a given string.
ex. abc => bcd
const moveCharForward = (str) => {
str
.split('')
.map(char => String.fromCharCode(char.charCodeAt(0) + 1)).join('');
}
console.log(moveCharForward('abcd'));
when I called the method it throws undefined.
I modified the code by removing the curly brackets like below.
const moveCharForward = (str) =>
str
.split('')
.map(char => String.fromCharCode(char.charCodeAt(0) + 1)).join('');
console.log(moveCharForward('abcd')); //working correctly
Now when I called the method its working correctly.
I want to know why throws undefined when Im adding method implemetation inside the curly brackets?
When using arrow functions like this, if you don't use curly braces, then JavaScript implicitly returns the value following the arrow. However, if you do use curly braces, then JavaScript expects a block of code, in which there must be a return statement in order to return a value
When you add the curly braces you need the return keyword. Without curly braces the return is implied

how to return array of objects from .map [duplicate]

This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 4 years ago.
in the below code, activeProgs is an array contains program objects. i am using .map because i would like to have an array containing the name of the
program and a token value. this token value is an integer and it could be incremented by one for each program as shown below in the code.
my question is, if i want to have the same array that contains the program name and the token but as an object. in other words, i want the .map()
to return an array but that array contains objects with two attributes "progName" and "token". can i do the following?
activeProgs.map((prog)=> {progName: prog.getHeader().getName(), token: (++i)} )
please let me know how to do it correctly
code:
activeProgs.map((prog)=> prog.getHeader().getName() + '->' + (++i))
like so:
activeProgs.map((prog) => ({progName: prog.getHeader().getName(), token: (++i)}) );
or like so:
activeProgs.map((prog) => {
return {progName: prog.getHeader().getName(), token: (++i)}
})
In the first example, adding brackets around the {} forces it to be parsed as an expression containing an object literal. In your code, it is interpreted as part of the function declaration, making the next bit a syntax error.
The second one makes that more explicit
You weren't far off with the example you suggested, you just needed to wrap the object in brackets so the compiler understands you are returning an object and not declaring a function body
activeProgs.map(prog => ({
progName: prog.getHeader().getName(),
token: (++i)
}))

What is this es6 assignment operator? [duplicate]

This question already has answers here:
Javascript object bracket notation ({ Navigation } =) on left side of assign
(5 answers)
Closed 5 years ago.
If this operator declared:
const { assign, isEmpty, run } = Ember;
Then, instead of:
Ember.run(() => { ... });
Ember.assign(foo, {});
It can be written as:
run(() => { ... });
assign(foo, {});
Which is much nicer!
What is it and how does it work?
Note: I'll edit this question to make it clearer when I know...
It's called destructuring and yes, it's very nice. Very convenient for cleaning up your code.
As explained by MDN:
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Full reference here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Javascript documentation notation [duplicate]

This question already has answers here:
What do the brackets around the arguments mean when reading documentation for a method? [duplicate]
(3 answers)
Closed 6 years ago.
I've seen this a lot and most of the time I can figure out what it means, but there have been times when I was a bit confused. Looking at documentation mostly on jquery i see something like this:
.toggleClass( function [, state ] )
what does the bracket notation with the comma and state mean exactly?
Any info would be awesome.
Thanks!
Everything between the brackets [] is optional.
In your case it means that state can be omitted, and the function will still work.
Optional parameters.
Those marked inside such as state in your case can be omitted and the function will not throw an error.
For another example:
jQuery.ajax( url [, settings ] )
Means both
jQuery.ajax( "www.google.com" )
and
jQuery.ajax( "www.google.com" , {dataType: 'mycustomtype'} )
are valid.

What does this documentation syntax mean at MDN for a JavaScript function? [duplicate]

This question already has answers here:
How to interpret function parameters in software and language documentation?
(4 answers)
Closed 7 years ago.
I'm learning JavaScript through "Eloquent JavaScript" manual and now I'm doing exercises from chapter 5 "High-Order Functions". One of the functions this chapter introduces you is "reduce". I understand how it works, my problem comes up when I try to understand its definition at MDN. I don't understand syntax definition it gives:
arr.reduce(callback[, initialValue])
This syntax sections is followed by the section called Parameters. These are:
callback
previousValue
currentValue
index
array
initialValue (optional)
What I don't understand is what do those square brackets and the comma mean? Because when I see square brackets immediately I think in arrays. And why is just initialValue in the definition and not the others parameters? Why there is no space between square brackets and callback?
Because below there are two examples:
Example 1
[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array) {
return previousValue + currentValue;
});
Example 2
var total = [0, 1, 2, 3].reduce(function(a, b) {
return a + b;
});
// total == 6
and I don't know how do they fit into the definition.
Thanks
It's usually a convention for API documentations to use [] to denote optional parameters. However, the [] is not part of the syntax on usage. It's just documentation convention.
As already explained in other answers, the parameters inside of the "[]" are optional. Regarding the question as to why the "other parameters" (i.e. previousValue etc.) are not there, those are parameters to callback and not to reduce. So callback will receive those arguments on each run of reduce.

Categories

Resources