Practice: Data Types and Arithmetic Operators

Try this exercise to practice writing statements using numbers, strings, and Boolean values. The code defines three variables (using the 'var' keyword) and uses assignment statements. Copy and paste the code into each program and run it to validate the output. You can use the Replit online editor at https://replit.com/languages/nodejs or any editor you choose. This exercise does not count towards your grade. It is just for practice!

Arithmetic

// This program demonstrates arithmetic operations.

var a;
var b;
    
a = 3;
b = 2;
output("a = " + a);
output("b = " + b);
output("a + b = " + (a + b));
output("a - b = " + (a - b));
output("a * b = " + a * b);
output("a / b = " + a / b);
output("a % b = " + (a % b));

// Display output to the current environment
function output(text) {
  if (typeof document === 'object') {
    document.write(text);
  } 
  else if (typeof console === 'object') {
    console.log(text);
  } 
  else {
    print(text);
  }
}


Output

a = 3
b = 2
a + b = 5
a - b = 1
a * b = 6
a / b = 1.5
a % b = 1


Discussion

Each new code element represents:

  • +, -, *, /, and % represent addition, subtraction, multiplication, division, and modulus, respectively.