Display Logical Operation Results on Web Page
In this step, you'll combine all the logical operators you've learned and create a comprehensive demonstration that displays the results on the web page. We'll modify the HTML file to include a more structured approach to showing logical operator results.
Update the logical-operators.html
file with the following complete code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>JavaScript Logical Operators Demo</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 0 auto;
padding: 20px;
}
.result {
margin: 10px 0;
padding: 10px;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<h1>JavaScript Logical Operators Exploration</h1>
<div id="andResults" class="result">
<h2>AND (&&) Operator Results</h2>
</div>
<div id="orResults" class="result">
<h2>OR (||) Operator Results</h2>
</div>
<div id="notResults" class="result">
<h2>NOT (!) Operator Results</h2>
</div>
<script>
// Function to display results
function displayResult(elementId, message) {
const element = document.getElementById(elementId);
const resultLine = document.createElement("p");
resultLine.textContent = message;
element.appendChild(resultLine);
}
// AND (&&) Operator Demonstration
function demonstrateAndOperator() {
let isAdult = true;
let hasLicense = true;
let canDrive = isAdult && hasLicense;
displayResult("andResults", `Can drive? ${canDrive}`);
let age = 25;
let hasValidLicense = age >= 18 && age <= 65;
displayResult("andResults", `Valid driving age? ${hasValidLicense}`);
}
// OR (||) Operator Demonstration
function demonstrateOrOperator() {
let isWeekend = false;
let isHoliday = true;
let canRelax = isWeekend || isHoliday;
displayResult("orResults", `Can relax? ${canRelax}`);
let age = 16;
let hasParentalConsent = true;
let canAttendEvent = age >= 18 || hasParentalConsent;
displayResult("orResults", `Can attend event? ${canAttendEvent}`);
}
// NOT (!) Operator Demonstration
function demonstrateNotOperator() {
let isRaining = false;
let isSunny = !isRaining;
displayResult("notResults", `Is it sunny? ${isSunny}`);
let age = 16;
let isAdult = !(age < 18);
displayResult("notResults", `Is an adult? ${isAdult}`);
}
// Run all demonstrations when page loads
function runAllDemonstrations() {
demonstrateAndOperator();
demonstrateOrOperator();
demonstrateNotOperator();
}
// Call the main function when the page loads
window.onload = runAllDemonstrations;
</script>
</body>
</html>
Key improvements in this version:
- Added styled result sections for each logical operator
- Created a
displayResult()
function to show results
- Implemented a
runAllDemonstrations()
function to execute all operator demonstrations
- Added basic CSS to improve readability
- Used
window.onload
to ensure all scripts run after the page loads
Example browser output will show results for AND, OR, and NOT operators in separate, styled sections.