Math with Javascript

You are trying to make the graphic above to celebrate having a success first two weeks at Hogwarts but you are running into some problems. You can’t get the lettering to look right and your rectangles aren’t lining up right. You have variables for your rectangle width and height, 100, and 135 respectively, but how do you use them to their fullest potential? Using math in Javascript can help solve these types of problems.

Adding and Subtracting

Adding and subtracting work just like they do on paper. Use + or – do add or subtract number or variables. You can also use math in your text codes, as shown in Text and Variables. You can use adding and subtracting when defining variables. If you wanted to change the rectangle width variable to 100 less than the height, you could write rectW = rectH – 100;. Or if you wanted to make the width 100 more than the height, you could right rectW = rectH + 100;. Just like on paper, the order of your addition doesn’t matter, but the order for subtraction does.

Multiplying and Dividing

To multiply two things use the * sign and for division use /. For example, for my x and y coordinates, I multiplied the rectangle width or height by the number of rectangles it will be over or down. For my letter size,  I divided the rectangle width by 4. This made my rectangles line up exact and my letters to fit in each rectangle. These also work just like on paper, just with different symbols.

All of these can be used in variables, coordinates, and sizes. Using math and variables together it can make moving and changing things around a ton easier. Math also saves you from making more variables than are necessary.

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *