3

some tricky javascript tests

Here are the answers:

  1. a = 0, b=2;
    a– == 0 is false, because the “a” is returned before the calculation “–“, as (a–==0) is false, the next part of comparison is cancelled. So b still has value 2, but a becomes 0
  2. one possible answer:
  3. undefined
    see var hoisting
  4. true, false, true, true
    depending on position of decrement/increment operator, the returned result is different.
    ex:
  5. function
    same as variable hoisting, function declaration is hoisted as well.
  6. == operator trys to do the type coercion before comparison (regardless of type), but === compare both type and value.
  7. ref: Floating Point Basic

Darktalker

3 Comments

  1. For #2, obeying the priority of operators, shouldn’t the value of -5+2*2 be -5+(2*2), i.e. -1?

  2. To make it work properly you need to create the whole equation as a string and eval it all at once, then js will sort out the order of operators itself. So you want something like

    var equation=’0′;
    for (var index in t) {
    equation+=t[index][0]+t[index][1];
    }
    return eval(equation);

  3. in fact, the caculation should be step by step like a real calculator, the question asks you to do like this:

    //step 1
    var result = -5+2;
    //step 2
    result = result * 2;

    at first, I didn’t understand the question neither 🙂

Leave a Reply