Where JavaScript runs
Activity: First alert() popup
In this episode, the McTweak family will introduce you to the world of JavaScript, the programming language that makes websites interactive and dynamic.
Today's mission: Help review a rookie coder's JavaScript code that works but lacks proper comments. The McTweak family will show the importance of code comments for making JavaScript readable and maintainable.
CodyMcTweak: Alright team, we've covered HTML for structure and CSS for style. Now it's time for the third pillar of web development: JavaScript.
JavaScript is what makes websites interactive. While HTML and CSS are about presentation, JavaScript is about behavior and functionality.
AshleyMcTweak: So what exactly can JavaScript do that HTML and CSS can't? I thought websites were just about showing information and making it look pretty.
AllyMcTweak: Great question! JavaScript lets websites respond to user actions in real-time. Think about things like:
Basically, any time a website does something without loading a new page, that's JavaScript at work!
TrashyMcTweak: Yeah, it's also what makes those annoying pop-ups and auto-playing videos that follow you around the page. JavaScript is like fire – incredibly useful but also the reason 90% of websites are digital dumpster fires.
But I'll admit, without JavaScript, the web would be as boring as Garbage's Tinder profile – just static pictures that nobody wants to interact with.
GarbageMcTweak: At least I HAVE a profile, Trashy. And for your information, JavaScript was created in just 10 days in 1995 by Brendan Eich at Netscape. It was originally called Mocha, then LiveScript, before they renamed it JavaScript to piggyback on Java's popularity.
Despite the rush job, it became the language of the web. Talk about failing upwards.
AshleyMcTweak: So where does JavaScript actually run? Is it on a server like a normal program, or...?
CodyMcTweak: JavaScript traditionally runs in the browser, on the client-side. This means it executes directly on the user's device, not on the server.
Each browser has a JavaScript engine that reads and executes the code. Chrome uses V8, Firefox uses SpiderMonkey, and Safari uses JavaScriptCore.
FattyMcTweak: But that's not the whole story! Since 2009, JavaScript can also run on servers using Node.js, which is built on Chrome's V8 engine.
This gave us a premium full-stack experience where the same language runs everywhere. One language for both front-end and back-end – like getting the full meal deal without having to learn another syntax!
GrumpyMcTweak: LISTEN UP! JavaScript in the browser has LIMITATIONS for security reasons! It can't access your file system or run system commands directly.
And that's a GOOD THING! Can you imagine if ANY website could read your personal files? CHAOS! DISASTER! Your cat pictures and tax returns EVERYWHERE!
CodyMcTweak: To add JavaScript to an HTML page, we use the <script> tag. We can either include the code directly or link to an external file:
<!DOCTYPE html>
<html>
<head>
<title>My First JavaScript Page</title>
</head>
<body>
<h1>Hello, JavaScript!</h1>
<!-- Method 1: Inline JavaScript -->
<script>
alert("Hello from inline script!");
</script>
<!-- Method 2: External JavaScript -->
<script src="script.js"></script>
</body>
</html>
// This is an external JavaScript file
alert("Hello from external script!");
CodyMcTweak: Hey team, we have our first JavaScript code review from a rookie programmer. They created a simple calculator interface with a pop-up alert that works, but... well, see for yourselves:
function calculate() {
let x = document.getElementById("num1").value;
let y = document.getElementById("num2").value;
let op = document.getElementById("operator").value;
let result;
x = parseFloat(x);
y = parseFloat(y);
if (op === "+") {
result = x + y;
} else if (op === "-") {
result = x - y;
} else if (op === "*") {
result = x * y;
} else if (op === "/") {
result = x / y;
}
alert("The result is: " + result);
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
<script src="calculator.js"></script>
</head>
<body>
<h1>Simple Calculator</h1>
<input type="number" id="num1" placeholder="Enter first number">
<select id="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">×</option>
<option value="/">÷</option>
</select>
<input type="number" id="num2" placeholder="Enter second number">
<button onclick="calculate()">Calculate</button>
</body>
</html>
TrashyMcTweak: OH MY GOD! What is this barren wasteland of uncommented code? It's like walking into an unfurnished apartment with zero context about which room is which!
Sure, it works, but so does a potato as a battery. That doesn't mean I want to power my grid with root vegetables!
GrumpyMcTweak: NO COMMENTS?! What do they think this is, a GUESSING GAME? "Ooh, what does this line do? NOBODY KNOWS!"
In SIX MONTHS, they won't even remember what this code does! And don't get me started on ERROR HANDLING! What if someone divides by ZERO?! CATASTROPHE!
AllyMcTweak: JavaScript comments are crucial for making code readable and maintainable. They serve several important purposes:
Remember: Code is read far more often than it's written. Write for humans, not just for the computer!
AshleyMcTweak: So how do we add comments in JavaScript? Is it the same as HTML?
CodyMcTweak: JavaScript has two types of comments:
///* and end with */Let's improve this code by adding proper comments:
/**
* Simple Calculator Function
* Performs basic arithmetic operations between two numbers
* and displays the result in an alert box.
*/
function calculate() {
// Get input values from the form
let x = document.getElementById("num1").value;
let y = document.getElementById("num2").value;
let op = document.getElementById("operator").value;
let result;
// Convert input strings to numbers
x = parseFloat(x);
y = parseFloat(y);
// Perform the selected operation
if (op === "+") {
result = x + y;
} else if (op === "-") {
result = x - y;
} else if (op === "*") {
result = x * y;
} else if (op === "/") {
// Check for division by zero
if (y === 0) {
alert("Error: Cannot divide by zero!");
return;
}
result = x / y;
}
// Display the result using an alert popup
alert("The result is: " + result);
}
FattyMcTweak: Much better! See how we added a premium documentation comment at the top explaining what the function does? That's like the appetizer before the main course – it gives you a taste of what's coming!
And notice how we also added error handling for division by zero. That's a common mistake that would crash our calculator.
GarbageMcTweak: I'd go even further. Let's make this code more maintainable with a switch statement instead of multiple if-else statements, and add input validation:
/**
* Simple Calculator Function
* Performs basic arithmetic operations between two numbers
* and displays the result in an alert box.
*
* @version 1.1
* @author Rookie Coder (improved by McTweak Team)
*/
function calculate() {
// Get input values from the form
let x = document.getElementById("num1").value;
let y = document.getElementById("num2").value;
let op = document.getElementById("operator").value;
let result;
// Validate inputs
if (x === "" || y === "") {
alert("Please enter both numbers");
return;
}
// Convert input strings to numbers
x = parseFloat(x);
y = parseFloat(y);
// Check for NaN
if (isNaN(x) || isNaN(y)) {
alert("Please enter valid numbers");
return;
}
// Perform the selected operation using switch
switch(op) {
case "+":
result = x + y;
break;
case "-":
result = x - y;
break;
case "*":
result = x * y;
break;
case "/":
// Check for division by zero
if (y === 0) {
alert("Error: Cannot divide by zero!");
return;
}
result = x / y;
break;
default:
alert("Invalid operator");
return;
}
// Display the result using an alert popup
alert("The result is: " + result);
}
AllyMcTweak: Perfect! Now the code is not only functional but also:
This is a great example of how comments and careful error handling make JavaScript code much more professional and maintainable.
CodyMcTweak: Now let's focus on the alert() function we've been using. This is one of the simplest ways to interact with users in JavaScript.
The alert() function displays a popup message box with the specified text and an OK button. It's a great way to start learning JavaScript interactions.
SnowzieMcTweak: * wags tail excitedly *
Woof! (Translation: Don't forget that alert() is a blocking function - it pauses JavaScript execution until the user dismisses it!)
AshleyMcTweak: Did... did SnowzieMcTweak just explain JavaScript concepts?
GrumpyMcTweak: OBVIOUSLY! Snowzie's been learning PROGRAMMING from watching us! Just ANOTHER reason to PROPERLY COMMENT your code - even the DOG needs to understand it!
Type some JavaScript code below to create your own alert message. Click "Run Code" to see it in action.
FattyMcTweak: Here are some premium examples you can try in the editor:
alert("Hello, JavaScript world!");alert("My name is " + "Your Name");alert(5 + 10); (What will this display?)alert("5" + "10"); (Compare with the previous example!)CodyMcTweak: Great job on your first JavaScript lesson! We've covered what JavaScript is, where it runs, the importance of code comments, and created our first interactive element with alert().
In our next episode, we'll dive into variables and data types. Keep practicing with the code editor, and don't forget to add comments to your code!
<script> tag, either inline or linked to external files// Single-line comments/* Multi-line comments */alert() function displays a popup message to the user