2.6 - Maths in JS

News:

Cyber Patriot (Cyber Titan) Security Competition

Option cyber security competition opportunity - Click here to join! (last chance)

Review

Web browsers can run a scripting language called JavaScript. The syntax is very similar to C, C++, C#, Java, etc...

We learned about the console and printing to the console or screen with console.log() and alert().

Today's Lesson: 2.6 - Maths in JavaScript

Computers were designed to do mathematics quickly. Let's try!

  • + and - for add and subtract

  • * and / for multiply and divide

  • == "is it equal" (that is important)

  • != "is it not equal"

  • < > <= >=

  • ** for exponent: 4**2 -> 16

  • Cannot assume BEDMAS - it is important to utilize brackets (or parentheses) ( ) properly!

JavaScript also has a Math object to perform more complex operations.

  • Math.PI

  • Math.sqrt(number)

  • Math.pow(base, exponent) // same as **

  • Math.random()

  • So much more...

Today's Task

  • Open your Hello World REPL from last class (you should have an HTML "Hello World" REPL from 2.5)

  • We will reuse that REPL to output some math to the console.
    Each item should be a new "console.log". For Example:
    console.log(2 + 2); // will output 4
    console.log(5 * 7.1);
    // 35.5

  • Have your program output the correct answers to the following when you click RUN:
    6 + 5
    7 - 3
    3 + 4 * 2
    (4 / 2) + 3
    5 + 2 ** 3
    9 == 3 * 3
    5 == -5
    Math.round(6.4854)
    Math.PI

  • Spend some time playing around with the Math object and do more maths in JavaScript.

Extra

  • How can we get a random number between (and including) 1 to 100?

  • When you print Math.PI it gives a LOT of decimals. How can we round it to 4 decimals (3.1416) using Math.round()?