What does Return do in here? - javascript

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

Related

How can I understand the following javascript code which contains a function within function

I am learning javascript, and I am not able to understand the following piece of code.
const increment = (function() {
return function test(number, value) {
return number + value;
};
})();
console.log(increment(5, 2)); // output 7
My attempt at understanding
I removed the () on line 5, and then ran the following code.
const increment = (function() {
return function test(number, value) {
return number + value;
};
});
console.log(increment(5, 2));
This returns the output test(number, value) which I can understand. The increment variable points to the function test.
However, I don't understand how adding () passes the arguments (5,2) to test?
Said another way, if the output of the second code block is test(number, value), the output after adding () is test(number,value)() which seems meaningless.
It calls self-invoking.
If you write function like that (function foo(){})() then foo will be immediately called and result will be returned.
So as result in increment you have test function.
And then you call it with arguments.
increment(5, 2) // test(5, 2)
Here is some info about that
() at the end of the function immediately calls it - it's called IIFE ("Immediately invoked function expression").
When calling it with increment(5, 2) - you are actually calling the test function that is returned by the IIFE.
Your question is regarding the Javascript Immediate Functions.
First, we need to know what a function is, which is basically a block of code that returns a value.
And to declare a function in Javascript, one way is this:
function a() {
return "in this case, a string";
}
If we do:
const variable = function () {
return "in this case, a string";
};
console.log(variable); // Function
But Immediate Functions, as the name implies, are functions that are executed immediately after being defined, so, the value that the function returns is the value that will be given to the variable:
const variable = (function () {
return "in this case, a string";
})();
console.log(variable); // "in this case, a string"
About removing parentheses:
// This is
const increment = (function() {
return function test(number, value) {
return number + value;
};
});
// ...the same as this
const increment = function() {
return function test(number, value) {
return number + value;
};
};
We use parentheses just to isolate this expression (which is the function) and execute it right afterwards:
// Now the parentheses make sense,
// because we need it to execute the function right after it is defined
const increment = (function() {
return function test(number, value) {
return number + value;
};
})();
Read more about Immediate Functions here

JavaScript Functions , return undefined

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);

alert function in javaScript

Can someone help me to better understand why the second alert box appears with 'undefined' in it? When I call the function without alert function I don't see it.
var n = 1; // global scope
function one() {
alert(n);
}
alert(one());
alert(one()) alerts the return value of the function one. That function does not return a value, so its return value is undefined.
If you want to change the value of the second alert, you need to use return <value> from within one.
var n = 1; // global scope
function one() {
alert(n);
return 42;
}
alert(one());

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 JavaScript function always returns 'undefined' – and how to fix that?

I'm using phonegap with application preferences plugin and trying to make a helper function to get a value from it. However the function is not returning a correct value. I know this has to do with asynchronous thingy but unfortunately I don't know how to fix it. (I've tried to search help here, and found little, and tried to implement it in helper method)
What I want to achieve is:
function populateList() {
var a = 1;
var number = getSettingFromApplicationPreferences('number');
// number is always undefined
var letter = getSettingFromApplicationPreferences('letter');
// letter is always undefined
number = (number) ? number : 1;
letter = (letter) ? letter : 'b';
// Here I'll do some DOM manipulation and use 'number' and 'letter' on it, and
// define new variables based on 'number' and 'letter'
}
here's the helper function that I need help with:
function getSettingFromApplicationPreferences(setting) {
var x = (function () {
window.plugins.applicationPreferences.get(
// setting
setting,
// success callback
function(returnValue) {
console.log(setting + ': ' + returnValue);
return returnValue;
},
// error callback
function(error) {
alert("Failed to get a setting: " + error);
return false;
}
);
})();
return x;
}
Question
How is it possible to return the 'returnValue' from application preferences with that helper function?
The problem is, your callback doesn't actually set a value for x. So, you're going to have some other way to do whatever you're doing, because return values will not work.
You are using an asynchronous function incorrectly, you cannot assign like you are because the function hasn't returned yet and so you get an undefined. You need to use a callback function instead.
That means that inside the success function you would do whatever you need to do with the "returnValue".

Categories