JavaScript Variables & Arithmetic

This week we focused on variables and doing basic arithmetic in JavaScript. Initializing and declaring a variable is simple, but I found that while I was writing practice programs, it was easy to forget to initialize properly by using the term “var.”

Incorrect (unless x has already be initialized):

x = name;

Correct (initializes a variable named x and assigns a value):

var x = name;

One interesting thing to note about JavaScript variables is that you don’t have to declare the type, which is automatically determined based on the content assigned to the variable.

Besides knowing the basic arithmetic operators, assignment operators, and increment and decrement operators, doing math in JavaScript requires a good understanding of the mathematical order of operations, or operator preference. I have always enjoyed algebra, so I’m pretty good with operator preference, although in JavaScript you have to be a little more careful in constructing equations.

Also, some mathematical computations require the use of the Math object, which can take certain reserved JavaScript constants or functions. For example, to do exponentiation you can’t simply use the caret (^) symbol like this:

var x = 3 ^ y;

Instead, you have to use the Math object like this:

var x = Math.pow(3, y);

One skill that we practiced quite a bit this week was doing desk checks. This is a way to manually work your way through a program by hand to follow the value of variables as they are assigned or changed. I’m not sure at this point if it is a practical skill for programming, but I do know it helped me understand what was happening with within the code as I ran examples.