“I could never learn to code– I hated math in high school.”
That’s one of the most common things I hear from people when I mention how surprised I was (am?) that I ended up being a professional computer nerd for a living.
Even for the people I talk to who are open to the idea of learning how to code (if only for the variety of doors and opportunities it will open for them if not for the fun of coding itself), they still find the idea of doing math professionally a
somewhat extremely daunting and unpleasant prospect.
The good news: you don’t have to be Einstein, Oppenheimer, Feynman, or any other world-renowned mathematician or physicist to be a software engineer.
The bad news: you will probably have to brush up on some basics up through algebra (and possibly geometry, if you end up getting into front-end data analytics visualizations). So if this was you after your last math class ever…
…I just want you to know that I’m laughing at you a little bit 😝
In my last post, we covered basic data types and printing to the console, which will be your new best friend for a little while. For obvious reasons, mathematical operators in code are primarily used to manipulate data in the form of numbers, but as we’ll see shortly, they can also be used to mutate strings.
In the following examples, we’ll be using the mathematical operators inside the console.log function, which will print the result to the console (denoted by the comments). It should be pretty straightforward:
console.log( 2 + 4 ); // 6 console.log( 4 - 2); // 2 console.log( 2 * 4); // 8 console.log( 4 / 2); // 2
Side note: you can use the + operator on strings, like so:
console.log('I have the ' + 'best cat.'); // 'I have the best cat.'
These are really useful for rounding non-integer numbers up, down, or whichever is closest:
Math.floor(3.5234); // 3 Math.ceil(4.5902); // 5 Math.floor(-1.3902); // -2 Math.ceil(-3.4992); // -3 Math.round(3.4); // 3
There is also a method for randomly producing a value between 0 and 1.
Math.random(); // returns something between 0 and 1
One important operator that you may not be familiar with from grade school math class is called the modulo. Its symbol is the % sign. What it does is return the remainder of one number divided by another. Examples:
console.log( 5 % 4 ); // 1 console.log( 28 % 2 ); // 4 console.log( 10 % 5 ); // 0
Note that dividing 10 by 5 has no remainder at all, since 5 goes into 10 exactly twice.
Questions, comments, and constructive/corrective feedback always appreciated.