Let's say I have a display function which I want to use it as follows:
display(min(1,10))
//expected output
min(1,10)
I am not able to get the name of the function and its parameters as is from the arguments object. I have started out like this.
function display() {
return arguments[0];
}
display(min(1,10));
//expected output
min(1,10)
//actual output
1
I understand that the min function is getting evaluated and its value is being taken as the first argument.
Short of wrapping the min function inside quotes, is there nothing we can do to get the passed function name and its parameters?
display('min(1,10)');
//expected output
min(1,10)
//actual output
min(1,10)
I understand that the min function is getting evaluated and its value is being taken as the first argument.
Correct.
Short of wrapping the min function inside quotes, is there nothing we can do to get the passed function name and its parameters?
No, nothing. By the time the value gets to display, there is nothing about it that associates it with where it came from (the result of calling min(1, 10)).
function min(a,b){
return 1;
}
function display() {
return arguments[0];
}
console.log(display(min));
min(1,10) will return the value first then it will go into display function.
Related
I am new learning the fundamentals. I have looked at many questions on here and youtube, and even on my udemy lecture. But none answer my question.
To be clear, my question is NOT how to use the return operator. I can use it perfectly well. The question is more to do with HOW it works, and what is actually happening in detail.
And please don't say "So in short, when we return something from a function, we are actually returning it from a function." - because this was one of the explainations I got before, and it does not explain anything to me hahaha :)
Here is the example code for this question:
function example(digit1, digit2) {
const sum = digit1 + digit2;
return `${sum}`
}
const invoke = example(1, 2);
console.log(invoke);
I think the best way to answer this question is to give me a step by step list of the journey that 'sum' makes. From the moment it is written, to the end of the whole code.
The return operator is clearly moving 'sum', as the word 'return' can only mean this, by definition.
When I read this code I see that 'sum' is inside the curly braces off the function, and then directly after this 'sum' is then RETURNED (to the place which it started). Now as 'sum' has not gone anywhere, returning it (to the place which it started) is REDUNDANT.
when the function is invoked there must be some kind of journey happening which I do not understand.
Thank you for your time :)
When I read this code I see that 'sum' is inside the curly braces off the function, and then directly after this 'sum' is then RETURNED (to the place which it started). Now as 'sum' has not gone anywhere, returning it (to the place which it started) is REDUNDANT.
Nope. You're misinterpreting what's "returning" and where it's being returned to.
The function is returning the value contained in sum to whatever called the function, not to "the place where it (sum) started".
function example(digit1, digit2) {
const sum = digit1 + digit2;
return `${sum}`
}
const invoke = example(1, 2);
console.log(invoke);
The function example receives two values which it places in the variables digit1 and digit2, then creates a new variable sum which contains the result of adding digit1 and digit2. (The variables digit1, digit2, and sum are all scoped to the function itself; they do not exist outside of that function.) It then returns the value contained in sum -- not the variable itself -- to the thing that called the function.
Which in this case, is this line:
const invoke = example(1, 2)
The function example receives the values 1 and 2, and returns the value "3". Which means that outside the function, the returned value takes the place of the function call itself, resulting in, effectively,
const invoke = "3"
The code outside the function "calls" the function. The function "returns" a value -- not a variable, a value! -- to the code outside the function. You can think of a function as a box with inputs and an output: you call it with inputs, and it returns to you an output value.
(Incidentally, the return statement you've used unnecessarily coerces the result into a string, where you probably want a number: just return sum would likely be preferable.)
return will put whats being returned (sum in this case) at the place where the function is invoked (in this case, in front of invoke).
so invoke = sum (sum is returned/ put on the place where the function is invoked)
The return statement below doesn't output anything or errors, any reason why?
I tried Chrome and Firefox and repl.it.
Here is the code I have:
//Create a function that uses a return statement
function multiply(num1, num2){
return num1 * num2;
}
//Call the function
multiply(10,20 );
I don't get any output or errors.
if you return something, it means it returns something. Right now, you only call multiply(), this function returns a value but you assign it to nothing.
If you use the following:
var returnValue = multiply(5, 10)
your returnValue variable contains the return value of the multiply function.
You don't get any output because you haven't done anything to generate output. You aren't getting any errors because there are no errors in your code. (It's okay to not use the return value of the function; in fact, it's quite common.)
Just returning a value from a function doesn't output it anywhere, it just returns it from the function so you can use it in the code that called the function. One thing you might do with it is output it, but you also might just use it for something else, like including it in a calculation:
function multiply(num1, num2){
return num1 * num2;
}
// Using the return value to output it:
console.log(multiply(2, 3));
// Using it in another calcuation...
const x = multiply(2, 3) + 4;
// ...the result of which we might output if we like:
console.log(x);
But again, you might never output the result of a function. For instance, this code uses the result of the function document.getElementById to set up an event handler. Doing that has no output at all:
let clickCounter = 0;
document.getElementById("btn").addEventListener("click", function() {
++clickCounter;
});
<input type="button" value="Click Me" id="btn">
Unless you're not showing us all of your code, it's because you are not returning the value to anything. Functions that return a value need to have that value used somehow in order for it to be visible. Some examples might be:
Using it as a parameter in another method call (e.g., logging it to the console):
console.log(multiply(10,20));
Setting it to a variable:
var result = multiply(10,20);
Using it as a value in another piece of logic:
document.getElementById("equation").textContent = "10 x 20 = " + multiply(10,20);
Without actively capturing and/or using the return value of a method, it will not be displayed anywhere.
I often do not understand how the value of certain function parameters is determined. Take the following code snippet for example:
function gotItAll(res) {
$('#actionscreen').modal('hide')
if (res.ErrorHtml != "" && res.ErrorHtml.substring(0,31) != "Error copying to sub data table") {
document.getElementById('GridView').innerHTML = res.ErrorHtml;
InfoMessage("Error", res.ErrorHtml);
} else {
if (res.BrowseTreeBreadCrumbs != null) {
//generateBrowseTreeHtml(res);
sessionStorage.setItem("browseTreeBC", res.BrowseTreeBreadCrumbs);
if (res.BrowseTreeBreadCrumbs.indexOf("-1") > 0 || res.BrowseTreeBreadCrumbs.indexOf("- -1") > 0 || res.BrowseTreeBreadCrumbs.indexOf("- -999") > 0 || res.BrowseTreeBreadCrumbs.indexOf("-999") > 0 || res.BrowseTreeBreadCrumbs.indexOf("-999") > 0 || res.BrowseTreeBreadCrumbs.indexOf("</b> </span") > 0) {
$('#breadCrumbsID').hide();
}
}
BaseTable = res.TableName;
recs = res.records;
'res' is a parameter that I could not find defined anywhere, yet it returns a value. I was not able to identify where gotItAll() is called and passed a value other than res. In addition, we have res.ErrorHtml, res.BrowseTreeBreadCrumbs.indexOf, res.TableName etc. that do not appear to be defined anywhere, yet they all return different values.
res is passed in from whatever calls gotItAll
The res.whatever are the attributes of the res object
The name res is just for use in that function, and will likely have a different name to what was used as the parameter.
Example
funciton addOneToNumber(numberToAddTo)
{
return numberToAddTo += 1;
}
function mainFunction()
{
var newNumber = addOneToNumber(1)
}
Edit:
You can use any object in javascript to be used as a parameter. In this case the function has been used. It also looks like failedCallback is also a function. Which would be called if the call to the server fails
Inside InventoryEditor.ItemEdit.AddNew somewhere, gotItAll is called with res which would of been a result of the server call from whichever type of call is made
The code snippet you posted is just the function declaration. Basically that snipper defines the existence of a function called gotItAll, which takes one parameter as the input. The parameter is called res, so inside the function, the word res refers to the parameter of the function.
Let's use a simple function as example:
function double(x) {
return x * 2
}
This function as a parameter as well, called x. Inside the function, you refer to it as x.
When you want to use the function, you call the function and you gave a parameter, such as:
double(2) // returns 4
double(4) // returns 8
double(7) // returns 14
As you can see, we can pass to the function double different values. When you call double(4), basically the function considers x = 4, and so everytime inside the function declaration you use x, you will be using the value 4 instead.
You can also pass different variables to the function:
var y = 10
double(y) // returns 20
Same as before, you give to the function the variable y, whose value is 10. So basically the program does x = y and everytime it refers to x inside the function declaration, it will be using the value of y.
Back to your example. I don't know what that function do, but basically res is the placeholder name of the parameter that will be passed to the function. That function can be called from around the code as gotItAll(variableName), and the function will be executed considering res = variableName. In the snipper you pasted, the function is only declared but there are not examples of actual usages of the function, that's why you can't see where res comes from.
EDIT: after your comment, I realized what you are actually referring to. Actually, in Javascript you can pass functions as the parameter of another function. Take for example the double function declared above. Now I want to create a function that doubles the number only if they are even. I can declare this:
function doubleEven(x, doublingFunction) {
if (x % 2 === 0) {
return doublingFunction(x)
} else {
return x
}
}
and I can use it as:
doubleEven(2, double) // returns 4
doubleEven(5, double) // returns 5
Basically, I pass double as a parameter to the doubleEven function. So, inside the doubleEven declaration, doublingFunction becomes equal to double and so it is a function.
Of course in this example this is silly, there is no need to pass a function for doubling a number. However this is used a lot in javascript to provide a callback to asynchronous task, such as a network request.
I have been dealing with issues in multiple pieces of code but it seems to boil down to what I’m showing in this demo. I think it is related to the ’s dereferencing of a closure:
function get_5(callback) {
var result = 5;
callback(result);
}
function get_self(x) {
return x;
}
get_5(console.log);
// 5
console.log(get_self(5));
// 5
In the first result, the first function ran as expected, sending its hidden variable into the input of the console.log function.
The second result also makes sense, as it really just proves the second function works: it takes what was fed in and returns it.
But things get strange when I try to combine the two functions:
var a = get_5(get_self);
console.log(a);
// Undefined!
This third result is undefined, strangely enough, and I am not sure why. Is the closure being dereferenced, maybe to the “sneakiness” of the get_self function? How can I fix this? As a bonus, is there a way to eliminate the get_self function entirely and be able to directly read the variable result, which isn’t modified, without specifying any particular callback?
get_5 has no return statement. It doesn't matter what you pass to get_5, it will always return undefined.
Perl will return the result of evaluating the last statement in a sub, but JavaScript will not.
If you want get_5 to return the result of calling the callback you pass to it, then you have to say so explicitly:
function get_5(callback) {
var result = 5;
return callback(result);
}
I wrote a simple function to sort objects not expecting it to work but it does:
function sortObjs(objArr,field) {
objArr.sort(
function(a,b) {
if( isNaN(a[field]) ) {
return a[field].localeCompare(b[field]);
} else {
return parseFloat(a[field]) - parseFloat(b[field])
}
}
);
return objArr;
}
When I call this function I get my sorted objects without issue. But I was not expecting it to work because I thought the first two return statements would exit the function before it got to the last statement: return objArr.
You have a nested function. The first two returns will exit the inner function, while the last one will exit the outer one.
EDIT:
You can think of function returns as "replacing" the function with the returned value. For example:
var i = getSum(1, 3);
function getSum(a, b) {
return a + b;
}
The function getSum returns the sum of a and b. The line var i = getSum(1, 3) will execute the lines of code contained in the function with a = 1 and b = 3. The value that is returned "replaces" the function call. So now the line of code looks like var i = 4;. Although this is not exactly how it works, it's a good way to conceptualize it. This is a special case because you aren't actually running the inner method here, you're passing it as a variable.
Let me know if you have any more questions!
To understand why the inner function's return statements would not have an effect on the return statement in the outer scope, you need to understand how the Array.prototype.sort() function works.
The function arr.sort([compareFunction]), takes a function as a parameter.
compareFunction
Optional. Specifies a function that defines the sort order.
If omitted, the array is sorted according to each character's Unicode code point value,
according to the string conversion of each element.
The logic you write inside the compareFunction gets executed when
the java script engine tries to compare two elements during its
comparison operation.
Hence for each comparison that it makes, the function would return a
value, based on which the elements would be ordered.
This implies that the compareFunction that we pass on as a parameter
would be used to just obtain a value based on which two elements can
be compared and not exit the sort operation, leave alone exiting the
outer function.
Having said this, the code return objArr;, takes no effect, since the array would be sorted in place.