Play with Variables
Learning Objectives
- Master variable declaration and usage
- Understand expressions and operators
- Learn type conversions
- Practice user interactions
- Apply proper variable naming conventions
Section 3.1: Variables
What is a Variable?
A variable is a named container that stores a value. Think of it as a labeled box where you can put and retrieve data.
let name = "Alice";
let age = 25;
let isStudent = true;
console.log(name); // Alice
console.log(age); // 25
console.log(isStudent); // true
Declaring Variables
let username = "john_doe";
let score = 100;
const PI = 3.14159;
const MAX_USERS = 100;
// const value = 5;
// value = 10; // ERROR: Cannot reassign
var old = "not recommended"; // Works but avoid this
Variable Naming Rules
- Start with letter, underscore, or dollar sign
- Contain letters, numbers, underscores, or dollar signs
- Case-sensitive:
name≠Name - No reserved keywords:
let,const,function, etc.
Good vs Bad Naming
// ✅ GOOD
let userName = "Alice";
let userAge = 30;
let isActive = true;
let totalScore = 100;
// ❌ BAD
let n = "Alice"; // Too vague
let x = 30; // Not descriptive
let a = true; // Unclear purpose
let totalscorethisseason = 100; // Hard to read
Section 3.2: Expressions
What is an Expression?
An expression is a combination of values and operators that produces a result.
let result = 5 + 3; // Expression: 5 + 3
let message = "Hello" + " " + "World"; // String expression
let isVerified = 10 > 5; // Boolean expression
Arithmetic Operators
let a = 10, b = 3;
console.log(a + b); // 13 (addition)
console.log(a - b); // 7 (subtraction)
console.log(a * b); // 30 (multiplication)
console.log(a / b); // 3.333... (division)
console.log(a % b); // 1 (remainder)
console.log(a ** b); // 1000 (exponentiation)
Comparison Operators
let age = 18;
console.log(age > 18); // false (greater than)
console.log(age >= 18); // true (greater or equal)
console.log(age < 21); // true (less than)
console.log(age <= 21); // true (less or equal)
console.log(age == 18); // true (equal)
console.log(age != 15); // true (not equal)
Logical Operators
let isStudent = true;
let hasScholarship = false;
console.log(isStudent && hasScholarship); // false (AND)
console.log(isStudent || hasScholarship); // true (OR)
console.log(!isStudent); // false (NOT)
Section 3.3: Type Conversions
Automatic Conversion
JavaScript automatically converts types in some situations:
console.log("5" + 3); // "53" (number to string)
console.log("5" - 3); // 2 (string to number)
console.log("10" * "2"); // 20 (strings to numbers)
console.log(true + 1); // 2 (true = 1)
console.log(false + 1); // 1 (false = 0)
Manual Conversion
let str = "42";
console.log(Number(str)); // 42
console.log(parseInt("3.14")); // 3
console.log(parseFloat("3.14")); // 3.14
let num = 42;
console.log(String(num)); // "42"
console.log(num.toString()); // "42"
console.log(num + ""); // "42"
console.log(Boolean(1)); // true
console.log(Boolean(0)); // false
console.log(Boolean("text")); // true
console.log(Boolean("")); // false
Section 3.4: User Interactions
Getting User Input
let name = prompt("What is your name?");
console.log("Hello, " + name);
alert("Welcome to this program!");
let confirmed = confirm("Do you agree?");
console.log(confirmed); // true or false
Complete Example
let name = prompt("Enter your name:");
let age = prompt("Enter your age:");
age = Number(age); // Convert to number
console.log("Name: " + name);
console.log("Age: " + age);
console.log("Next year you'll be " + (age + 1));
Section 3.5: Variable Naming Best Practices
camelCase (Recommended for JavaScript)
let firstName = "John";
let isValidUser = true;
let totalNumberOfItems = 50;
let myPhoneNumber = "555-1234";
PascalCase (For Classes)
class UserAccount { }
class CalculatorApp { }
CONSTANT_CASE (For Constants)
const MAX_LOGIN_ATTEMPTS = 3;
const API_URL = "https://api.example.com";
const PI = 3.14159;
Meaningful Names
// ✅ GOOD - Clear purpose
let userAge = 25;
let isAdmin = true;
let totalPrice = 99.99;
// ❌ BAD - Unclear
let ua = 25;
let ia = true;
let tp = 99.99;
Coding Challenges
Challenge 3.1: Improved Hello
Task: Create a program that:
- Asks for the user's name
- Asks for their favorite color
- Displays: "Hi [name], your favorite color is [color]!"
Challenge 3.2: VAT Calculation
Task: Create a calculator that:
- Asks for a product price
- Calculates 15% VAT
- Displays the original price, VAT amount, and total price
Example Output:
Original Price: $100
VAT (15%): $15
Total Price: $115
Challenge 3.3: Celsius to Fahrenheit Conversion
Task: Convert temperature from Celsius to Fahrenheit
- Formula: F = (C × 9/5) + 32
- Ask user for temperature in Celsius
- Display result in Fahrenheit
Challenge 3.4: Variable Swapping
Task: Write a program that:
- Creates two variables with initial values
- Swaps their values without using a third variable
- Displays the swapped values
Hint: Use arithmetic operations to swap values.
Key Takeaways
✅ Variables store data with meaningful names
✅ Use let or const for variable declaration
✅ Expressions combine values and operators
✅ Type conversion changes data types
✅ User interactions get input via prompt(), alert(), confirm()
✅ Use camelCase for variable naming
Quiz Questions
- What is a variable and why would you use one?
- Explain the difference between
letandconst - What does
5 + "5"return and why? - How can you convert a string to a number?
- What is the best way to name variables in JavaScript?
Next Module: Module 4 - Add Conditions