LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Javascript, conditionals, higher-order functions (https://www.linuxquestions.org/questions/programming-9/javascript-conditionals-higher-order-functions-897506/)

tinyTux 08-15-2011 07:54 PM

Javascript, conditionals, higher-order functions
 
Hi. I'm playing around with Javascript until my book arrives. I was in the process of writing this small program as part of an on-line practice exercise:
Code:

function sum(a, b) { return a + b }

function difference(a, b) { return a - b }

function product(a, b) { return a * b }

function quotient(a, b) { return a / b }

function dispResult() {
  // put form values into variables
  a = window.document.calcform.a.value
  op = window.document.calcform.op.value
  b = window.document.calcform.b.value
  c = window.document.calcform.b.value

  // idea is to make opfunc a reference to a function
  // that I can pass on to some other function later on
  // (higher-order style)
  opfunc = if (op == "+") { sum }
            else if (op == "-") { difference }
              else if (op == "*") { product }
                else if (op == "/") { quotient }
                  else { null }

  // other code will go here eventually
}

However, the compiler will not accept the first if statement. Question: do Javascript conditionals return values? If not, what would be the most similar working syntax to the above?

ButterflyMelissa 08-16-2011 03:42 AM

I dont see semi-colons...according to what I recall, statements should end with a semi-colon...

Quote:

function sum(a, b) { return a + b }
should probably be:

Quote:

function sum(a, b)
{
return a + b;
}
Or, the way I'd write it:
Quote:

function sum(a, b)
{
c = a + b;
return c;
}
...but, that's my style... :)

Luck

Thor

ntubski 08-16-2011 10:42 AM

Javascript uses C-style syntax so statements cannot return values. You can use the ternary operator (which works the way you want if to work) though:
Code:

var opfunc =
    (op == "+")? sum :
    (op == "-")? difference :
    (op == "*")? product :
    (op == "/")? quotient :
    null

I think using an associative array/object would be a better idea:
Code:

var funcs = {"+": sum, "-": difference, "*": product, "/": quotient}
var opfunc = funcs[op]



All times are GMT -5. The time now is 07:58 PM.