JavaScript Functions , return undefined - javascript

Hello Everyone hope you all doing great ,
this is my code , function with name and callback
taking the name to callback function to make return the name and console.log it
if i
function doSomething(name,callback) {
callback(name);
}
function foo(n) {
return n;
}
var val = doSomething("TEST",foo);
console.log(val);
i got undefined .
if i
function doSomething(name,callback) {
callback(name);
}
function foo(n) {
console.log(n);
}
var val = doSomething("TEST",foo);
that works fine and console.log the TEST name .
So why the return not working ?
thanks

Your doSomething() function doesn't return anything, which means an assignment using it will be undefined. But, that's not really the problem here.
The underlying problem is that you seem to be mixing two different data processing patterns here: if you're writing purely synchronous code, then use returning functions (which immediately return some value). If you need asynchronous code, then use a callback (which will "eventually" do something). Mixing those two patterns is a recipe for problems and frustration:
Either:
don't name your function a "callback", and have it return its processed value, or
make the callback responsible for doing whatever it is you were going to do with val.
Case 1:
function doSomething(data, processor) {
return processor(data);
}
function passThrough(v) { return v; }
var val = doSomething("test", passThrough);
// immediately use "val" here in for whatever thing you need to do.
Case 2:
function doSomething(data, callback) {
// _eventually_ a callback happens - for instance, this
// function pulls some data from a database, which is one
// of those inherently asynchronous tasks. Let's fake that
// with a timeout for demonstration purposes:
setTimemout(() => callback(data), 500);
}
function handleData(val) {
// use "val" here in for whatever thing you need to do. Eventually.
}
doSomething("test", handleData);
And if you want to go with case 2, you really want to have a look at "Promises" and async/await in modern Javascript, which are highly improved approaches based on the idea of "calling back once there is something to call back about".
2021 edit: a third option since original writing this answer is to use the async/await pattern, which is syntactic sugar around Promises.
Case 3:
async function doSomething(input) {
// we're still _eventually_ returning something,
// but we're now exploiting `async` to wrap a promise,
// which lets us write normal-looking code, even if what
// we're really doing is returning a Promise object,
// with the "await" keyword auto-unpacking that for us.
return someModernAsyncAPI.getThing(input);
}
function handleData(val) {
// ...
}
async function run() {
const data = await doSomething("test");
handleData(data);
}
run();

function doSomething(name,callback) {
callback(name);
}
function foo(n) {
console.log(n);
return n;
}
var val = doSomething("TEST",foo);
Take a look at above code. When you call doSomething, which internally executes foo it prints on the console because thats what console.log is for. However, after this statement it returns n as well which then is received in doSomething. But its not being returned. To put it simply, what you are mainly doing is
function doSomething(name,callback) {
const returnValue = callback(name);
}
If you call the above method, it will return undefined. To make it return correct value, you have to call "return returnValue". Similary you have to say
return callback(name)
Hope this helps.
Happy Learning

Inorder to assign the returning value/object of a function(in this case doSomething, it should have a return statement. Else the function returns nothing, so when you assign that to val, it is still undefined.
So you modify your code like this:
function doSomething(name,callback) {
return callback(name);
}
function foo(n) {
return n;
}
var val = doSomething("TEST",foo);
console.log(val);

undefined is implicitly returned if you don't have a return in your function.
when you call var val = doSomething("TEST",foo), you are aligning the return value of doSomething to val, which is undefined.
function doSomething(name,callback) {
return callback(name);
}
function foo(n) {
return n;
}
var val = doSomething("TEST",foo);
console.log(val);

Related

What does Return do in here?

I have problem with 'return' means in this code.
1.
function func4() {
var str = "function works.";
console.log(str);
}
func4();
2.
function func4() {
var str = "function works.";
return str;
}
var value = func4();
console.log(value);
Both of them, their result is 'function works.'.
I know that return used for exit function but I'm still confuse when I have to use return exactly.
Sorry about my super basic question :(
As far as I understand 'return' assigns value to a function and returns it, so you're displaying function's value. In the first case you are just simply invoking a function to display a string.
Let's analize this two scenarios:
You have a function that initialize a variable with a predefinided value, and then, you log the value. Then, outside the function you execute it
You have the same variable but with the difference that instead of loggin the value inside the function, you returned it from it. So you can initialize the funcion and store the value on another variable var value = func4();.
Let me try to explain it with some requirements.
I want a function which returns me some data instead of passing a variable and updating the variable in function.
You call a function and it is always best to test negative scenarios first. So in case of negative scenario you can return it from there it self.
In your second case if you see you are getting a value from that function and then printing it. Same thing you can not do using first function.
Always there are workarounds for everything. In the end it depends on your need and what is best suited for that situation.
Both of those functions don't equal the same thing, but they do log the same string.
func4() in #1 is equal to undefined, because it returns nothing.
func4() in #2 returns (gives back) the value "function works.", a string, which is then given to console.log outside of the function.
function func1() {
var str = "function works.";
// console.log(str);
}
func1();
function func2() {
var str = "function works.";
return str;
}
// console.log(func2());
console.log(func1() === undefined);
console.log(func2() === 'function works.');
If you want to use the func4() value for further calculations without calling it again, then you would return {value}.
For e.g
function func4(userInput) {
return userInput % 2 == 0;
}
var response = func4(userInput);
if(response == true) {
console.log('user entered an even number');
} else {
console.log('user entered a odd number');
}
// from here you can use the value of response n times without calling the function again.
Whereas, if you don't return then you will have to call the function x number of times whenever you want to re-user the response of it.
function func4(){
var str = "function works.";
return str;
}
var value = func4();
console.log(value);
//here return means you are returning the value of variable 'str'.
You can find the details here.
https://learn.microsoft.com/en-us/cpp/c-language/return-statement-c?view=vs-2019#:~:text=A%20return%20statement%20ends%20the,value%20to%20the%20calling%20function

Returning from an anonymous function won't work, even though it's not async

I have the following function:
function filterDesiredURLs(tweet) {
tweet.entities.urls.forEach((url) => {
desiredURLs.forEach((regexPattern) => {
if (regexPattern.test(url['expanded_url'])) {
console.log('hello, im returning');
return true;
}
})
})
}
And I'm calling it like this:
console.log(filterDesiredURLs(tweet));
Where tweet is a defined object. I can see that the function is indeed returning because I see the output hello, im returning in the console, but the console.log(filterDesiredURLs(tweet));prints undefined. I would expect this for anonymous functions passed as callbacks for async operations, but this is not async, so the return should work. What's happening?
return doesn't operate across function boundaries. It only returns from the innermost function. To do what you want you probably want filter or find coupled with some:
function filterDesiredURLs(tweet) {
// First, you were missing a return in the outer function
// Without a return here, *this* function will return `undefined`
return tweet.entities.urls.filter(url => {
// We are using `filter` to reduce the URL list to only
// URLs that pass our test - this inner function needs to return
// a boolean (true to include the URL, false to exclude it)
return desiredURLs.some(regexPattern => {
// Finally, we use `some` to see if any of the regex patterns match
// This method returns a boolean value. If the function passed to it ever
// returns true, it terminates the loop and returns true
// Otherwise, it iterates over the entire array and returns false.
return regexPattern.test(url['expanded_url']);
});
});
}
When you call return like that, you're returning from the closest function (in this case, the anonymous function passed as argument to your inner forEach).
From the docs:
The return statement ends function execution and specifies a value to
be returned to the function caller.
To accomplish your goal, you may try this:
function filterDesiredURLs(tweet) {
let found = false;
tweet.entities.urls.forEach((url) => {
desiredURLs.forEach((regexPattern) => {
if (regexPattern.test(url['expanded_url'])) {
console.log('hello, im returning');
found = true;
/* don't need return because forEach does not expects a function that returns something; and you can't break forEach */
}
})
})
return found;
}
The javascript forEach method returns undefined.
forEach is an operation which retains the array as immutable and returns a new array. In your code, the forEach method is called and it doesn't return anything, hence undefined.

What is the point of the return in Javascript?

I've recently been learning javascript and came across the return statement or whatever it is. I've watched tutorials on it and I still don't get the point of it. Do I ever need it for anything and can someone please explain in detail what it does? Thanks
The return statement has multiple uses:
1) Return early from your function before the end of the function body. This is often within a branch of the code as in:
function whatever()
// do some things
if (err) {
console.log(err);
return err;
}
// other code here that will not execute if there was an err
}
2) Return a specific value back to the caller as in:
function add(a, b) {
return a + b;
}
var sum = add(3,4);
console.log(sum); // will show 7
The return statement in javascript can be used by itself to just exit the current function call and not return a specific value or it can be used to return a specific value.
If no return statement is present in a function, then the function will execute to the end of the function body and will return automatically at the end of the function body.
The only point of it is to send a value (string, number, or other values) from your function so that is can be used outside the function. Instead you can use global variables but that takes up more code, so it's a shortcut instead.
jfreind00 above said that you can use it to branch off early but that's what break. Here is the syntax:
function HiThere(something) {
if (something === true) {
break;
}
alert("Hi");
}
In this case, if something is true, then exit the function, if not then say hi.
Return would be like this:
function HiThere(something) {
if (something === true) {
return "Value to return: " + something;
}
alert("Hi");
}
In this case, if something is true, then exit the function and return Value to return: true, if not then say hi but don't return anything back.
Here's the most common use of the return statement:
document.getElementById("demo").innerHTML = myFunction(5,3); // Call a function
// to set the "demo" element to the value of: 5 * 3
function myFunction(a,b) {
return a * b;
}
<p id="demo"></p>
Use it to return a value. Your value could be "Yes", "false", "hello world" or "eat dirt." You can then run certain code based on the returned value.
Hope this helps!

Why does this forEach return undefined when using a return statement

Object.prototype.e = function() {
[].forEach.call(this, function(e) {
return e;
});
};
var w = [1,2];
w.e(); // undefined
But this works if I use alert instead
// ...
[].forEach.call(this, function(e) {
alert(e);
});
// ...
w.e(); // 1, 2
I realize this is an old question, but as it's the first thing that comes up on google when you search about this topic, I'll mention that what you're probably looking for is javascript's for.. in loop, which behaves closer to the for-each in many other languages like C#, C++, etc...
for(var x in enumerable) { /*code here*/ }
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...in
http://jsfiddle.net/danShumway/e4AUK/1/
A couple of things to remember :
for..in will not guarantee that your data will be returned in any particular order.
Your variable will still refer to the index, not the actual value stored at that index.
Also see below comments about using this with arrays.
edit: for..in will return (at the least) added properties to the prototype of an object. If this is undesired, you can correct for this behavior by wrapping your logic in an additional check:
for(var x in object) {
if(object.hasOwnProperty(x)) {
console.log(x + ": " + object[x]);
}
}
Your example is a bit odd, but as this question is becoming the canonical "return from forEach" question, let's use something simpler to demonstrate the problem:
Here, we have a function that checks the entries in an array to see if someProp matches value and, if so, increments the count on the entry and returns the entry:
function updateAndReturnMatch(array, value) {
array.forEach(function(entry) {
if (entry.someProp == value) {
++entry.count;
return entry;
}
});
}
But calling updateAndReturnMatch gives us undefined, even if the entry was found and updated.
The reason is that the return inside the forEach callback returns from the callback, not from updateAndReturnMatch. Remember, the callback is a function; return in a function returns from that function, not the one containing it.
To return from updateAndReturnMatch, we need to remember the entry and break the loop. Since you can't break a forEach loop, we'll use some instead:
function updateAndReturnMatch(array, value) {
var foundEntry;
array.some(function(entry) {
if (entry.someProp == value) {
foundEntry = entry;
++foundEntry.count;
return true; // <== Breaks out of the `some` loop
}
});
return foundEntry;
}
The return true returns from our some callback, and the return foundEntry returns from updateAndReturnMatch.
Sometimes that's what you want, but often the pattern above can be replaced with Array#find, which is new in ES2015 but can be shimmed for older browsers:
function updateAndReturnMatch(array, value) {
var foundEntry = array.find(function(entry) {
return entry.someProp == value;
});
if (foundEntry) {
++foundEntry.count;
}
return foundEntry;
}
The function e() isn't returning anything; the inner anonymous function is returning its e value but that return value is being ignored by the caller (the caller being function e() (and can the multiple uses of 'e' get any more confusing?))
Because
function(e) {
return e;
}
is a callback. Array.forEach most likely calls it in this fashion:
function forEach(callback) {
for(i;i<length;i++) {
item = arr[i];
callback.call(context, item, i, etc.)
}
}
so the call back is called, but the return doesn't go anywhere. If callback were called like:
return callback.call();
the it would return out of forEach on the first item in the array.
You can use for...of to loop over iterable objects, like array, string, map, set... as per Mozilla docs.
const yourArray = [1, 2, 3]
for (const el of yourArray) { // or yourMap, Set, String etc..
if (el === 2) {
return "something"; // this will break the loop
}
}

Can a JavaScript function return itself?

Can I write a function that returns iteself?
I was reading some description on closures - see Example 6 - where a function was returning a function, so you could call func()(); as valid JavaScript.
So I was wondering could a function return itself in such a way that you could chain it to itself indefinitely like this:
func(arg)(other_arg)()(blah);
Using arguments object, callee or caller?
There are 2-3 ways. One is, as you say, is to use arguments.callee. It might be the only way if you're dealing with an anonymous function that's not stored assigned to a variable somewhere (that you know of):
(function() {
return arguments.callee;
})()()()().... ;
The 2nd is to use the function's name
function namedFunc() {
return namedFunc;
}
namedFunc()()()().... ;
And the last one is to use an anonymous function assigned to a variable, but you have to know the variable, so in that case I see no reason, why you can't just give the function a name, and use the method above
var storedFunc = function() {
return storedFunc;
};
storedFunc()()()().... ;
They're all functionally identical, but callee is the simplest.
Edit: And I agree with SLaks; I can't recommend it either
Yes.
Just return arguments.callee;
However, this is likely to result in very confusing code; I do not recommend it.
You can do what you want as following:
// Do definition and execution at the same time.
var someFunction = (function someFunction() {
// do stuff
return someFunction
})();
console.log(someFunction)
arguments.callee is not supported in JavaScript strict mode.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
Even sorter that all the above is:
f=()=>f
There is a simple way to achieve this doing the following:
let intArr = [];
function mul(x){
if(!x){
return intArr.reduce((prev, curr) => prev * curr)
}
intArr.push(x);
return mul;
}
console.log(mul(2)(4)(2)()); => outputs 16
It is also possible just to return the argument the self invokable function like
console.log( (function(a) { return a; })(1) ); // returns 1

Categories