JavaScript Addition Calculator Help

Here is the code that creates the add variable and passes it to the update function.


var add = function (c, d) {
    return c + d;
};
update(add);

That could also be done without creating the add variable, by passing the function directly to the update function.


update(function (c, d) {
    return c + d;
});

In both cases, the function that does the adding is an anonymous function.
The anonymous function is created by using a function expression, which is different from the typical functions that you normally deal with which are created by using a [url=“https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/function”]function statement.

Here is a function created using the function statement, and one created using the function expression.


// function statement
function foo(bar) {
    ...
}

// function expression
var baz = function (bat) {
    ...
};

When I used the term “object” before, that is only because everything in javascript is an object. The window object and the document object you already know about, but strings, numbers, and functions are also treated as objects.

When I referred to the func object that’s in the update function, it’s was purely to refer to the variable called func, which contains the anonymous function that we created to add numbers.

The reason why the func object contains a function to add numbers, is so that you can pass different functions in to the update function to perform subject, divide, multiply, square roots, x to the power of y, and so on.

I’m wondering again about parsInt vs Number. I cant find it anymore but didn’t I read somewhere that as far as penalties etc go, we want to avoid using Boolean changes like that?

Correct. Number() return 0 for the boolean “false”, 1 for the boolean “true” and the number of seconds since the epoch for Date objects.
parseInt returns NaN for all these cases and would therefore be more semantically correct for this script.

you want to avoid using default operators when anything falsy might be considered a valid value.

For example:


// default to -1 on an invalid value
var x = parseInt(someValue, 10) || -1;
// but what if someValue is 0 ?

The above will incorrectly default to -1 when you use the value 0, which may not be what you intend.

In situations like that where you don’t want a falsy value to be considered false, you need to become more explicit about your conditions.

Are you suggesting that he will be more appropriately served by his calculator script by using parseFloat(value, 10) and checking it through isNaN ?

Yes, because that’s the semantically correct the way to do it.

  • parseFloat() instead of Number() for the reasons I described in my previous post (#23)
  • isNaN() instead of the default operator for the reasons described by you in post #24

And because the default operator works differently in languages other than JavaScript. For example in PHP:


$b = $a || -1; // $a is not defined, so it's null

We would expect $b to be -1, but the output is “true”, since PHP treats this as the logical result of ($a || -1) and not, like javascript ($a) || (-1).
I’m not saying you shouldn’t use the default operator, I’m saying you should not expect it to work the same across different lanuages, which makes it somewhat tricky.

So instead of


var c = Number(cInput.value) || 0;

this is to be done instead.


var c = parseFloat(cInput.value);
if (isNaN(c)) {
    c = 0;
}

Is there any improvement that can be made on that?

Perhaps this?


var c = parseFloat(cInput.value, 10) || 0;

Despite the OR operator appearing weird to someone who’s used to PHP, in JavaScript the Default Operator and Guard Operator serve as well known and highly recognisable coding patterns. I would not want to throw out the baby with the bath water, and when push comes to shove I appeal to a higher authority, and side with Douglas Crockford on such matters, which you may see in a recent presentation near the end of Crockford on JavaScript – Chapter 2: And Then There Was JavaScript

Yes, that works, looks elegant, and is semantically correct.

I was just warning people for the use of the default operator in other languages. I’ve had some long debugging-sessions in PHP only to find out that OR doesn’t work as a default operator there and I wanted to spare other people that hassle! :slight_smile:

I’d just like to point out that the default operator is yet another reason why JavaScript is so nice, neat and elegant and PHP is pretty ugly and clunky.

Off Topic:

Paul, who would you rather meet - Crockford or Pratchett?

Off Topic:

That would have to be Pratchett - his works demonstrate that he has a wide-range of knowledge that covers many different domains.

parseInt is basically a function for extracting a number from the front of a text string. The number can be in any number base from 2 to 36 and will be converted to work internally as binary and to display as decimal once the conversion takes place.

the second parameter into the parseInt is a value between 2 and 36 identifying the number base of the number in the text string.

If no second parameter is supplied then base 16 will be assumed if the text string starts with ‘0x’, base 8 if it starts with ‘0’ and base 10 (decimal) if it starts with a number between 1 and 9.

The parseInt will stop extracting when it reaches a character that is not a number in the number base it is using.

For example

parseInt(‘z’,36) returns the number 35.
parseInt(‘3’,2) returns the number 0 because a 3 isn’t a number in base 2 (where only 0 and 1 are numbers)
parseint(‘09’) will return 0 because 9 is not a number in base 8 and the leading zero without a second parameter tells it that the number is octal not decimal.

The Number() function doesn’t work with number bases and doesn’t discard non-numeric content. Instead it returns NaN if the string contains anything anywhere that can’t be interpreted as a decimal number.

So you’re saying Number() is a looser woman. That’s fine, it’s more that I thought JS was particularly slow with some things… like, I do remember where I read that using bitwise operators in JS was slow because of its interpreted-ness (that it had a fat layer between your commands and raw bit crunching) (Rhino book).

hexatridecimal… is waaaya over my head. I’m ok with spatial stuff but somehow I still suck hard at geometry. I guess you’d use that in animation? : )

Number() is intended for converting other data types into numbers (assuming they contain something that can be interpreted as a number).

parseInt() also returns a decimal number but is a lot more flexible on what it can read in.

The shortest way to convert a field to a number is to use the unary + operator to do it.

var num = Number(numstr);
var num = +numstr;

both of these do exactly the same thing.

Off Topic:

No, you’re using it every day yourself!
Colors in CSS are also like ffffff for white, which is actually 16-16-16-16-16-16, as f = 16 in hexadecimal.
(Unless you use rgb() to define colors in CSS of course, in which ignore this post :))
And I’ve never heard about hexadecimal for animation. Animation is all about floating point calculations.

Off Topic:

But all I do is memorise all those hex numbers… I can’t tell you where on a round wheel they’re sitting! It’s just easier for me to memorise them all than try to figure out what numbers give me what colours…
And you can use them to mark a position on a round wheel… why I figured animation.

Wow, sorry for the extremely late reply and all that! :eek:

Hmmm, I see. Kind of. I think 60% understood and 40% not-understood. I’m sure I’ll understand it all after reading through it a few times though. Thanks for the explanation. :tup:

Basically I lost everyone here when you all started going on about ParseInt versus Number(). Seeing as this is a JavaScript Calculator, and it’s in the JavaScript forum, and I’m an aspiring Front-End Web Developer - Can we stick to optimisation for this as a stand-alone JavaScript Calculator, please? It doesn’t bother me if it would be best to use a coding pattern that works best for JS and PHP. I want to optimise it as JS alone. Cheers.

So with that in mind, and the code that I currently have for the JS Calculator, how else could this script be optimised for speed, reliability, and semantics (didn’t know JS was semantic)? Also, the current JavaScript doesn’t validate with JSLint, I’d like it to though :slight_smile: Well, I need it to.

Thanks again for the help so far, and I think that if we keep the participation in this thread going to the point where we have a completed, JSLint validated, speedy, and reliable JavaScript Calculator we’ll also be able to get to another point that I want to see happen :smiley:

Andrew Cooper