Back

Activity 1.8 Intermediate Data Types and Operations

divider

Introduction

Activity 1.8

Intermediate Data Types and Operations

Topics

  • Escape Sequences
  • Constants
  • Compound Assignment Operators
  • Increment and Decrement Operators
  • Math Constants and Functions

Escape Sequences

An escape sequence is a special combination of characters that tells a computer to do something other than what those characters normally do.

In JavaScript, an escape sequence starts with a backslash (\) followed by another character.

For example, the sequence \n doesn't print a backslash and the letter 'n'. Instead, the backslash "escapes" the usual meaning of the 'n' and tells the program to insert a new line.

Escape Sequences

  • \n Newline
  • \\ Backslash literal
  • \" Double-Quote literal
  • \t Tab
  • \' Single-Quote literal

Constants

A constant is a variable whose value, once assigned, cannot be changed. It's used to store data that should remain the same throughout a program's execution.

Constants

You define a constant using the const keyword. The convention is to name constants using all uppercase letters, with words separated by underscores.

const TAX_RATE = 0.08;
...
let total = subtotal * TAX_RATE;

Why Use Constants

Readability: Using a descriptive name like PI or MAX_CONNECTIONS is much clearer than using a "magic number" like 3.14159 or 100.

Preventing Errors: Since the value can't be changed after initialization, you're protected from accidentally overwriting it later in your code.

Compound Assignment Operators

Compound assignment operators provide a concise way to perform an operation on a variable and then assign the new value back to that same variable.

+= -= *= /= %=
Addition Assignment: x = x + 5 -> x += 5
Subtraction Assignment: x = x - 5 -> x -= 5
Multiplication Assignment: y = y * 2 -> y *= 2
Divison Assignment: y = y / 2 -> y /= 2
Modulus Assignment: y = y % 2 -> y %= 2

Increment and Decrement Operators

The increment (++) and decrement (--) operators are a shorthand way to add or subtract 1 from a variable. These are frequently used in loops and counters.

let x = 5;
let y = 5;
x++; // x becomes 6
y--; // y becomes 4

Math Constants and Functions

JavaScript contains a collection of functions and constants for performing common mathematical operations.

Constants:
Math.PI
Represents the mathematical constant PI (Ď€), approximately 3.14159.

Math Constants and Functions

Functions:
Math.round(num)
Round a decimal number to the nearest whole number.
Math.floor(num)
Round a decimal number down to the nearest whole number.
Math.ceil(num)
Round a decimal number up to the nearest whole number.

Math Constants and Functions

Math.sqrt(num)
Returns the positive square root of num. Example: Math.sqrt(25) returns 5.0.

Math Constants and Functions

Math.random()
Returns a random number value greater than or equal to 0.0 and less than 1.0 (~0.9999).
Example: Math.floor((Math.random() * 10) + 1 returns a random integer between 1 and 10.

'F' → Fullscreen

Objectives

  • icon Practice implementing various JavaScript constructs:
    • icon Escape sequences
    • icon Constants
    • icon Compound assignment operations
    • icon Increment & decrement operations
    • icon Math constants and functions
divider

Activity Tasks

  • icon Create a new project named 1-8-intermediate-data.js.
  • icon Complete each task individually.

Task 1: Increment, Decrement, and Compound Assignment

1-8-intermediate-data.js
console.log("--- Task 1: Increment, Decrement, and Compound Assignment ---");
let score = 10;
console.log("Initial score: " + score);
// Compound assignment
score += 5;
console.log("Score after += 5: " + score);
// Increment operator
score++;
console.log("Score after ++: " + score);
// Decrement operator
score--;
console.log("Score after --: " + score);
alert("Press Enter to continue...");
// -----------------------------------------------------------------------------
//

Task 2: Math Constants and Functions

1-8-intermediate-data.js
19 collapsed lines
console.log("--- Task 1: Increment, Decrement, and Compound Assignment ---");
let score = 10;
console.log("Initial score: " + score);
// Compound assignment
score += 5;
console.log("Score after += 5: " + score);
// Increment operator
score++;
console.log("Score after ++: " + score);
// Decrement operator
score--;
console.log("Score after --: " + score);
alert("Press Enter to continue...");
// -----------------------------------------------------------------------------
console.log("--- Task 2: The Math Object and Constants ---");
let radius = 5;
// Calculate area using Math.PI Math.pow()
let area = Math.PI * Math.pow(radius, 2);
console.log("Area of circle with radius " + radius + ": " + area);
// Generate a random dice roll (1-6)
let diceRoll = Math.floor(Math.random() * 6) + 1;
console.log("Random dice roll: " + diceRoll);
alert("Press Enter to continue...");
// -----------------------------------------------------------------------------
//

Task 3: Escape Sequences

1-8-intermediate-data.js
34 collapsed lines
console.log("--- Task 1: Increment, Decrement, and Compound Assignment ---");
let score = 10;
console.log("Initial score: " + score);
// Compound assignment
score += 5;
console.log("Score after += 5: " + score);
// Increment operator
score++;
console.log("Score after ++: " + score);
// Decrement operator
score--;
console.log("Score after --: " + score);
alert("Press Enter to continue...");
// -----------------------------------------------------------------------------
console.log("--- Task 2: The Math Object and Constants ---");
let radius = 5;
// Calculate area using Math.PI Math.pow()
let area = Math.PI * Math.pow(radius, 2);
console.log("Area of circle with radius " + radius + ": " + area);
// Generate a random dice roll (1-6)
let diceRoll = Math.floor(Math.random() * 6) + 1;
console.log("Random dice roll: " + diceRoll);
alert("Press Enter to continue...");
// -----------------------------------------------------------------------------
console.log("--- Task 3: Escape Characters ---");
// Using tab (\t) for formatting
let table = "Item\t\tPrice\nKeyboard\t$75\nMouse\t\t$25";
console.log(table);
// Using newline (\n) and quotes (\")
let message = "He said, \"Hello, world!\"\nAnd the program responded, 'Hi.'";
console.log(message);
alert("Press Enter to continue...");
// -----------------------------------------------------------------------------
//

Task 4: Combining Concepts

1-8-intermediate-data.js
47 collapsed lines
console.log("--- Task 1: Increment, Decrement, and Compound Assignment ---");
let score = 10;
console.log("Initial score: " + score);
// Compound assignment
score += 5;
console.log("Score after += 5: " + score);
// Increment operator
score++;
console.log("Score after ++: " + score);
// Decrement operator
score--;
console.log("Score after --: " + score);
alert("Press Enter to continue...");
// -----------------------------------------------------------------------------
console.log("--- Task 2: The Math Object and Constants ---");
let radius = 5;
// Calculate area using Math.PI Math.pow()
let area = Math.PI * Math.pow(radius, 2);
console.log("Area of circle with radius " + radius + ": " + area);
// Generate a random dice roll (1-6)
let diceRoll = Math.floor(Math.random() * 6) + 1;
console.log("Random dice roll: " + diceRoll);
alert("Press Enter to continue...");
// -----------------------------------------------------------------------------
console.log("--- Task 3: Escape Characters ---");
// Using tab (\t) for formatting
let table = "Item\t\tPrice\nKeyboard\t$75\nMouse\t\t$25";
console.log(table);
// Using newline (\n) and quotes (\")
let message = "He said, \"Hello, world!\"\nAnd the program responded, 'Hi.'";
console.log(message);
alert("Press Enter to continue...");
// -----------------------------------------------------------------------------
console.log("--- Task 4: Challenge Task (Combining Concepts) ---");
let totalStudents = 15;
const GRADE_INCREASE = 1.05;
let newGrade = 80;
// Compound assignment with a constant
newGrade *= GRADE_INCREASE;
// Round the grade using Math.round()
let roundedGrade = Math.round(newGrade);
console.log(`Out of ${totalStudents} students,`);
console.log(`the new rounded grade is: ${roundedGrade}.`);
//
divider

Sample Output

Your program output should something similar to the sample output below.

Sample Output
--- Task 1: Increment, Decrement, and Compound Assignment ---
Initial score: 10
Score after += 5: 15
Score after ++: 16
Score after --: 15
Press Enter to continue... [Enter]
--- Task 2: The Math Object and Constants ---
Area of circle with radius 5: 78.53981633974483
Random dice roll: 6
Press Enter to continue... [Enter]
--- Task 3: Escape Characters ---
Item Price
Keyboard $75
Mouse $25
He said, "Hello, world!"
And the program responded, 'Hi.'
Press Enter to continue... [Enter]
--- Task 4: Challenge Task (Combining Concepts) ---
Out of 15 students,
the new rounded grade is: 84.
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. Think about the concept of compound assignment. What is a real-world scenario (outside of a programming context) where you might perform a similar "shortcut" operation—where you update a value by combining it with another? For example, is there a situation where you keep a running total of expenses by adding each new cost to your existing total, rather than recalculating from scratch each time?
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete