Differences between these 2 lines of code [duplicate] - javascript

This question already has answers here:
In Javascript, when is it necessary to assign a named function to a variable?
(3 answers)
Closed 6 years ago.
I'm learning some more ES6:
const _findCartItem = ( item ) => {
return _cartItems.find( cartItem => cartItem.id === item.id);
};
converts to:
var _findCartItem = function _findCartItem(item){
return _cartItems.find(function(cartItem){
return cartItem.id == item.id;
})
};
However, is there a difference between this and the following? Is this dual declaration necessary?
var _findCartItem = function(item){
return _cartItems.find(function(cartItem){
return cartItem.id == item.id;
})
};

Conceitualy, no, both will do the same. Syntactically, yes. First one is passing a reference of a named function to a variable, second a anonymous function.
Using first option is prefereble because you get better call stacks.

Related

Reduce method returns [duplicate]

This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
Closed last year.
Why does the second assignment need return and the first returns variable total automatically?
const total = inventors.reduce(((total, inventor) => total += inventor.passed - inventor.born), 0);
const transportation = data.reduce(((prevVal, currentVal) => {
if (!prevVal[currentVal]) {
prevVal[currentVal] = 0;
}
prevVal[currentVal]++;
return prevVal;
}), {})
If return prevVal is omitted I get Uncaught TypeError: Cannot read properties of undefined
What is the difference in how reduce() acts with values. Is it effected by ternary operation? If so then why this returns 0?
const transportation = data.reduce(((prevVal, currentVal) =>
(!prevVal[currentVal]) ? prevVal[currentVal] = 0 : prevVal[currentVal]++), {})
When using curly braces with an arrow function, the return is not implicit, so you have to use return

What's wrong with my array.filter syntax? [duplicate]

This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
Closed 8 months ago.
this.firmCategories = this.firmCategories.filter(x => {
x.id !== firmCatId;
});
I can see that there is one element of the firmCategories array that has the matching ID by using my debugger, however, I am left with a completely empty array after this executes.
I would expect to have every element except for the one that has the matching ID leftover. What's up?
You are missing a return statement.
this.firmCategories = this.firmCategories.filter(x => {
return x.id !== firmCatId;
});
Or take an arrow function without a function body.
this.firmCategories = this.firmCategories.filter(x => x.id !== firmCatId);

Why this function is always returning null [duplicate]

This question already has answers here:
What does `return` keyword mean inside `forEach` function? [duplicate]
(2 answers)
Closed 2 years ago.
This is my JavaScript function to check if a particular entry exists or not in an array, but this is always returning null even though there is a match
function getSupplierForId(supplierId) {
data.suppliers.forEach(x => {
console.log('Current item id : ' + x.id);
console.log('Requested supplier id : ' + supplierId);
console.log('Both ids are equal : ' + (x.id === supplierId));
if (x.id === supplierId) {
console.log(x);
return x;
}
});
return null;
}
This is my console output:
Why is it returning null always?
Because you have return null; at the end. return statements do not cross function boundaries. return x; only returns from the inner function (whose caller is .forEach), not from the outer function.
Anyways, the right tool to use in your case is .find:
function getSupplierForId(supplierId) {
return data.suppliers.find(x => x.id === supplierId)
}
You might also find my post about callbacks interesting: https://felix-kling.de/blog/2019/javascript-callbacks-misconceptions.html

Is it possible in Javascript to get the name of a variable? [duplicate]

This question already has answers here:
Determine original name of variable after its passed to a function
(9 answers)
JavaScript: Get Argument Value and NAME of Passed Variable [duplicate]
(7 answers)
Closed 7 years ago.
I know this is completely useless, but I'm nonetheless curious. Is it possible to do something like the below?
function getVariableName ( v )
{
// .... do something .....
// return the string "v"
}
var x = 69;
var y = "somestring";
console.log(getVariableName(x)); // prints "x" to the console
console.log(getVariableName(y)); // prints "y" to the console
function getArgNames(fn) {
var matches = fn.toString().match(/\(([a-z_, ]+)\)/i);
if (matches.length > 1) {
return matches[1].replace(/\s+/g, '').split(',');
}
return [];
}
That will return an array of the names of all arguments passed in to the function.

How does one break out of a forEach loop? [duplicate]

This question already has answers here:
how to break the _.each function in underscore.js
(11 answers)
Closed 9 years ago.
If you have:
var some = [0,1,2,3];
_.forEach(some, function (val) {
if(val === 1) {
// this return does nothing
return;
}
});
Looking at the underscore source you can break out of forEach using
var breaker = {};
However breaker is not released to public scope and appears to be an internal variable.
you can use some instead of forEach, which will stop it the first time you return something non-falsy.
The opposite is every(), where it stops when you return something falsy.
You still have to pass the data using closure, since .some() will return true or false.
var some = [0,1,2,3];
_.some(some, function (val, index) {
if(val === 1) {
// this return does nothing
alert("exiting at step "+index+" from finding "+val);
return true;
}
alert("continuing at step "+index+" found "+val);
});

Categories