Answer the question
In order to leave comments, you need to log in
JavaScript How to pass one of the parameters to a function - an object?
Prompt how to transfer object as parameter f-ii and how the call looks.
Task:
Write a calculator function for adding positive numbers, which takes 3 parameters: the first number, the second number, the name of the operation (plus, minus, multiply, divide).
Answer the question
In order to leave comments, you need to log in
function calc(x, y, operation) {
var operations = {
plus: function(x, y) { return x + y },
minus: function(x, y) { return x - y },
multiply: function(x, y) { return x * y },
divided: function(x, y) { return x / y },
}
return operations[operation] && operations[operation](x, y);
}
calc(10, 20, "plus"); // 30
Could it be something else like this:
function calc(a, b, operation) {
if(['+',' -', '*', '/'].indexOf(operation) < 0) {
throw new Error('invalid operation');
}
return eval(parseFloat(a) + operation + parseFloat(b));
};
calc(5, 2, '*') //10
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question