What is => in javascript? [duplicate] - javascript

This question already has answers here:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 7 years ago.
What does => mean in javascript? I see it here
var N = 50
function asyncFunc (cb) {
setTimeout(() => cb(Math.random()), 100)
}
function loop (max, results, done) {
// Recursion base-case
if (results.length >= max) return done(results)
asyncFunc((res) => {
results.push(res)
loop(max, results, done)
})
}
let randomNumbers = []
loop(N, randomNumbers, function (results) {
console.log(results)
})
It appears twice in setTimeout() and asyncFunc().

This is called the 'fat arrow' it will be coming to JavaScript with ES6 but it has also be implemented in languages that transpile to javascript like coffescript. You can read about it more here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

It's an "arrow function" - a new (in ES6 aka ES1015) short hand notation for functions that's particularly useful for callbacks.

Related

JavaScript Syntax Question - function returning "undefined" [duplicate]

This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
Closed 1 year ago.
When I log this to the console it shows up as undefined. However, when I remove the braces in the function it logs the desired result. I'm confused -- aren't we always supposed to include curly braces in a function? Thank you all.
const shoutGreetings = arr => {
arr.map(word => word.toUpperCase() + '!')
};
const greetings = ['hello', 'hi', 'heya', 'oi', 'hey', 'yo'];
console.log(shoutGreetings(greetings))
Return the result of your map function:
return arr.map(...

JavaScript Closures calculate sum [duplicate]

This question already has answers here:
Closure in JavaScript - whats wrong?
(7 answers)
"add" function that works with different combinations of chaining/arguments
(4 answers)
Puzzle: JS Function that returns itself until there are no arguments
(5 answers)
Variadic curried sum function
(19 answers)
Closed 1 year ago.
I just started learning closures in JavaScript and I'm trying to understand a basic problem.
For example, I'm trying to implement the sum method: sum(1)(4)(5)
const sum = (a) => {
return (b) => {
if(typeof b === 'number')
return sum(a+b)
return a;
}
}
When I call: console.log(sum(1)(4)(5)()) it works perfect and return 10. However, if I call console.log(sum(1)(4)(5)), it returns [Function (anonymous)]. Why?
Thanks
Every time you call your function like:
sum(1)(10)
you are returning the inner function:
(b) => {
if(typeof b === 'number')
return sum(a+b)
return a;
}
Because type of b === 'number' and you are returning sum(a+b) that calls
again the function sum and returns again the inner function. Thats why when you finally put the last parenthesis like:
sum(1)(10)()
The inner function will execute and type of b in this case is different from number and will return 'a' that already contains the sum of the values.

Typescript arrow function parantheses in filter method [duplicate]

This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
Arrow function without curly braces
(9 answers)
Closed 2 years ago.
Imagine I have an array containing movie objects such that
const movies: Movie[] = [ movie1, movie2, movie3, movie4 ];
I want to select a movie, for instance I have chosen movie2, then I want movie2 to be removed.
The following code works, Imagine m is the selected movie:
movies = movies.filter( m => m !== movie );
I want to understand how the arrow function works and tried the following code but it did not work.
movies = movies.filter( m => {
m !== movie;
});
What is the difference between those two codes?
The difference is, that the short-hand version implicitly returns the result. The long version from you is missing the return statements, like:
movies = movies.filter( m => {
return m !== movie;
});

javascript: 'return' is ignored and keeps looping [duplicate]

This question already has answers here:
What does `return` keyword mean inside `forEach` function? [duplicate]
(2 answers)
Short circuit Array.forEach like calling break
(30 answers)
Closed 4 years ago.
function checkMagazine(magazine, note) {
var map = new Map();
var noteAr = note.split(" ");
var magazineAr = magazine.split(" ")
noteAr.forEach((note) => {
if (map.has(note)) {
map.set(note, map.get(note) + 1)
} else {
map.set(note)
}
});
magazineAr.forEach((word) => {
if (!map.has(word)) {
return "No"
}
});
return "Yes"
}
I'm checking to see if each word of a note is contained in the magazine by first hashing the values of the note and checking them in magazineAr. If the note word does not exist in the hash, then I am return "NOing. However, I keep getting a return "YES" in console.
I've watched it in debugger mode and I see it enter the statement where it hits 'return No' but then it just keeps on going with the forEach loop. I've even tried return false but same thing.
A forEach callback ignores the value that's returned - no matter what it is, every item in the array will be called with the forEach. For what you're trying to do, you should probably use every instead, which checks whether all items in the array fulfill the condition:
const hasEveryWord = magazineAr.every(word => map.has(word));
return hasEveryWord
? "Yes"
: "No";

Javascript "=>" syntax meaning [duplicate]

This question already has answers here:
What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?
(14 answers)
Closed 7 years ago.
Code example:
function unusedDigits(...args){
return [0,1,2,3,4,5,6,7,8,9].filter(o => args.join("").indexOf(o) === -1).join("")
}
Everything is clear here. Exept =>. What does this mean in javascript?
This is a ES6 arrow function which is a short syntax for function expression. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
So:
// ES5
var selected = [0,1,2,3,4,5,6,7,8,9].filter(function (o) {
return args.join("").indexOf(o) === -1;
});
// ES6
var selected = [0,1,2,3,4,5,6,7,8,9].filter(o => args.join("").indexOf(o) === -1);

Categories

Resources