confused about return array#map javascript [duplicate] - javascript

This question already has answers here:
Can anyone explain why linebreaks make return statements undefined in JavaScript? [duplicate]
(4 answers)
Closed 7 years ago.
I have the code:
function func1(){
return
array.map(function(el){
return el.method();
});
}
function func2(){
var confused =
array.map(function(el){
return el.method();
});
return confused;
}
Why func1 return undefined while func2 return good value (that i need)?
Sorry for my english.

Internally in JS engine first example looks like this,
function func1() {
return;
array.map(function(el){
return el.method();
});
};
that's why you get undefined, don't add new line after return, because return statement followed by a new line tells the JS intepreter that a semi colon should be inserted after that return.
function func1() {
return array.map(function(el){
return el.method();
});
};

Related

Multiply function with 1 argument only [duplicate]

This question already has answers here:
What is 'Currying'?
(23 answers)
Closed 4 years ago.
I have a javascript coding exercise to do which has got me a bit stuck (I'm only just starting javascript).
The exercise is as follows:
Write a function multiply(a) that returns a function capable of multiplying by a. Call this function with b as a parameter.
So far I have the main skeleton (not difficult):
function multiply(a) {
return //Stuck here
}
I'm not sure if the question is to call multiply(b) and have it give us the result of a*b or something else...
I tried writing a function directly after the return statement but this just printed out the function name.
function multiply(a) {
return function f { return a * b } //Here I assume b is a variable defined somewhere
}
Thanks in advance!
You could take a closure over the variable and return a function for the multiplication for the multiplicand.
function multiply(a) {
return function (b) {
return a * b;
}
}
var threeTimes = multiply(3);
console.log(threeTimes(7));

What is this js syntax called [duplicate]

This question already has answers here:
What is 'Currying'?
(23 answers)
Closed 4 years ago.
I recently found JavaScript code like this:
someFunction()()
Function immediately invoked right after function without classic IIFE syntax.
What is that kind of syntax called? And how it works?
Its a function that returns another function.
Here is an example on how it works, this can help you to understand better.
function sum(x){
return function(y){
return x+y;
}
}
sum(3)(5); //8
For you code to work:
someFunction()();
You need to have code that looks like this:
function someFunction() {
console.log('someFunction()');
// do something before return
return function() {
console.log('someFunction()()');
// do something else here
}
}
someFunction()();
In this example you first call someFunction then you call the function that was returned by someFunction.
This can be good to do when you need to pass in a variable that will be used in the inner function but the inner function will be called in the future like this:
function someFunction(outerVal) {
console.log('Outer called.');
return function(innerVal) {
console.log('inner called.');
return outerVal * innerVal;
}
}
var inner = someFunction(12);
setTimeout(()=> {
console.log(inner(4));
}, 1000);
I use this often in Node.js for common middle-ware that needs a single value to be unique.
app.get('/dogs', myFn('woof'));
app.get('/cats', myFn('meow'));
app.get('/birds', myFn('tweet'));
function myFn(word) {
return function(req, res, next) {
res.write(word).end();
}
}
That is an over simplification, but can be vary powerful.

Javascript function returning undefined even though console.log shows correct value [duplicate]

This question already has answers here:
forEach/for...in not returning values? [duplicate]
(5 answers)
Closed 5 years ago.
I've checked other questions that seem to be duplicates but none of them have solved my problem. I have this simple function that loops through an array of rule objects and returns the one with the matching "type":
$ctrl.findRule = function(ruleName){
$ctrl.rules.forEach(function(rule){
if(rule.type === ruleName){
console.log("returning rule: " + rule.type);
return rule;
}
});
return null;
};
I call this function as follows:
var wordCountRule = $ctrl.findRule("word_count");
console.log(wordCountRule);
I see on the console returning rule: word_count and then the console.log(wordCountRule) displays undefined. I have tried everything and I have no idea why this is happening.
Thanks!
The issue is because you're returning the value from the inner forEach handler function, not your outer findRule() function.
To fix this you could define a variable to hold the return value and amend that within the inner scope:
$ctrl.findRule = function(ruleName) {
var returnVal = null;
$ctrl.rules.forEach(function(rule) {
if (rule.type === ruleName) {
returnVal = rule;
}
});
return returnVal;
};
However you should note that it you're looking for a single value you can use find() directly, without the need to loop explicitly:
$ctrl.findRule = function(ruleName) {
return $ctrl.rules.find(function(rule) {
return rule.type === ruleName;
});
};
Taking the above example a step further, by using ES6 syntax it can be reduced to just this:
$ctrl.findRule = ruleName => $ctrl.rules.find(rule => rule.type === ruleName);

why i always getting back as undefined? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I am new to Javascript, and Trying to write a function inside a function, but it always show undefine.
function csnotebook(){
function calculate_mw(peptide){
var total_mw=0;
var split_peptide = peptide.split("-");
// Check if the blog id is found in database
Aa.findOne({ three_letter: split_peptide[1] }, (err, aa) => {
// Check if the id is a valid ID
if (!aa) {
console.log("wrong aa");
}else{
total_mw += aa.mw;
}
return total_mw;
});
}
var publicAPI = {
mw: calculate_mw
};
return publicAPI;
}
var fred = csnotebook();
var totalmw = fred.mw("Ala-Cys");
console.log(totalmw);
I assume i can find the corresponding value mw from database, but totalmw, I always get undefined for some reson, anybody know why? Thank you!!
The inner function calculate_mw doesn't return anything, so the return value of a function is undefined unless you return something.
If you want to return the result of the Aa.findOne you should:
return Aa.findOne(...

Curly bracket with "return" keyword [duplicate]

This question already has answers here:
Why do results vary based on curly brace placement?
(6 answers)
Closed 9 years ago.
var calculator = function ()
{
function abc() { return (2+3); }
return {
addFun: abc
}
}();
var calcu = function () {
function abc() { return (3+4); }
return
{
addFun: abc
}
}();
$(document).ready(function () {
alert(calculator.addFun());
**alert(calcu.addFun());**
});
What is difference between calculator and calcu function? calcu function gives error when it execute.
Difference is only that curly bracket is next line in "calcu". It is work fine if I remove next and put curly bracket with "return" keyword.
Please explain why so?
It's being parsed as this:
return; // returns undefined
// a block:
{
addFun: abc // syntax error!
};
because of automatic semicolon insertion.
Change it to:
return {
addFun: abc
};
It's called automatic semicolon insertion:
When a continue, break, return, or throw token is encountered and a LineTerminator is encountered before the next token, a semicolon is automatically inserted after the continue, break, return, or throw token.
Since there's a newline right after your return statement, a semicolon is inserted automatically, turning your code into:
return;
{
addFun: abc
}
Return is a tricky keyword in JavaScript. In the first example, you are returning an anonymous object to the calculator function, and in the second example you are returning no values. JavaScript will interpret the second function like this:
var calcu = function() {
function abc() ...
return; // return undefined
{
addFun: abc
}
Notice the semi colon is interpreted after the return keyword and thus the calcu function will return nothing.
return
{
addFun: abc
}
This is wrong because JavaScript would execute return and will get out.
This should be
return {
addFun: abc
}
Have a look at linting tools such as jshint to avoid this and many other errors, here is it's output:
What happens is that this section:
return
{
addFun: abc
}
is being interpreted as two statements, a return void (the function returns void immediatelly) plus an object expression containing addFun that is not assigned to anything.

Categories