ES6 arrow functions and array.map [duplicate] - javascript

This question already has answers here:
Where can I get info on the object parameter syntax for JavaScript functions?
(1 answer)
What does this symbol mean in JavaScript?
(1 answer)
Closed 5 years ago.
I am trying to understand some shorthand ways of writing ES6.
What I cannot fully understand in the example below is the last shorthand "({length})" - I comprehend that it does work, and that it gets the length property of the array, but not why. How could this syntax be applied in another scenario, not involving arrays?
//Declare array
var materials = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];
//Long version - ok
materials.map(function(material) {
return material.length;
});
//Arrow function - ok
materials.map((material) => {
return material.length;
});
//Shorthand arrow function - ok
materials.map(str => str.length);
//What? :)
materials.map( ({length}) => length );
The example above is from the mozilla documentation of arrow functions.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

The length is a property of strings, and can be destructured and returned in the map.
It's mostly the same as:
materials.map((str) => {
const {length} = str;
return length;
});

Related

Javascript: Create dictionary from array of strings [duplicate]

This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 3 years ago.
I have an array of strings that I get from an endpoint and I need to convert it to key-value pairs for the frontend to display them correctly. I have tried different concepts such as reduce and map but have not been able to get it working successfully. I assume it might be one-liner for someone familiar with FE but has taken forever for a BE person like me.
Here is what I have tried:
var input = ['quiz1', 'quiz2'];
const mapping = input.map(x => {"id":x, "label":x};);
console.log(mapping);
I am expecting an output of the format
[{"id":"quiz1", "label":"quiz1"}, {"id":"quiz2", "label":"quiz2"}]
Thanks for looking!
It's simply two syntax errors:
var input = ['quiz1', 'quiz2'];
const mapping = input.map(x => ({"id":x, "label":x}));
console.log(mapping);
Firstly, no semicolon in a un-braced arrow function body.
This is invalid: (() => 3;). This is valid: (() => 3).
Secondly, wrap return obj in ().
This is invalid: () => {x: 3}. This is valid: () => ({x: 3}).

What does ‘...’ in JavaScript do? [duplicate]

This question already has answers here:
What "..." means in Javascript (ES6)? [duplicate]
(1 answer)
Spread Syntax vs Rest Parameter in ES2015 / ES6
(11 answers)
Closed 4 years ago.
I’m new to coding and slef teaching JavaScript.
My task I was set was to identify the largest value in an array.
My soloition works, but I needed the ‘...’ for it to work properly.
My question is, what does the ‘...’ in the last line actually mean/do?
function createAnArr(){
let myArr = prompt("Enter your numbers separated by commas:").split(",");
return myArr;
}
console.log(Math.max(...createAnArr()));
'...' it means it will be able to take any number of arguments of the respective scope
'...': The spread operator is used for array construction and destructuring, and to fill function arguments from an array on invocation. A case when the operator spreads the array (or iterable object) elements.
more details you can see here

Arrow function inside map operator/method in javascript explanation e => e.target.value [duplicate]

This question already has answers here:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 6 years ago.
I am following a tutorial in javascript/angular2 and I know it is a novice question, but if someone could please explain what exactly is this piece of code doing. I have read at various places and in the Mozilla docs, but I am still confused about it. I am aware that: map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results,but what exactly is the code doing in this context:
map(e => e.target.value)
It's nearly the same as this:
map(function(e) {
return e.target.value;
});
...it's just using the concise arrow function form instead of a function function. There are other differences between function functions and arrow functions (arrow functions close over this and a couple of other things, function functions don't), but that code isn't using any of them.
This is using ES2015/ES6 shorthand syntax. To write it out in ES5:
map(function(e) { return e.target.value; })
The function is the callback function, the e is the current element of the array, and the return value of e.target.value will be the value put in the new array.

find out if the of the callback function is an ES6 arrow [duplicate]

This question already has answers here:
JavaScript ES6: Test for arrow function, built-in function, regular function?
(10 answers)
Closed 6 years ago.
Because of the big difference in the context difference between normal and ES6 arrow functions I'd like to be able to find out which one was received on a callback fn.
typeof will return function for both. Is there any way to distinguish?
Arrow functions can't be used as constructors and show typeof arrowFunc.prototype as undefined, whereas a non-arrow function shows `"object".
You can use Function.toString() to return a string representation of the source code of the function, then look for an arrow (=>) in the string.
var arrowFunc = x => 2 * x
var regFunc = function (x) {return 2 * x}
arrowFunc.toString().indexOf("=>") // 2
regFunc.toString().indexOf("=>") // -1

JavaScript's array filter function used without assigning a function - What happens here? [duplicate]

This question already has answers here:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 4 months ago.
Can anyone explain these snippet (just line with the comment above) to me?
function wordRate(word, str) {
let words = str.match(/\w+/g) || [];
// What does these comparison or whatever it is?
return words.filter(w => w == word).length / words.length;
}
Array.filter expects a function as first parameter: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
What is done here instead?
To really understand this, you have to break it down.
ECMAScript 2015 (the latest version of Javascript, formerly ECMAScript 6) introduced arrow functions, which are essentially syntactic sugar for anonymous functions.
Instead of defining a cumbersome and wieldy expression like
function(x) { return x*x;}
arrow functions allow you to write instead
(x) => x*x
where function parameters are specified in parenthesis and the returned result immediately follow the arrow.
In this particular example,
words.filter(w => w == word).length / words.length;
can be rewritten as
words.filter(function(w) {return (w == word);}).length / words.length;
This is easy to interpret: we're finding what fraction of the words array is made up of just a single target word.
(w => w == word)
is equivalent to
(function(w){return w == word})
so this is a Ecmascript 6 (javaScript 6) feature. look here
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Categories