Arithmetic in Sheet Workers

There’s a lot you can do with JavaScript, but you are usually concerned with one thing: updating an attribute value. For that, you need to be able to do two things: perform arithmetic and work with strings. We’ll deal with arithmetic in this post. But we’ll touch on a few more advanced things too.

In Anatomy of a Sheet Worker, we learned how to collect attributes, and we learned a bit more about how to Create Variables, and the difference between Numbers and Strings. Now we can do some stuff.

Doing Stuff

The simplest thing is to perform arithmetic of various sorts. Here are some different calculations:

const move = dex + agl;
const move = dex *2 + agl;
const move = (dex + agl) *2; 
const move = dex/10 + agl/10;Code language: JavaScript (javascript)

You can add (+), subtract (-), multiply (*), divide (/), and more. But addition and division are usually all you need. But you also can do this:

dex += 5;
agl -= dex;Code language: Markdown (markdown)

The +-, -=, *=, and /= syntaxes are shorthand. Instead of typing this:

dex = dex +5;Code language: Markdown (markdown)

you can simply type:

dex += 5;Code language: Markdown (markdown)

Whenever you find yourself altering a value, you can use syntax like += or *=. Javascript knows that you are modifying the original value by the modifier.

There is a difference between += and =+, but it’s very subtle and pretty much always irrelevant in sheet workers, so you can ignore it and use either order.

Conclusion

In this post, we described how to perform simple arithmetic. In the next post, we’ll cover conditional calculations – using if statements. You’ll find these very, very useful.

Series Navigation<< Variables – How to Name ThingsWhat If? in Sheet Workers >>

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.