Javascript Calculator Function: How does it work? - javascript

I'm going through some tutorials and saw this block of code that I can't figure out. Can someone walk me through it please? I don't understand how the return ultimately executes the variable function.
var plus = function(x,y){ return x + y };
var minus = function(x,y){ return x - y };
var operations = {
'+': plus,
'-': minus
};
var calculate = function(x, y, operation){
return operations[operation](x, y);
}
calculate(38, 4, '+');
calculate(47, 3, '-');

operations is an object that has + and - as keys, so by passing one of those to it you will get
operations['+'] = plus
Now, the brackets indicate a function call which can also be made via a variable as in this case. So translated the return statement is nothing more than
return plus(x,y);
var calculate = function(x, y, operation){
return operations[operation](x, y); // operations['+'] = plus
}
Which calls above method and returns the value returned by that method.

Explanation
Look at my comments for an explanation.
var plus = function(x,y){ return x + y }; //-- var plus contains this function now.
var minus = function(x,y){ return x - y };
var operations = {
'+': plus, //-- This states that '+' contains the plus function.
'-': minus //-- This states that '-' contains the minus function.
};
var calculate = function(x, y, operation){ //-- operation makes it able to select a function from operations.
return operations[operation](x, y);
}
calculate(38, 4, '+'); //-- The '+' selects the plus function here.
calculate(47, 3, '-'); //-- The '-' selects the minus function here.

Executions will be something like this:
First argument is being passed as a key of the object and respective function is executed with arguments..
var calculate=function(x, y, operation)
{
//operations['+'](38, 4);
//operations['-'](47, 3);
return operations[operation](x, y);
};

Related

What is going on with this JavaScript code?

Sorry I am new to Programming so I was unable to ask a more specific question. I find this code really confusing. I'm learning about callbacks.
function add(x, y, callback) {
callback(x + y)
}
function subtract(x, y, callback) {
callback(x - y);
}
function multiply(x, y, callback) {
callback(x * y);
}
function calculate(x, callback) {
callback(x);
}
calculate(5, (n) => {
add(n, 10, (n) => {
subtract(n, 2, (n) => {
multiply(n, 5, (n) => {
console.log(n); // 65
});
});
});
});
Essentially all this script does is the following ((5 + 10) - 2) * 5. Which returns the sum of 65. It just does that with extensive use of callbacks.
All function you have has a callback, this means each function can call a another function if that function is defined,. side note: otherwise it gives an error.
function subtract(x, y, callback) {
callback(x - y);
}
This function take in three values:
x equals A number
y equals The number that x will be minused with
callback = The function to run at the end
Let's just run that function and put in an anonymous function with a console.log
subtract(15, 2, function (x) {
console.log(x);
// x = 13
});
Let add another layer to that same function by calling it twice.
subtract(15, 2, function (x) {
subtract(x, 2, function (x) {
console.log(x);
// x = 11
});
});
That is how everything works, it is just nested functions over complicating basic math.
This is a JS callback example:
In JS, just like a value one can pass a function to another function;
So, if you want to simplify what is going on here, in the calling part -
var calculateVal = calculate(5); // result is 5
var addedVal = add(calculateVal, 10); // result is 15
var subtractVal = subtract(addedVal, 2); // result is 13
var multiplyVal = multiply(subtractVal, 5); // result is 65 ; your end resullt

I am trying to get the addition value of using return function but not getting | Could you help to me what exactly I am doing wrong?

I am trying to get the added value of using return function.
var x, y;
function test(x, y) {
x = prompt("Enter a number");
y = prompt("enter another Number");
return (x + y);
}
test();
.prompt() returns a string. You need to convert that to a number with something like parseInt() or parseFloat() etc:
var x, y, result;
function test(x, y) {
x = parseInt(prompt("Enter a number"));
y = parseInt(prompt("enter another Number"));
return (x + y);
}
console.log(test());
If you want to save x and y values to your predefined variables, just remove them as arguments from test function - then it will use your predefined ones:
var x, y, result;
function test() {
x = parseInt(prompt("Enter a number"), 10);
y = parseInt(prompt("enter another Number"), 10);
return x + y;
}
console.log(test(), x, y);
Also as #j08691 suggested, you should convert results of prompt to number first before making the sum.

How to add parameters to a function argument without calling it

For example, addEventListener's 2-nd argument has a "e" or "evt" or "event" or "..." parameter. How can I add parameters to a function argument without calling it (without using arguments object). Is it possible?
Sorry for my bad english :)
You are looking for partial functions.
You can create functions with arguments and not provide them. For example,
function add(x, y) {
return x + y;
}
console.log(add(1, 2)); // 3
console.log(add(2)); // NaN (2 + undefined)
console.log(add(0)); // NaN (undefined + undefined)
If you don't want the function to return value like NaN, you can write this:
function add2(x, y) {
x = x || 0;
y = y || 0;
return x + y;
}
console.log(add2(1, 2)); // 3
console.log(add2(2)); // 2
console.log(add2(0)); // 0

How to Put a function with two parameters in a Array (JavaScript)?

I have:
function val(a,z){
return a/2, z+8;
}
val(3,4);
Put this result:
x = 1,5
y = 12
in a Array;
[x,y];
Thanks.
If you want to return multiple variables in an array then just add [] to your return statement.
function val(a,z){
return [a/2, z+8];
}
//then , the first array element is the x, second one is y
//var a = val(4,6)
//a[0] = 2 <- x
//a[1] = 14 <- y
Try to return as object
Like this
function val(a, z) {
return {
x: a / 2,
y: z + 8
};
}
var data = val(3, 4);
console.log(data.x);
console.log(data.y);

can two variables operated equate to a constant in JavaScript?

I need to have two variables, x and y, and an equation involving both that always equals one.
This is a simple example. This example may be easy to define in terms of y, like y = 1/x, but I have another equation I need to use, and it is too hard to define in terms of y.
var x, y;
x*y = 1;
x = Math.random()*20;
console.log(y);
I would get an error message for this, like
Uncaught ReferenceError: Invalid left-hand side in assignment (line 2)
a variable could be defined as x*y, like var z= x*y, but apparently not a constant. Maybe there is some way around this, like defining two variables, one as the constant and the other as the equation and finding some way to relate them? Maybe javascript's looseness will allow for some new technique?
Thanks ahead of time! :)
You can't do this directly. The value of x depends on the value of y. You must describe their dependency.
You can do something like:
var x_y = (function () {
var x = 1, y = 1;
return {
set_x: function (new_x) {
x = new_x;
y = 1 / new_x;
},
set_y: function (new_y) {
y = new_y;
x = 1 / new_y;
},
get_x: function () {
return x;
},
get_y: function () {
return y;
}
};
}());
x_y.set_x(Math.random()*20);
console.log(x_y.get_y());
So essentially we're saying x = 1 / y; and y = 1 / x; and we couple the values: if you change one, the other changes as well.

Categories