Math is the basis of computer science. We looked at strings first but that's only because we're used to typing words and sentences. Also, we learned about output. What about numeric variables?
Statically-typed (or strongly-typed) languages like C++ do not have active memory management. It is up to the programmer to know and declare the exact type of variable (memory space) required. This is because a number without decimals (
integer) takes less memory than a number with decimals (
Any sort of mathematics can be done in most programming languages. It is up to the programmer to learn the built-in mathematics as well as to create any new required computations. Here are the basic mathematical commands available. Assume
xhas a value of
let x = 19;)
Computers and programming languages do their best to follow proper order of operations for mathematics. That being said, the interpreter or compiler can only interpret your code as best as possible. For this reason, it's important to utilize brackets (or parentheses)
1 + 8 / 2is quite different from
(1 + 8) / 2.
Assigning a numeric value to a variable is straight-forward. Any math that is done must also be stored, either in a new variable or back into the current one. The list below is an incomplete list of the ways you can assign a value to memory.
There is a standard in programming that the variable or item being used to contain data is on the left of an operator and the mathematics or item(s) being assigned to that variable is on the right.
x = 5will assign 5 to the variable x while
5 = xwill throw an exception because it is not possible to store x into the value 5. This becomes important when comparing two items (see below). You can not use a single
=to compare, it assigns.
In order to make decisions we must be able to compare values. Comparisons typically return a
false. Below is an incomplete list of the ways you can compare two or more values.
It is easy to confuse the terminology or logic with the operators
>=. You should be reading it from left-to-right. Here are some examples:
4 < 10is read "four is less than 10"
100 > 6is read "one hundred is greater than six"
someVariable >= 0is read "some variable is greater than or equal to 0
x <= yis read "x is less than or equal to y"
When a variable is created in memory, it has no value. It has a name, but the variable itself has not been defined.
let x = 3; // Has the value 3
let y; // Has no value, specifically it has no definition
console.log(x + "\n" + y)
NaNwhich represents "Not a Number".
You can check to see if something is a number:
let myNumber = 3;
let myString = "Hello";
isNaN(myNumber); // false
isNaN(myString); // true
/* Remember, to print those results, use console.log()
and to store them, you need a variable:
let result = isNaN(myString); */