JavaScript Mastery — Chapter 2: JS Output & Syntax
Master the 4 core JavaScript output mechanisms, statement rules, code blocks, single & multi-line comments, camelCase conventions, and case-sensitivity pitfalls.
Chapter Navigation
2.1 JavaScript Output Methods
JavaScript does not possess built-in print functions like other compiled programming languages. Instead, JavaScript outputs data by interacting with the browser DOM, browser dialog windows, or the developer console.
There are 4 primary output mechanisms in JavaScript:
Writes output directly inside an HTML element. The standard production method for dynamic DOM rendering.
Writes output to the browser DevTools Console. The primary tool for debugging and inspection.
Writes directly into the HTML document stream. Warning: Deletes existing HTML if called after page load!
Displays a modal alert box with an OK button. Useful for urgent user notifications.
Live Output Demonstrator Widget
Click any button below to trigger the respective JavaScript output method in real-time:
Example 1: Writing to innerHTML
To access an HTML element, JavaScript uses document.getElementById(id) and modifies its innerHTML property:
<!DOCTYPE html>
<html lang="en">
<body>
<h2 id="heading">Original Heading</h2>
<p id="paragraph">Original text paragraph.</p>
<script>
// Select element by ID and change content
document.getElementById("heading").innerHTML = "Updated Title with innerHTML! 🚀";
document.getElementById("paragraph").innerHTML = "Calculated Result: " + (15 + 25);
</script>
</body>
</html>
Try It Yourself »
Warning: document.write() Danger
Using document.write() after an HTML document has fully loaded will completely overwrite and erase the existing HTML document! It should strictly only be used for quick testing or initial loading streams.
Example 2: Debugging with console.log()
console.log() writes messages directly to your browser's Developer Console (press F12 or Ctrl+Shift+I to open):
<!DOCTYPE html>
<html lang="en">
<body>
<h2>Check Browser Console (F12)</h2>
<script>
// Log numbers, strings, and arithmetic calculations
console.log("Hello, Console!");
console.log(5 + 10);
// Log variables
let user = "Alice";
let score = 95;
console.log("User:", user, "Score:", score);
</script>
</body>
</html>
Try It Yourself »
2.2 Statements & Execution Flow
A JavaScript Program is a sequence of instructions executed line-by-line by a computer engine. In programming, these instructions are called statements.
Example: Anatomy of a JavaScript Statement
Statements consist of Values, Operators, Expressions, Keywords, and Semicolons:
// Statements consist of Values, Operators, Expressions, Keywords, and Comments
let x, y, z; // Statement 1: Declare variables
x = 10; // Statement 2: Assign value 10 to x
y = 20; // Statement 3: Assign value 20 to y
z = x + y; // Statement 4: Add x and y, assign to z
Try It Yourself »
Semicolons (;) in JavaScript
Semicolons separate JavaScript statements. Place a semicolon at the end of every executable statement:
Multiple Statements on One Line
When separated by semicolons, multiple statements can be written on a single line (though line breaks are preferred for readability):
let a = 1; let b = 2; let c = a + b; console.log(c);
Try It Yourself »
Automatic Semicolon Insertion (ASI)
JavaScript features Automatic Semicolon Insertion (ASI), meaning semicolons are technically optional in many places. However, professional engineers always explicitly include semicolons to prevent subtle execution bugs when minifying code.
Code Blocks ({ ... })
JavaScript statements can be grouped together inside curly brackets { ... } into code blocks. The purpose of code blocks is to define statements to be executed together (e.g. inside functions or conditional logic):
Code Block Example
Statements grouped inside curly brackets { ... } execute together:
function calculateTotal() {
let price = 50;
let tax = 5;
let total = price + tax;
document.getElementById("demo").innerHTML = "Total Amount: $" + total;
}
Try It Yourself »
2.3 Syntax Rules & Literals
JavaScript syntax defines the set of rules for how JavaScript programs are constructed.
1. Fixed Values (Literals)
Fixed values are called Literals:
- Numbers: written with or without decimals (
10.50,1001). - Strings: text written within double or single quotes (
"John Doe",'Hello').
2. Variable Values (Variables)
In programming, variables are used to store data values:
- Declared using keywords:
let,const, orvar. - Values are assigned using the assignment operator (
=).
2.4 Comments & Documentation Standards
JavaScript comments are ignored by browser execution engines. Comments are used to explain code logic, improve code maintainability, or temporarily disable code during testing.
Single-Line Comments (//)
Single-line comments start with //. Everything between // and the end of line is ignored by the engine:
// Declare x variable
let x = 5;
let y = 10; // Inline comment explaining y
Try It Yourself »
Multi-Line Comments (/* ... */)
Multi-line comments start with /* and end with */. Useful for block documentation or disabling code:
/*
The code below calculates
the total invoice price
including tax rates.
*/
let total = price * tax;
Try It Yourself »
JSDoc Documentation Standard
JSDoc uses multi-line comments with extra asterisks (/** ... */) to document function parameters and return types:
/**
* Calculates the total cost including tax.
* @param {number} amount - Subtotal cost
* @param {number} taxRate - Tax percentage (e.g. 0.08)
* @returns {number} Final calculated cost
*/
function calculateInvoice(amount, taxRate) {
return amount + (amount * taxRate);
}
Try It Yourself »
2.5 Case Sensitivity & Identifiers
All JavaScript identifiers are strictly case-sensitive.
Example: Case Sensitivity Pitfall
Variables lastName and lastname are two distinct variables in JavaScript:
let lastName = "Doe";
let lastname = "Smith";
console.log(lastName); // Outputs "Doe"
console.log(lastname); // Outputs "Smith"
Try It Yourself »
JavaScript Naming Conventions (camelCase)
Historically, different languages use different naming formats (e.g., first-name in HTML/CSS, first_name in Python/SQL). In JavaScript, lowerCamelCase is the industry standard for variables and functions:
firstName(camelCase — preferred for variables & functions)UserProfileCard(PascalCase — used for ES6 Classes and React components)MAX_RETRY_COUNT(UPPER_SNAKE_CASE — used for global constants)
Reserved Keywords
JavaScript reserved words cannot be used as variable or function names because they are reserved for language syntax:
2.6 Hands-on Challenge: Sales Receipt Calculator & Logger
Build an Interactive Receipt & Console Logger
Challenge Task & Instructions
Task: You are provided with a shopping cart card containing product price ($25) and quantity (3). Write a JavaScript function generateReceipt() that:
- Calculates total cost (
price * quantity). - Uses
innerHTMLto update<span id="receipt-total">with the text"$75.00". - Logs a formatted message to the browser console:
console.log("Order Processed. Total: $75.00"); - Includes a single-line comment explaining the total calculation.
Question / Starter Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sales Receipt Challenge</title>
<style>
body { font-family: system-ui, sans-serif; padding: 24px; background: #0f172a; color: #f8fafc; }
.receipt-card { background: #1e293b; border: 1px solid #334155; border-radius: 12px; padding: 20px; max-width: 400px; }
.btn { background: #6366f1; color: #fff; border: none; padding: 8px 16px; border-radius: 6px; font-weight: bold; cursor: pointer; }
</style>
</head>
<body>
<div class="receipt-card">
<h3>🛒 Checkout Summary</h3>
<p>Item: Wireless Headphones ($25)</p>
<p>Quantity: 3</p>
<h4>Total: <span id="receipt-total" style="color:#38bdf8;">$0.00</span></h4>
<button class="btn" onclick="generateReceipt()">Generate Receipt</button>
</div>
<script>
function generateReceipt() {
// TODO 1: Declare price (25) and quantity (3)
// TODO 2: Calculate total
// TODO 3: Update innerHTML of #receipt-total
// TODO 4: Log order confirmation to console.log()
}
</script>
</body>
</html>
🚀 Solve Challenge in Playground »
let total = 25 * 3;. Then update element content with document.getElementById("receipt-total").innerHTML = "$" + total + ".00";!
function generateReceipt() {
let price = 25;
let quantity = 3;
// Calculate total cost
let total = price * quantity;
// Display total on web page
document.getElementById("receipt-total").innerHTML = "$" + total + ".00";
// Log message to browser DevTools console
console.log("Order Processed. Total: $" + total + ".00");
}
▶ Try Solution in Playground »