JavaScript CONSTANTS are easy (7:42)
Learn about constants in JavaScript - variables that cannot be changed once assigned. Understand why constants are important for protecting data integrity and preventing accidental or malicious changes to critical values in your programs.
- What constants are and why they're important
- Difference between
letandconst - Naming conventions for constants
- Protecting values from modification
- When to use constants vs variables
- Creating a circle circumference calculator
- Using mathematical constants (PI)
- Type safety and data protection
// Using let (can be changed)
let PI = 3.14159;
PI = 420.69; // This works but is wrong!
// Using const (cannot be changed)
const PI = 3.14159;
PI = 420.69; // TypeError: Assignment to constant variableHTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Website</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 id="myH1">Enter the radius of the circle</h1>
<label for="radiusInput">Radius:</label>
<input type="text" id="radiusInput">
<button type="button" id="submitButton">Submit</button>
<h4 id="myH3">Circumference: </h4>
<script src="index.js"></script>
</body>
</html>JavaScript:
let circumference;
let PI = 3.14159;
document.getElementById("submitButton").onclick = function() {
radius = document.getElementById("radiusInput").value;
console.log(`radius: ${radius}`);
radius = Number(radius); // Convert to number
circumference = 2 * PI * radius;
console.log(`circumference: ${circumference}`);
document.getElementById("myH3").textContent = "Circumference: " + circumference + "cm";
}Note: In this example, PI should be declared as const PI = 3.14159 to prevent accidental changes!
// ✅ UPPERCASE for primitive constants (numbers, booleans)
const PI = 3.14159;
const MAX_USERS = 100;
const IS_ADMIN = true;
const TAX_RATE = 0.07;// ✅ camelCase for strings and objects (typically)
const appName = "My Application";
const config = { theme: "dark" };const DAYS_IN_WEEK = 7;
// Later in code...
// DAYS_IN_WEEK = 8; // Error! Prevents mistakes// ❌ Hard to understand
let radius = 5;
let result = 2 * 3.14159 * radius;
// ✅ Clear and readable
const PI = 3.14159;
let radius = 5;
let circumference = 2 * PI * radius;// Current implementation (not ideal)
let PI = 3.14159;
let circumference;
let radius;
document.getElementById("submitButton").onclick = function() {
radius = document.getElementById("radiusInput").value;
radius = Number(radius);
circumference = 2 * PI * radius;
document.getElementById("myH3").textContent = "Circumference: " + circumference + "cm";
}
// Problem: PI can be accidentally changed!
PI = 100; // No error, but mathematically wrong!// ✅ Good naming const PI = 3.14159;
### 3. **Using let Instead of const for Fixed Values**
```javascript
// ❌ Current example uses let (can be changed)
let PI = 3.14159;
PI = 100; // Oops! No error, but wrong
// ✅ Should use const (cannot be changed)
const PI = 3.14159;
// PI = 100; // TypeError: Assignment to constant variabl PI * radius;
document.getElementById("myH3").textContent = "Circumference: " + circumference + "cm";
}
// PI = 100; // TypeError: Assignment to constant variable
const PI = 3.14159;
PI = 3.14; // ❌ TypeError: Assignment to constant variable// ❌ Poor naming for constants
const pi = 3.14159; // Should be uppercase for numbers
const APPNAME = "MyApp"; // Should be camelCase for strings// ❌ Wrong - age will change
const age = 25;
age = 26; // Error!
// ✅ Correct - use let
let age = 25;
age = 26; // Works fine| Feature | let | const |
|---|---|---|
| Can reassign | ✅ Yes | ❌ No |
| Must initialize | ❌ No | ✅ Yes |
| Block scoped | ✅ Yes | ✅ Yes |
| Best for | Changing values | Fixed values |
Update the current code to use const for PI instead of let:
// Change this:
let PI = 3.14159;
// To this:
const PI = 3.14159;Calculate the area of a circle using PI as a constant. Formula: π * r²
const PI = 3.14159;
let radius;
let area;
document.getElementById("submitButton").onclick = function() {
radius = document.getElementById("radiusInput").value;
radius = Number(radius);
area = PI * radius * radius; // or PI * radius ** 2
console.log(`Area: ${area}`);
}const PI = 3.14159;
const E = 2.71828; // Euler's number
const GOLDEN_RATIO = 1.61803;Calculate total price with tax using TAX_RATE as a constant.
const TAX_RATE = 0.07;
let price = 100;
let total = price + (price * TAX_RATE);
console.log(`Total with tax: $${total}`);Convert hours to seconds using constants for MINUTES_PER_HOUR and SECONDS_PER_MINUTE.
- Use const by default - Only use
letwhen you know the value will change - UPPERCASE primitive constants - Numbers and booleans
- camelCase reference types - Strings, objects, arrays
- Group related constants - Keep them organized at the top of files
- Meaningful names - Make it clear what the constant represents
- Constants cannot be reassigned after initial assignment
- Use
constfor protection against accidental or malicious changes - UPPERCASE naming for primitive type constants (numbers, booleans)
- camelCase naming for reference type constants (strings, objects)
- Better code quality - Makes code more readable and maintainable
- Type safety - Prevents runtime errors from value changes
- Default to const - Use
letonly when you need to reassign
JavaScript COUNTER PROGRAM - Build a practical counter with increment, decrement, and reset!
Duration: 7:42
Difficulty: Beginner
Prerequisites: Variables, data types