Returning multiple values in javascript? - javascript

Is there a way to use a sort of the C#-like out or ref parameter modifiers with Javascript to do something like this:
function myManyReturnFunction(number1, number2, out x, out y) {
x = number1 * number2;
y = number1 / number2;
return true;
}
var height1, height2 = 0;
var check = myManyReturnFunction(1,1, out height1, out hight2);
I would like to change the variable's reference as well. So yes, passing an argument by reference.

function myManyReturnFunction(number1, number2) {
return {
x: number1 * number2,
y: number1 / number2
}
}
And you don't need x and y parameters, simply call:
var result = myManyReturnFunction(6, 9);
var x = result.x;
var y = result.y;

You can create an "object"...
function getObj(){
var objOut = new Object();
objOut.name = "Smith";
objOut.State = "Arkansas";
return objOut;
}

If you define the 'out' variables in the global scope outside if your function they can be reassigned inside the function with something like this:
var height1 = 0, height2 = 0;
function myManyReturnFunction(number1, number2) {
height1 = number1 * number2;
height2 = number1 / number2;
return true;
}
var check = myManyReturnFunction(1,1);
You can also create an object, which you can then pass to your function, which can be modified within the function like so:
var myValues = {}
function setValues(num1, num2, vals) {
vals.x = num1 * num2;
vals.y = num1 / num2;
return True;
}
setValues(1, 1, myValues);

There are several ways to return multiple values in JavaScript. You've always been able to return multiple values in an array:
function f() {
return [1, 2];
}
And access them like this:
var ret = f();
document.write(ret[0]); // first return value
But the syntax is much nicer in JavaScript 1.7 with the addition of destructuring assignment (if you're lucky enough to be targeting an environment guaranteed to support it (e.g. a Firefox extension)):
var a, b;
[a, b] = f();
document.write("a is " + a + " b is " + b + "<br>\n");
Another option is to return an object literal containing your values:
function f() {
return { one: 1, two: 2 };
}
Which can then be accessed by name:
var ret = f();
document.write(ret.one + ", " + ret.two);
And of course you could do something really horrible like modify global scope or even set properties on the function itself:
function f() {
f.one = 1;
f.two = 2;
}
f();
document.write(f.one + ", " + f.two);
More reading (and the source of some of these examples):
https://developer.mozilla.org/en/New_in_JavaScript_1.7#Destructuring_assignment_(Merge_into_own_page.2fsection)

You can return non-primitive types:
function blah() {
return { name: 'john', age: 23 };
};
var x = blah();

Related

Getting undefined value when trying to use with inner functions

Following is my code snippet :
function executorFunc(input){
return input();
}
function mainFunc(){
var a = 100;
function innerFunc(){
var b = 20;
return a + b;
}
executorFunc(innerFunc);
}
var finalVal = mainFunc();
console.log(finalVal);
I was in the assumption that innerFunc gets created within mainFunc and will be aware of outer/enclosing functions data like a = 100. To my surprise, it's not. There is something that is doing it wrong or there is something which I have misunderstood in basics of JS.
The final output is undefined where I was expecting 120.
Expected result as you are not returning the value from mainFunc function().
Use
return executorFunc(innerFunc);
function executorFunc(input){
return input();
}
function mainFunc(){
var a = 100;
function innerFunc(){
var b = 20;
return a + b;
}
return executorFunc(innerFunc);
}
var finalVal = mainFunc();
console.log(finalVal);
The problem here is that mainFunc does not return any value. So finalVal remains undefined.

What's the best way to allocate the variables with multiple combinations

I want to reduce the initialization of multiple combination variables.
My aim is to create a function and pass a function with variable.
If I pass a variable x into function value(x); I should get output as "123". Similarly, if I pass a variable xy into function value(xy), then I should get output as "123456". Basically, I want to concatenate variables
Here is the javascript code as
var x = "123";
var y = "456";
var z = "789";
var a = "0-+";
var xy = x + y;
var yz = y + z;
var zx = z + x;
var xa = x + a;
var ya = y + a;
var za = z + a;
var ax = a + x;
var ay = a + y;
var az = a + z;
var xz = x + z;
var yx = y + x;
var zx = z + x;
var zy = z + y;
var xyz = x + y + z;
var xyza = x + y + z + a;
function value(input) {
console.log(input);
}
Sample execution as follows:
value(x); //output: 123
value(y); //output: 456
value(xy); //output: 123456
value(za); //output: 7890-+
In this case, there are lots of combination for the above variables i have defined to meet all possible combinations. I want to validate the user input from the above combination and also i dont want to write so many variables. Is there any possible easy solution ?
Please suggest. Thanks
I would declare a global object to store the variables as keys:
var globals = {
"x": "123",
"y": "456",
"z": "789"
};
Note that you can refer to your "variables" by globals.x, or globals.y (you can replace globals with a shorter keywork to reduce code of course).
It is a little extra effort to define the "variable names" with quotes.
However, now you get to use:
alert(Combinate("xz"));
// output: 123789
With a function like:
function Combinate(phrase) {
result = "";
for (var i = 0, len = phrase.length; i < len; i++) {
result += globals[phrase[i]];
}
return result;
}
Here's a JSFiddle.
You'll want to use some form of iterating over an array or object. As an example:
var x = "dave";
var y = "bill";
var z = "john";
var a = "suzan";
var people = [x,y,z,a];
for(i=0; i<people.length; i++) {
for(x=0; x<people.length; x++) {
value(people[i] + people[x]);
for(y=0; y<people.length; y++) {
value(people[i] + people[x] + people[y]);
for(z=0; z<people.length; z++) {
value(people[i] + people[x] + people[y] + people[z]);
}
}
}
}
// not sure why you'd have a function to wrap console.log(), but...
function value(input) {
console.log(input);
}
See in action on jsFiddle.
There are more elegant paths, but this should get you on the road to learning about JavaScript.

How do I call this function in JavaScript?

I am trying to call this function in Javascript but it wont work.
eval("function f() { return x + 1;}")
I called it by typing function f(12);
If you MUST you eval.. you should give x to the function as a parameter. So it should be :
eval("function f(x) { return x + 1;}")
But you could just write it as:
function f(x) {
return x + 1;
}
eval() in javascript
The eval() function evaluates or executes an argument.
If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.
var x = 10;
var y = 20;
var a = eval("x*y") ;
var b = eval("2+2") ;
var c = eval("x+17")";
var res = a + b + c;
Output:
200
4
27
Create your function like this:
function f(x) {
return x + 1;
}

javascript scope : retain global variable value after a function

When the 'hypotenuse' function is called the value of 'x' changes from 1. Fix it so that 'x' is still 1 in the gobal scope.
var x = 1;
var y = 1;
function hypotenuse(a , b) {
var cSquared = a * a + b * b;
x = Math.sqrt(cSquared);
return x;
}
hypotenuse(x, y);
All you need to do to make this happen is redeclare the x variable using var within the function. This is will declare the x variable within the scope of the function, leaving the original, globally scoped x variable untouched:
var x = 1;
var y = 1;
function hypotenuse(a , b) {
var cSquared = a * a + b * b,
x = Math.sqrt(cSquared);
return x;
}
hypotenuse(x, y);
Or, using the code style which you originally adopted (splitting out var declarations):
var x = 1;
var y = 1;
function hypotenuse(a , b) {
var cSquared = a * a + b * b;
var x = Math.sqrt(cSquared);
return x;
}
hypotenuse(x, y);
For more detailed info on what is happening here, read up on javascript scope
Try this:
var x = 1;
var y = 1;
function hypotenuse(a, b) {
var cSquared = a * a + b * b;
var x = Math.sqrt(cSquared);
return x;
}
//console.log(hypotenuse(x, y));
//console.log('x = ' + x);

If I have a variable, assigned to the value of a function call, can that variable be updated if the function call's parameters are changed?

If I have a function, like this:
function f(x,y){
return x + y;
}
And if I have variables of parameters I want passed to f:
var parameter1;
var parameter2;
If I assign this function call to a variable:
var functionCallValue = f(parameter1,parameter2);
How can I ensure that functionCallValue changes depending on different values I assign to the variable parameter1 and parameter2?
I suppose what you need is a closure.
var servant = function(x, y) { return x + y; };
var param1 = 40;
var param2 = 2;
var master = function() { return servant(param1, param2) };
var result = master(); // 42.
param1 = 2;
param2 = 40;
var anotherResult = master(); // still 42, because that's really the answer!
functionCallValue is assigned the result (returnvalue) of your function f. (The function is called, the value calculated and the result handed over to your variable.) Thus functionCallValue does not automatically update, if you change the parameters (which would make no sense at all), you need to call the function again with the altered parameters.
For something like an auto-update you need a closure like this:
var asdf = (function(){
var param1 = 1;
var param2 = 2;
var result = param1+param2;
function compute(){
result = param1 + param2;
}
return{
param1:function(x){
param1 = x;
compute();
},
param2:function(x){
param2 = x;
compute();
},
result:function(){
return result;
}
}
})();
console.log(asdf.result()); // logs 3
asdf.param1(3);
console.log(asdf.result());​ // logs 5
Demo

Categories

Resources