Categories Javascript

Introduction to JavaScript Fundamentals

Welcome to the first part of our comprehensive JavaScript guide. In this document, we’ll explore the core fundamentals of JavaScript as a programming language, before diving into browser interactions and practical applications in later sections.

JavaScript is the powerhouse of modern web development, bringing life and interactivity to otherwise static web pages. Whether you’re new to programming or experienced with other languages, understanding JavaScript’s unique features and syntax is essential for effective web development.

This guide includes interactive examples throughout—we strongly encourage you to try these exercises in your own browser to reinforce your learning through hands-on practice.

Let’s begin with the basics and build a solid foundation for your JavaScript journey.

Getting Started with JavaScript

Before diving into complex programming concepts, it’s important to understand how to include JavaScript in your web pages and write your first lines of code.

Including JavaScript in HTML Documents

There are two primary ways to add JavaScript to your HTML documents:

  1. Internal JavaScript:
<script>
    // Your JavaScript code here
    console.log("Hello, World!");
</script>
  1. External JavaScript:
<script src="script.js"></script>

Best practices for script placement:

  • Place script tags just before the closing </body> tag for better page loading
  • Use external files for better organization and caching
  • Add defer attribute when loading external scripts in the head

External JavaScript files promote code reuse and maintainability. When your website has multiple pages, using external scripts means you only need to update your code in one place. Additionally, browsers can cache external JavaScript files, potentially improving load times for returning visitors.

Try It Yourself: Including JavaScript

Create a new HTML file called first-javascript.html with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My First JavaScript</title>
</head>
<body>
    <h1>My First JavaScript Page</h1>
    <p>Open the console (F12 or right-click > Inspect > Console) to see the JavaScript output.</p>

    <!-- Internal JavaScript -->
    <script>
        console.log("This message comes from internal JavaScript!");
    </script>

    <!-- External JavaScript -->
    <script src="script.js"></script>
</body>
</html>

Next, create a file called script.js in the same folder with this content:

console.log("This message comes from external JavaScript!");
alert("Welcome to JavaScript!");

Open first-javascript.html in your browser to see the JavaScript in action. Check the console to see both messages, and you’ll also see an alert popup.

Your First JavaScript Program

Let’s start with a simple “Hello World” example:

console.log("Hello, World!");
alert("Welcome to JavaScript!");

You can view the output in your browser’s developer console (usually accessible by pressing F12).

The console.log() method is invaluable for development and debugging. It writes information to the browser’s console without affecting the webpage’s appearance. The alert() method, on the other hand, displays a popup dialog with your message, interrupting the user experience. While useful for learning, alerts are generally avoided in production applications in favor of more user-friendly notification methods.

Try It Yourself: Interactive Hello World

Create a new HTML file called interactive-hello.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Interactive Hello World</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; max-width: 600px; margin: 0 auto; padding: 20px; }
        button { padding: 8px 16px; margin: 10px 0; }
        #output { padding: 10px; background-color: #f0f0f0; border-radius: 4px; min-height: 20px; }
    </style>
</head>
<body>
    <h1>Interactive Hello World</h1>
    <p>Click the buttons below to see JavaScript in action:</p>
    
    <button id="consoleBtn">Log to Console</button>
    <button id="alertBtn">Show Alert</button>
    <button id="displayBtn">Display on Page</button>
    
    <h3>Output:</h3>
    <div id="output"></div>
    
    <script>
        document.getElementById('consoleBtn').addEventListener('click', function() {
            console.log('Hello, World! Check the console.');
            document.getElementById('output').textContent = 'Message logged to console. Press F12 to view.';
        });
        
        document.getElementById('alertBtn').addEventListener('click', function() {
            alert('Hello, World!');
            document.getElementById('output').textContent = 'Alert displayed.';
        });
        
        document.getElementById('displayBtn').addEventListener('click', function() {
            document.getElementById('output').textContent = 'Hello, World!';
        });
    </script>
</body>
</html>

Open this file in your browser to interact with the buttons and see different ways JavaScript can communicate with users.

Basic Syntax and Fundamentals

Understanding JavaScript’s core syntax and fundamental concepts provides the foundation for all your future JavaScript programming.

Variables and Declarations

JavaScript offers three ways to declare variables:

var oldWay = "I'm function-scoped";
let modern = "I'm block-scoped";
const constant = "I can't be reassigned";

The var keyword was the original way to declare variables in JavaScript. However, it has some quirks related to hoisting—a behavior where variable declarations are moved to the top of their containing scope during compilation—that can lead to unexpected behavior. When variables declared with var are hoisted, only their declarations are moved up, not their initializations. This means you can access variables before they appear in your code, though they’ll be undefined. Modern JavaScript (ES6+) introduced let and const, which provide more predictable block-level scoping and are not hoisted in the same way, preventing the confusion that can arise from accessing variables before they’re declared.

Use let when you need to reassign a variable’s value, and const when you want to ensure a variable’s value remains fixed. As a best practice, favor const by default and only use let when necessary.

Naming conventions:

  • Use camelCase for variable names (start with lowercase, capitalize subsequent words)
  • Start with letters, $, or _
  • Make names descriptive and meaningful
  • Avoid reserved keywords (like functionreturnif)

Try It Yourself: Variables and Declarations

Create a file called variables.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Variables</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
        .example { background-color: #f0f0f0; padding: 15px; margin-bottom: 15px; border-radius: 4px; }
        .code { font-family: monospace; background-color: #eee; padding: 2px 4px; }
        button { padding: 8px 16px; margin-right: 10px; }
        .result { font-weight: bold; margin-top: 10px; }
    </style>
</head>
<body>
    <h1>JavaScript Variables and Declarations</h1>
    
    <div class="example">
        <h2>Variable Declaration Types</h2>
        <p>Click to see the differences between <span class="code">var</span>, <span class="code">let</span>, and <span class="code">const</span>:</p>
        <button onclick="testVar()">Test var</button>
        <button onclick="testLet()">Test let</button>
        <button onclick="testConst()">Test const</button>
        <div id="varResult" class="result"></div>
    </div>
    
    <div class="example">
        <h2>Hoisting Demonstration</h2>
        <p>See how variable hoisting works with <span class="code">var</span> vs <span class="code">let</span>:</p>
        <button onclick="demonstrateHoisting()">Show Hoisting</button>
        <div id="hoistingResult" class="result"></div>
    </div>
    
    <div class="example">
        <h2>Block Scope Comparison</h2>
        <p>Compare block scoping between <span class="code">var</span> and <span class="code">let</span>:</p>
        <button onclick="demonstrateScope()">Show Scope Differences</button>
        <div id="scopeResult" class="result"></div>
    </div>
    
    <script>
        function testVar() {
            var x = "Initial value";
            document.getElementById("varResult").innerHTML = "Initial value: " + x + "<br>";
            
            x = "New value";
            document.getElementById("varResult").innerHTML += "After reassignment: " + x + "<br>";
            
            var x = "Redeclared value";
            document.getElementById("varResult").innerHTML += "After redeclaration: " + x + "<br>";
        }
        
        function testLet() {
            let x = "Initial value";
            document.getElementById("varResult").innerHTML = "Initial value: " + x + "<br>";
            
            x = "New value";
            document.getElementById("varResult").innerHTML += "After reassignment: " + x + "<br>";
            
            try {
                // This would cause an error: "Identifier 'x' has already been declared"
                // let x = "Redeclared value";
                document.getElementById("varResult").innerHTML += "Cannot redeclare with let in the same scope!<br>";
            } catch (e) {
                document.getElementById("varResult").innerHTML += "Error: " + e.message + "<br>";
            }
        }
        
        function testConst() {
            const x = "Initial value";
            document.getElementById("varResult").innerHTML = "Initial value: " + x + "<br>";
            
            try {
                // This would cause an error: "Assignment to constant variable"
                // x = "New value";
                document.getElementById("varResult").innerHTML += "Cannot reassign a constant!<br>";
            } catch (e) {
                document.getElementById("varResult").innerHTML += "Error: " + e.message + "<br>";
            }
        }
        
        function demonstrateHoisting() {
            let result = "";
            
            // Using var before declaration
            result += "Value of x before declaration with var: " + x + "<br>";
            var x = 10;
            result += "Value of x after declaration with var: " + x + "<br><br>";
            
            // Using let before declaration would cause a ReferenceError
            result += "Using y before declaration with let would cause a ReferenceError<br>";
            // Uncommenting the next line would break the code
            // console.log(y);
            let y = 20;
            result += "Value of y after declaration with let: " + y + "<br>";
            
            document.getElementById("hoistingResult").innerHTML = result;
        }
        
        function demonstrateScope() {
            let result = "";
            
            // var and block scope
            {
                var blockVar = "I'm var in a block";
            }
            result += "Accessing blockVar outside its block: " + blockVar + "<br>";
            
            // let and block scope
            {
                let blockLet = "I'm let in a block";
                result += "Accessing blockLet inside its block: " + blockLet + "<br>";
            }
            
            try {
                // This would cause a ReferenceError
                result += "Accessing blockLet outside its block: " + blockLet + "<br>";
            } catch (e) {
                result += "Error when accessing blockLet outside its block: " + e.message + "<br>";
            }
            
            document.getElementById("scopeResult").innerHTML = result;
        }
    </script>
</body>
</html>

Open this file in your browser to explore how different variable declarations work.

Data Types

JavaScript is a dynamically-typed language, meaning you don’t need to explicitly declare a variable’s type. The interpreter will determine the type at runtime.

JavaScript has several primary data types:

let string = "Hello";           // String - text enclosed in quotes
let number = 42;                // Number - integers and floating-point numbers
let boolean = true;             // Boolean - true or false values
let undefinedVar;              // undefined - automatically assigned to uninitialized variables
let nullVar = null;            // null - represents the intentional absence of value

JavaScript also includes two complex data types:

  • Objects: Collections of key-value pairs
  • Arrays: Ordered collections of values

Type checking:

console.log(typeof string);     // "string"
console.log(typeof number);     // "number"

The typeof operator helps determine a value’s data type at runtime, which is particularly useful in a dynamically-typed language.

Try It Yourself: Data Types Explorer

Create a file called data-types.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Data Types</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
        .example { background-color: #f0f0f0; padding: 15px; margin-bottom: 15px; border-radius: 4px; }
        pre { background-color: #eee; padding: 10px; border-radius: 4px; overflow-x: auto; }
        .playground { margin-top: 20px; border: 1px solid #ddd; padding: 10px; border-radius: 4px; }
        #typeOutput { font-family: monospace; min-height: 200px; }
        input, button { margin: 5px; padding: 8px; }
    </style>
</head>
<body>
    <h1>JavaScript Data Types Explorer</h1>
    
    <div class="example">
        <h2>Primitive Data Types</h2>
        <pre id="primitiveOutput"></pre>
        <button onclick="explorePrimitives()">Explore Primitive Types</button>
    </div>
    
    <div class="example">
        <h2>Complex Data Types</h2>
        <pre id="complexOutput"></pre>
        <button onclick="exploreComplexTypes()">Explore Complex Types</button>
    </div>
    
    <div class="example">
        <h2>Type Conversion</h2>
        <pre id="conversionOutput"></pre>
        <button onclick="demonstrateConversion()">Show Type Conversions</button>
    </div>
    
    <div class="playground">
        <h2>Type Checking Playground</h2>
        <p>Enter any value to check its type:</p>
        <input type="text" id="typeInput" placeholder="Enter a value...">
        <button onclick="checkType()">Check Type</button>
        <pre id="typeOutput"></pre>
    </div>
    
    <script>
        function explorePrimitives() {
            let output = "";
            
            // String
            let stringValue = "Hello, World!";
            output += `String: ${stringValue}\nType: ${typeof stringValue}\n\n`;
            
            // Number
            let intValue = 42;
            let floatValue = 3.14;
            let negativeValue = -10;
            let specialNum = Infinity;
            output += `Integer: ${intValue}\nType: ${typeof intValue}\n\n`;
            output += `Float: ${floatValue}\nType: ${typeof floatValue}\n\n`;
            output += `Negative: ${negativeValue}\nType: ${typeof negativeValue}\n\n`;
            output += `Special: ${specialNum}\nType: ${typeof specialNum}\n\n`;
            
            // Boolean
            let boolTrue = true;
            let boolFalse = false;
            output += `Boolean (true): ${boolTrue}\nType: ${typeof boolTrue}\n\n`;
            output += `Boolean (false): ${boolFalse}\nType: ${typeof boolFalse}\n\n`;
            
            // Undefined
            let undefinedVar;
            output += `Undefined: ${undefinedVar}\nType: ${typeof undefinedVar}\n\n`;
            
            // Null
            let nullVar = null;
            output += `Null: ${nullVar}\nType: ${typeof nullVar} (quirk: null is an object in JS)\n\n`;
            
            document.getElementById("primitiveOutput").textContent = output;
        }
        
        function exploreComplexTypes() {
            let output = "";
            
            // Objects
            let person = {
                name: "John",
                age: 30,
                isStudent: false
            };
            output += `Object: ${JSON.stringify(person)}\nType: ${typeof person}\n\n`;
            
            // Arrays
            let colors = ["red", "green", "blue"];
            output += `Array: ${colors}\nType: ${typeof colors} (arrays are objects in JS)\n`;
            output += `Is Array? ${Array.isArray(colors)}\n\n`;
            
            // Functions
            let greet = function(name) { return `Hello, ${name}`; };
            output += `Function: ${greet}\nType: ${typeof greet}\n`;
            output += `Function call result: ${greet("Alice")}\n\n`;
            
            // Date
            let today = new Date();
            output += `Date: ${today}\nType: ${typeof today}\n\n`;
            
            document.getElementById("complexOutput").textContent = output;
        }
        
        function demonstrateConversion() {
            let output = "";
            
            // String to Number
            let str = "42";
            output += `Original: "${str}" (${typeof str})\n`;
            output += `Number conversion: ${Number(str)} (${typeof Number(str)})\n`;
            output += `parseInt conversion: ${parseInt(str)} (${typeof parseInt(str)})\n\n`;
            
            // Number to String
            let num = 42;
            output += `Original: ${num} (${typeof num})\n`;
            output += `String conversion: "${String(num)}" (${typeof String(num)})\n`;
            output += `toString conversion: "${num.toString()}" (${typeof num.toString()})\n\n`;
            
            // Boolean conversions
            output += `Empty string to boolean: ${Boolean("")} (${typeof Boolean("")})\n`;
            output += `"Hello" to boolean: ${Boolean("Hello")} (${typeof Boolean("Hello")})\n`;
            output += `0 to boolean: ${Boolean(0)} (${typeof Boolean(0)})\n`;
            output += `1 to boolean: ${Boolean(1)} (${typeof Boolean(1)})\n\n`;
            
            document.getElementById("conversionOutput").textContent = output;
        }
        
        function checkType() {
            const value = document.getElementById("typeInput").value;
            let output = "";
            
            try {
                // First try to parse as JSON for objects/arrays
                try {
                    const parsed = JSON.parse(value);
                    output += `Parsed value: ${JSON.stringify(parsed)}\n`;
                    output += `Type: ${typeof parsed}\n`;
                    if (Array.isArray(parsed)) {
                        output += `Is Array? true\n`;
                    }
                } catch {
                    // Not valid JSON, continue with regular value
                    output += `Raw value: ${value}\n`;
                    output += `Type: ${typeof value}\n`;
                    
                    // Additional type checks
                    if (value === "true" || value === "false") {
                        output += `As boolean: ${value === "true"}\n`;
                    }
                    
                    if (!isNaN(Number(value))) {
                        output += `As number: ${Number(value)}\n`;
                    }
                }
            } catch (e) {
                output += `Error: ${e.message}\n`;
            }
            
            document.getElementById("typeOutput").textContent = output;
        }
    </script>
</body>
</html>

Open this file in your browser to experiment with different JavaScript data types.

Operators

Operators allow you to perform operations on variables and values:

// Arithmetic
let sum = 5 + 3;               // Addition
let difference = 10 - 5;       // Subtraction
let product = 4 * 2;           // Multiplication
let quotient = 15 / 3;         // Division
let remainder = 10 % 3;        // Modulus (remainder after division)
let exponent = 2 ** 3;         // Exponentiation (2 raised to power of 3)

// Comparison
let isEqual = 5 === 5;         // Strict equality (compares value and type)
let isLooseEqual = 5 == "5";   // Loose equality (converts types before comparing)
let isGreater = 10 > 5;        // Greater than
let isLessOrEqual = 5 <= 5;    // Less than or equal to

// Logical
let andOperator = true && false;  // Logical AND (returns true only if both operands are true)
let orOperator = true || false;   // Logical OR (returns true if at least one operand is true)
let notOperator = !true;          // Logical NOT (inverts the boolean value)

Pay special attention to the difference between == (loose equality) and === (strict equality). The strict equality operator is generally preferred as it avoids unexpected type conversions.

Try It Yourself: Operators Calculator

Create a file called operators.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Operators</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
        .calculator { background-color: #f0f0f0; padding: 15px; margin-bottom: 15px; border-radius: 4px; }
        .input-group { margin-bottom: 10px; }
        label { display: inline-block; width: 150px; }
        input[type="number"] { width: 100px; padding: 5px; }
        button { padding: 8px 16px; margin: 5px; }
        .result { margin-top: 10px; padding: 10px; background-color: #dff0d8; border-radius: 4px; }
        .comparison-table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        .comparison-table th, .comparison-table td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        .comparison-table th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <h1>JavaScript Operators Interactive Demo</h1>
    
    <div class="calculator">
        <h2>Arithmetic Operators</h2>
        <div class="input-group">
            <label for="num1">First Number:</label>
            <input type="number" id="num1" value="10">
        </div>
        <div class="input-group">
            <label for="num2">Second Number:</label>
            <input type="number" id="num2" value="5">
        </div>
        
        <button onclick="calculate('+')" title="Addition">+</button>
        <button onclick="calculate('-')" title="Subtraction">-</button>
        <button onclick="calculate('*')" title="Multiplication">*</button>
        <button onclick="calculate('/')" title="Division">/</button>
        <button onclick="calculate('%')" title="Modulus (Remainder)">%</button>
        <button onclick="calculate('**')" title="Exponentiation">**</button>
        
        <div id="arithmeticResult" class="result"></div>
    </div>
    
    <div class="calculator">
        <h2>Comparison Operators</h2>
        <div class="input-group">
            <label for="comp1">First Value:</label>
            <input type="text" id="comp1" value="5">
        </div>
        <div class="input-group">
            <label for="comp2">Second Value:</label>
            <input type="text" id="comp2" value="5">
        </div>
        
        <button onclick="compare('==')" title="Loose Equality">==</button>
        <button onclick="compare('===')" title="Strict Equality">===</button>
        <button onclick="compare('!=')" title="Loose Inequality">!=</button>
        <button onclick="compare('!==')" title="Strict Inequality">!==</button>
        <button onclick="compare('>')" title="Greater Than">></button>
        <button onclick="compare('<')" title="Less Than"><</button>
        <button onclick="compare('>=')" title="Greater Than or Equal">>=</button>
        <button onclick="compare('<=')" title="Less Than or Equal"><=</button>
        
        <div id="comparisonResult" class="result"></div>
    </div>
    
    <div class="calculator">
        <h2>Logical Operators</h2>
        <div class="input-group">
            <label for="logical1">First Boolean:</label>
            <select id="logical1">
                <option value="true">true</option>
                <option value="false">false</option>
            </select>
        </div>
        <div class="input-group">
            <label for="logical2">Second Boolean:</label>
            <select id="logical2">
                <option value="true">true</option>
                <option value="false">false</option>
            </select>
        </div>
        
        <button onclick="logicalOp('&&')" title="Logical AND">&&</button>
        <button onclick="logicalOp('||')" title="Logical OR">||</button>
        <button onclick="logicalOp('!')" title="Logical NOT">! (NOT)</button>
        
        <div id="logicalResult" class="result"></div>
    </div>
    
    <div class="calculator">
        <h2>Equality Comparison Table</h2>
        <table class="comparison-table">
            <thead>
                <tr>
                    <th>Value A</th>
                    <th>Value B</th>
                    <th>A == B (Loose)</th>
                    <th>A === B (Strict)</th>
                </tr>
            </thead>
            <tbody id="equalityTable">
                <!-- Will be filled by JavaScript -->
            </tbody>
        </table>
        <button onclick="generateEqualityTable()">Generate Table</button>
    </div>
    
    <script>
        function calculate(operator) {
            const num1 = parseFloat(document.getElementById('num1').value);
            const num2 = parseFloat(document.getElementById('num2').value);
            let result;
            
            switch(operator) {
                case '+': result = num1 + num2; break;
                case '-': result = num1 - num2; break;
                case '*': result = num1 * num2; break;
                case '/': result = num1 / num2; break;
                case '%': result = num1 % num2; break;
                case '**': result = num1 ** num2; break;
            }
            
            document.getElementById('arithmeticResult').innerHTML = `
                <strong>${num1} ${operator} ${num2} = ${result}</strong><br>
                <code>let result = ${num1} ${operator} ${num2}; // ${result}</code>
            `;
        }
        
        function compare(operator) {
            let val1 = document.getElementById('comp1').value;
            let val2 = document.getElementById('comp2').value;
            let result;
            
            // Try to convert numeric strings to numbers
            if (!isNaN(val1)) val1 = Number(val1);
            if (!isNaN(val2)) val2 = Number(val2);
            
            switch(operator) {
                case '==': result = val1 == val2; break;
                case '===': result = val1 === val2; break;
                case '!=': result = val1 != val2; break;
                case '!==': result = val1 !== val2; break;
                case '>': result = val1 > val2; break;
                case '<': result = val1 < val2; break;
                case '>=': result = val1 >= val2; break;
                case '<=': result = val1 <= val2; break;
            }
            
            document.getElementById('comparisonResult').innerHTML = `
                <strong>${JSON.stringify(val1)} ${operator} ${JSON.stringify(val2)} is ${result}</strong><br>
                <code>let result = ${JSON.stringify(val1)} ${operator} ${JSON.stringify(val2)}; // ${result}</code><br>
                Type of first value: ${typeof val1}<br>
                Type of second value: ${typeof val2}
            `;
        }
        
        function logicalOp(operator) {
            const val1 = document.getElementById('logical1').value === 'true';
            const val2 = document.getElementById('logical2').value === 'true';
            let result;
            let code;
            
            switch(operator) {
                case '&&': 
                    result = val1 && val2; 
                    code = `let result = ${val1} && ${val2}; // ${result}`;
                    break;
                case '||': 
                    result = val1 || val2; 
                    code = `let result = ${val1} || ${val2}; // ${result}`;
                    break;
                case '!': 
                    result = !val1; 
                    code = `let result = !${val1}; // ${result}`;
                    break;
            }
            
            document.getElementById('logicalResult').innerHTML = `
                <strong>Result: ${result}</strong><br>
                <code>${code}</code>
            `;
        }
        
        function generateEqualityTable() {
            const testValues = [
                0,
                "0",
                "",
                false,
                true,
                1,
                "1",
                null,
                undefined,
                NaN,
                []
            ];
            
            let tableHtml = '';
            
            for (let i = 0; i < testValues.length; i++) {
                for (let j = i; j < testValues.length; j++) {
                    const a = testValues[i];
                    const b = testValues[j];
                    
                    tableHtml += `<tr>
                        <td>${a === "" ? '""' : a === undefined ? 'undefined' : a === null ? 'null' : Array.isArray(a) ? '[]' : a}</td>
                        <td>${b === "" ? '""' : b === undefined ? 'undefined' : b === null ? 'null' : Array.isArray(b) ? '[]' : b}</td>
                        <td>${a == b}</td>
                        <td>${a === b}</td>
                    </tr>`;
                }
            }
            
            document.getElementById('equalityTable').innerHTML = tableHtml;
        }
        
        // Initialize with some values
        calculate('+');
        compare('===');
        logicalOp('&&');
    </script>
</body>
</html>

Open this file in your browser to explore different JavaScript operators.

Comments

Comments help document your code and make it more understandable:

// Single-line comment

/* Multi-line
   comment block */

/** 
 * Documentation
 * comment - often used to document functions
 * and their parameters
 */

Well-commented code is easier to maintain, especially when working in teams or returning to your own code after some time. Focus on explaining “why” something is done a certain way rather than “what” is being done, as the code itself should make the “what” clear.

Control Flow

Control flow determines the order in which your code executes. JavaScript provides several structures to control this flow based on conditions and repetition.

Conditional Statements

Conditional statements let your code make decisions:

// if/else statement
let age = 18;
if (age >= 18) {
    console.log("Adult");
} else if (age >= 13) {
    console.log("Teenager");
} else {
    console.log("Child");
}

// Switch statement
let day = "Monday";
switch (day) {
    case "Monday":
        console.log("Start of week");
        break;
    case "Friday":
        console.log("Weekend coming!");
        break;
    default:
        console.log("Regular day");
}

// Ternary operator - a compact form of if/else
let status = age >= 18 ? "Adult" : "Minor";

The if/else construct is JavaScript’s most basic conditional statement. The switch statement is useful when comparing a single value against multiple possible matches. Remember to include the break statement in each case to prevent fall-through execution.

The ternary operator (condition ? expressionIfTrue : expressionIfFalse) provides a concise way to write simple conditionals, especially when assigning values based on conditions.

Try It Yourself: Interactive Conditionals

Create a file called conditionals.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Conditionals</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
        .example { background-color: #f0f0f0; padding: 15px; margin-bottom: 20px; border-radius: 4px; }
        .input-section { margin-bottom: 15px; }
        label { display: inline-block; width: 100px; }
        input, select { padding: 5px; margin-right: 10px; }
        button { padding: 8px 16px; }
        .result { margin-top: 10px; padding: 10px; background-color: #e8f4f8; border-radius: 4px; }
        .code { font-family: monospace; background-color: #eee; padding: 10px; border-radius: 4px; white-space: pre; overflow-x: auto; }
    </style>
</head>
<body>
    <h1>JavaScript Conditional Statements</h1>
    
    <div class="example">
        <h2>Age Classifier (if/else)</h2>
        <div class="input-section">
            <label for="ageInput">Age:</label>
            <input type="number" id="ageInput" min="0" max="120" value="18">
            <button onclick="classifyAge()">Classify</button>
        </div>
        <div id="ageResult" class="result"></div>
        <div class="code" id="ageCode"></div>
    </div>
    
    <div class="example">
        <h2>Day of Week (switch)</h2>
        <div class="input-section">
            <label for="dayInput">Day:</label>
            <select id="dayInput">
                <option value="Monday">Monday</option>
                <option value="Tuesday">Tuesday</option>
                <option value="Wednesday">Wednesday</option>
                <option value="Thursday">Thursday</option>
                <option value="Friday">Friday</option>
                <option value="Saturday">Saturday</option>
                <option value="Sunday">Sunday</option>
            </select>
            <button onclick="describeDayOfWeek()">Describe</button>
        </div>
        <div id="dayResult" class="result"></div>
        <div class="code" id="dayCode"></div>
    </div>
    
    <div class="example">
        <h2>Ticket Price (ternary operator)</h2>
        <div class="input-section">
            <label for="isStudent">Student?</label>
            <input type="checkbox" id="isStudent">
            
            <label for="isSenior">Senior?</label>
            <input type="checkbox" id="isSenior">
            
            <button onclick="calculateTicketPrice()">Get Price</button>
        </div>
        <div id="ticketResult" class="result"></div>
        <div class="code" id="ticketCode"></div>
    </div>
    
    <div class="example">
        <h2>Traffic Light Simulator</h2>
        <div class="input-section">
            <button onclick="cycleLight()">Change Light</button>
        </div>
        <div style="text-align: center; margin: 20px 0;">
            <div id="redLight" style="display: inline-block; width: 50px; height: 50px; border-radius: 50%; background-color: #ccc; margin: 0 10px;"></div>
            <div id="yellowLight" style="display: inline-block; width: 50px; height: 50px; border-radius: 50%; background-color: #ccc; margin: 0 10px;"></div>
            <div id="greenLight" style="display: inline-block; width: 50px; height: 50px; border-radius: 50%; background-color: #ccc; margin: 0 10px;"></div>
        </div>
        <div id="lightInstruction" class="result"></div>
        <div class="code" id="lightCode"></div>
    </div>
    
    <script>
        // Age classifier
        function classifyAge() {
            const age = parseInt(document.getElementById('ageInput').value);
            let category;
            let code = `let age = ${age};\nlet category;\n\n`;
            
            code += `if (age >= 65) {\n    category = "Senior";\n}`;
            code += ` else if (age >= 18) {\n    category = "Adult";\n}`;
            code += ` else if (age >= 13) {\n    category = "Teenager";\n}`;
            code += ` else if (age >= 3) {\n    category = "Child";\n}`;
            code += ` else {\n    category = "Infant";\n}`;
            
            if (age >= 65) {
                category = "Senior";
            } else if (age >= 18) {
                category = "Adult";
            } else if (age >= 13) {
                category = "Teenager";
            } else if (age >= 3) {
                category = "Child";
            } else {
                category = "Infant";
            }
            
            document.getElementById('ageResult').textContent = `Age ${age} is classified as: ${category}`;
            document.getElementById('ageCode').textContent = code;
        }
        
        // Day of week
        function describeDayOfWeek() {
            const day = document.getElementById('dayInput').value;
            let description;
            let code = `let day = "${day}";\nlet description;\n\n`;
            
            code += `switch (day) {\n`;
            code += `    case "Monday":\n        description = "Start of the work week";\n        break;\n`;
            code += `    case "Tuesday":\n    case "Wednesday":\n    case "Thursday":\n`;
            code += `        description = "Mid-week";\n        break;\n`;
            code += `    case "Friday":\n        description = "Almost weekend!";\n        break;\n`;
            code += `    case "Saturday":\n    case "Sunday":\n`;
            code += `        description = "Weekend";\n        break;\n`;
            code += `    default:\n        description = "Invalid day";\n}`;
            
            switch (day) {
                case "Monday":
                    description = "Start of the work week";
                    break;
                case "Tuesday":
                case "Wednesday":
                case "Thursday":
                    description = "Mid-week";
                    break;
                case "Friday":
                    description = "Almost weekend!";
                    break;
                case "Saturday":
                case "Sunday":
                    description = "Weekend";
                    break;
                default:
                    description = "Invalid day";
            }
            
            document.getElementById('dayResult').textContent = `${day} is: ${description}`;
            document.getElementById('dayCode').textContent = code;
        }
        
        // Ticket price
        function calculateTicketPrice() {
            const isStudent = document.getElementById('isStudent').checked;
            const isSenior = document.getElementById('isSenior').checked;
            const regularPrice = 15;
            let price;
            
            let code = `const isStudent = ${isStudent};\n`;
            code += `const isSenior = ${isSenior};\n`;
            code += `const regularPrice = ${regularPrice};\n\n`;
            
            // First with if/else
            code += `// Using if/else\n`;
            code += `let price;\nif (isStudent || isSenior) {\n    price = regularPrice * 0.8; // 20% discount\n} else {\n    price = regularPrice;\n}\n\n`;
            
            // Then with ternary
            code += `// Using ternary operator\n`;
            code += `price = (isStudent || isSenior) ? regularPrice * 0.8 : regularPrice;`;
            
            price = (isStudent || isSenior) ? regularPrice * 0.8 : regularPrice;
            
            document.getElementById('ticketResult').textContent = `Ticket price: $${price.toFixed(2)}` + 
                (isStudent || isSenior ? " (with discount)" : " (regular price)");
            document.getElementById('ticketCode').textContent = code;
        }
        
        // Traffic light
        let currentLight = "red";
        
        function cycleLight() {
            let code = `// Current light: ${currentLight}\n\n`;
            code += `switch (currentLight) {\n`;
            code += `    case "red":\n        currentLight = "green";\n        instruction = "Go!";\n        break;\n`;
            code += `    case "green":\n        currentLight = "yellow";\n        instruction = "Prepare to stop";\n        break;\n`;
            code += `    case "yellow":\n        currentLight = "red";\n        instruction = "Stop!";\n        break;\n`;
            code += `}`;
            
            let instruction;
            
            switch (currentLight) {
                case "red":
                    currentLight = "green";
                    instruction = "Go!";
                    break;
                case "green":
                    currentLight = "yellow";
                    instruction = "Prepare to stop";
                    break;
                case "yellow":
                    currentLight = "red";
                    instruction = "Stop!";
                    break;
            }
            
            // Reset all lights
            document.getElementById('redLight').style.backgroundColor = "#ccc";
            document.getElementById('yellowLight').style.backgroundColor = "#ccc";
            document.getElementById('greenLight').style.backgroundColor = "#ccc";
            
            // Light up current one
            if (currentLight === "red") {
                document.getElementById('redLight').style.backgroundColor = "red";
            } else if (currentLight === "yellow") {
                document.getElementById('yellowLight').style.backgroundColor = "yellow";
            } else {
                document.getElementById('greenLight').style.backgroundColor = "green";
            }
            
            document.getElementById('lightInstruction').textContent = instruction;
            document.getElementById('lightCode').textContent = code;
        }
        
        // Initialize all examples
        classifyAge();
        describeDayOfWeek();
        calculateTicketPrice();
        document.getElementById('redLight').style.backgroundColor = "red";
        document.getElementById('lightInstruction').textContent = "Stop!";
        document.getElementById('lightCode').textContent = "// Initial state: red light";
    </script>
</body>
</html>

Open this file in your browser to interact with different JavaScript conditional structures.

Loops

Loops allow you to execute code repeatedly:

// for loop - use when you know how many iterations you need
for (let i = 0; i < 5; i++) {
    console.log(i);  // Outputs 0, 1, 2, 3, 4
}

// while loop - use when you don't know the number of iterations in advance
let count = 0;
while (count < 5) {
    console.log(count);
    count++;
}

// do...while loop - guarantees at least one execution
do {
    console.log("Executes at least once");
} while (false);

// Breaking and continuing
for (let i = 0; i < 10; i++) {
    if (i === 5) break;        // Exit loop completely
    if (i === 3) continue;     // Skip current iteration and continue with next
    console.log(i);            // Outputs 0, 1, 2, 4
}

Each loop type has its appropriate use cases. The for loop is typically used when iterating a known number of times, while while loops are better for situations where the termination condition depends on factors that might change during execution.

Modern JavaScript also provides more specialized loops like for...of for iterating over iterable objects (like arrays) and for...in for iterating over object properties.

Try It Yourself: Loop Visualizer

Create a file called loops.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Loops</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
        .example { background-color: #f0f0f0; padding: 15px; margin-bottom: 20px; border-radius: 4px; }
        .control-panel { margin-bottom: 15px; }
        label { display: inline-block; margin-right: 10px; }
        input, select { padding: 5px; margin-right: 10px; }
        button { padding: 8px 16px; margin-right: 5px; }
        .output { font-family: monospace; background-color: #eee; padding: 10px; border-radius: 4px; min-height: 100px; max-height: 300px; overflow-y: auto; }
        .step-result { margin-top: 10px; font-weight: bold; }
        .visualization { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 10px; }
        .box { width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; background-color: #ddd; border-radius: 4px; }
        .active { background-color: #5cb85c; color: white; }
        .skipped { background-color: #f0ad4e; color: white; }
        .code { font-family: monospace; background-color: #eee; padding: 10px; border-radius: 4px; white-space: pre; overflow-x: auto; }
    </style>
</head>
<body>
    <h1>JavaScript Loops Visualizer</h1>
    
    <div class="example">
        <h2>For Loop</h2>
        <div class="control-panel">
            <label for="forStart">Start:</label>
            <input type="number" id="forStart" value="0" min="0" style="width: 50px;">
            
            <label for="forEnd">End:</label>
            <input type="number" id="forEnd" value="10" min="0" style="width: 50px;">
            
            <label for="forStep">Step:</label>
            <input type="number" id="forStep" value="1" min="1" style="width: 50px;">
            
            <button onclick="runForLoop()">Run Loop</button>
            <button onclick="stepForLoop()">Step</button>
            <button onclick="resetForLoop()">Reset</button>
        </div>
        <div class="code" id="forLoopCode"></div>
        <div class="step-result" id="forStepResult"></div>
        <div class="visualization" id="forVisualization"></div>
        <div class="output" id="forOutput"></div>
    </div>
    
    <div class="example">
        <h2>While Loop</h2>
        <div class="control-panel">
            <label for="whileCondition">Condition (x < n):</label>
            <input type="number" id="whileCondition" value="5" min="0" style="width: 50px;">
            
            <button onclick="runWhileLoop()">Run Loop</button>
            <button onclick="stepWhileLoop()">Step</button>
            <button onclick="resetWhileLoop()">Reset</button>
        </div>
        <div class="code" id="whileLoopCode"></div>
        <div class="step-result" id="whileStepResult"></div>
        <div class="visualization" id="whileVisualization"></div>
        <div class="output" id="whileOutput"></div>
    </div>
    
    <div class="example">
        <h2>Do-While Loop</h2>
        <div class="control-panel">
            <label for="doWhileCondition">Condition (x < n):</label>
            <input type="number" id="doWhileCondition" value="0" min="0" style="width: 50px;">
            
            <button onclick="runDoWhileLoop()">Run Loop</button>
            <button onclick="stepDoWhileLoop()">Step</button>
            <button onclick="resetDoWhileLoop()">Reset</button>
        </div>
        <div class="code" id="doWhileLoopCode"></div>
        <div class="step-result" id="doWhileStepResult"></div>
        <div class="visualization" id="doWhileVisualization"></div>
        <div class="output" id="doWhileOutput"></div>
    </div>
    
    <div class="example">
        <h2>Break and Continue</h2>
        <div class="control-panel">
            <label for="breakAt">Break at:</label>
            <input type="number" id="breakAt" value="7" min="0" style="width: 50px;">
            
            <label for="continueAt">Continue at:</label>
            <input type="number" id="continueAt" value="3" min="0" style="width: 50px;">
            
            <button onclick="runBreakContinueLoop()">Run Loop</button>
            <button onclick="stepBreakContinueLoop()">Step</button>
            <button onclick="resetBreakContinueLoop()">Reset</button>
        </div>
        <div class="code" id="breakContinueCode"></div>
        <div class="step-result" id="breakContinueStepResult"></div>
        <div class="visualization" id="breakContinueVisualization"></div>
        <div class="output" id="breakContinueOutput"></div>
    </div>
    
    <script>
        // Initialize all code areas and visualizations
        window.onload = function() {
            resetForLoop();
            resetWhileLoop();
            resetDoWhileLoop();
            resetBreakContinueLoop();
        };
        
        // For Loop functionality
        let forLoopState = { current: 0, start: 0, end: 10, step: 1, output: [] };
        
        function updateForLoopCode() {
            const start = forLoopState.start;
            const end = forLoopState.end;
            const step = forLoopState.step;
            
            let code = `for (let i = ${start}; i < ${end}; i += ${step}) {\n`;
            code += `    console.log(i);\n`;
            code += `}`;
            
            document.getElementById('forLoopCode').textContent = code;
        }
        
        function resetForLoop() {
            const start = parseInt(document.getElementById('forStart').value);
            const end = parseInt(document.getElementById('forEnd').value);
            const step = parseInt(document.getElementById('forStep').value);
            
            forLoopState = { current: start, start, end, step, output: [] };
            updateForLoopCode();
            document.getElementById('forOutput').textContent = '';
            document.getElementById('forStepResult').textContent = '';
            
            // Create visualization boxes
            let html = '';
            for (let i = start; i < end; i += step) {
                html += `<div class="box" id="for-box-${i}">${i}</div>`;
            }
            document.getElementById('forVisualization').innerHTML = html;
        }
        
        function stepForLoop() {
            if (forLoopState.current < forLoopState.end) {
                // Clear previous active
                const boxes = document.querySelectorAll('#forVisualization .box');
                boxes.forEach(box => box.classList.remove('active'));
                
                // Log current value
                const current = forLoopState.current;
                forLoopState.output.push(`console.log(${current}); // Iteration ${forLoopState.output.length + 1}`);
                document.getElementById('forOutput').textContent = forLoopState.output.join('\n');
                document.getElementById('forStepResult').textContent = `Current value of i: ${current}`;
                
                // Highlight current box
                const box = document.getElementById(`for-box-${current}`);
                if (box) box.classList.add('active');
                
                // Move to next
                forLoopState.current += forLoopState.step;
                
                // Scroll output to bottom
                const output = document.getElementById('forOutput');
                output.scrollTop = output.scrollHeight;
            } else {
                document.getElementById('forStepResult').textContent = 'Loop complete';
            }
        }
        
        function runForLoop() {
            resetForLoop();
            while (forLoopState.current < forLoopState.end) {
                stepForLoop();
            }
        }
        
        // While Loop functionality
        let whileLoopState = { current: 0, condition: 5, output: [] };

        function updateWhileLoopCode() {
            const condition = whileLoopState.condition;
            
            let code = `let x = 0;\nwhile (x < ${condition}) {\n`;
            code += `    console.log(x);\n`;
            code += `    x++;\n`;
            code += `}`;
            
            document.getElementById('whileLoopCode').textContent = code;
        }

        function resetWhileLoop() {
            const condition = parseInt(document.getElementById('whileCondition').value);
            
            whileLoopState = { current: 0, condition, output: [] };
            updateWhileLoopCode();
            document.getElementById('whileOutput').textContent = '';
            document.getElementById('whileStepResult').textContent = '';
            
            // Create visualization boxes
            let html = '';
            for (let i = 0; i < condition; i++) {
                html += `<div class="box" id="while-box-${i}">${i}</div>`;
            }
            document.getElementById('whileVisualization').innerHTML = html;
        }

        function stepWhileLoop() {
            if (whileLoopState.current < whileLoopState.condition) {
                // Clear previous active
                const boxes = document.querySelectorAll('#whileVisualization .box');
                boxes.forEach(box => box.classList.remove('active'));
                
                // Log current value
                const current = whileLoopState.current;
                whileLoopState.output.push(`console.log(${current}); // x = ${current}`);
                document.getElementById('whileOutput').textContent = whileLoopState.output.join('\n');
                document.getElementById('whileStepResult').textContent = `Current value of x: ${current}`;
                
                // Highlight current box
                const box = document.getElementById(`while-box-${current}`);
                if (box) box.classList.add('active');
                
                // Move to next
                whileLoopState.current++;
                
                // Scroll output to bottom
                const output = document.getElementById('whileOutput');
                output.scrollTop = output.scrollHeight;
            } else {
                document.getElementById('whileStepResult').textContent = 'Loop complete';
            }
        }

        function runWhileLoop() {
            resetWhileLoop();
            while (whileLoopState.current < whileLoopState.condition) {
                stepWhileLoop();
            }
        }

        // Do-While Loop functionality
        let doWhileLoopState = { current: 0, condition: 0, output: [], executed: false };

        function updateDoWhileLoopCode() {
            const condition = doWhileLoopState.condition;
            
            let code = `let x = 0;\ndo {\n`;
            code += `    console.log(x);\n`;
            code += `    x++;\n`;
            code += `} while (x < ${condition});`;
            
            document.getElementById('doWhileLoopCode').textContent = code;
        }

        function resetDoWhileLoop() {
            const condition = parseInt(document.getElementById('doWhileCondition').value);
            
            doWhileLoopState = { current: 0, condition, output: [], executed: false };
            updateDoWhileLoopCode();
            document.getElementById('doWhileOutput').textContent = '';
            document.getElementById('doWhileStepResult').textContent = '';
            
            // Create visualization boxes - always at least 1 box for do-while
            let html = '';
            const maxIter = Math.max(1, condition);
            for (let i = 0; i < maxIter; i++) {
                html += `<div class="box" id="dowhile-box-${i}">${i}</div>`;
            }
            document.getElementById('doWhileVisualization').innerHTML = html;
        }

        function stepDoWhileLoop() {
            if (!doWhileLoopState.executed || doWhileLoopState.current < doWhileLoopState.condition) {
                // Clear previous active
                const boxes = document.querySelectorAll('#doWhileVisualization .box');
                boxes.forEach(box => box.classList.remove('active'));
                
                // Log current value
                const current = doWhileLoopState.current;
                doWhileLoopState.output.push(`console.log(${current}); // x = ${current}`);
                document.getElementById('doWhileOutput').textContent = doWhileLoopState.output.join('\n');
                document.getElementById('doWhileStepResult').textContent = `Current value of x: ${current}`;
                
                // Highlight current box
                const box = document.getElementById(`dowhile-box-${current}`);
                if (box) box.classList.add('active');
                
                // Move to next
                doWhileLoopState.current++;
                doWhileLoopState.executed = true;
                
                // Scroll output to bottom
                const output = document.getElementById('doWhileOutput');
                output.scrollTop = output.scrollHeight;
            } else {
                document.getElementById('doWhileStepResult').textContent = 'Loop complete';
            }
        }

        function runDoWhileLoop() {
            resetDoWhileLoop();
            do {
                stepDoWhileLoop();
            } while (!doWhileLoopState.executed || doWhileLoopState.current < doWhileLoopState.condition);
        }

        // Break and Continue Loop functionality
        let breakContinueState = { current: 0, breakAt: 7, continueAt: 3, output: [], complete: false };

        function updateBreakContinueCode() {
            const breakAt = breakContinueState.breakAt;
            const continueAt = breakContinueState.continueAt;
            
            let code = `for (let i = 0; i < 10; i++) {\n`;
            code += `    if (i === ${breakAt}) {\n`;
            code += `        console.log("Breaking loop at " + i);\n`;
            code += `        break;\n`;
            code += `    }\n`;
            code += `    if (i === ${continueAt}) {\n`;
            code += `        console.log("Skipping " + i);\n`;
            code += `        continue;\n`;
            code += `    }\n`;
            code += `    console.log(i);\n`;
            code += `}`;
            
            document.getElementById('breakContinueCode').textContent = code;
        }

        function resetBreakContinueLoop() {
            const breakAt = parseInt(document.getElementById('breakAt').value);
            const continueAt = parseInt(document.getElementById('continueAt').value);
            
            breakContinueState = { current: 0, breakAt, continueAt, output: [], complete: false };
            updateBreakContinueCode();
            document.getElementById('breakContinueOutput').textContent = '';
            document.getElementById('breakContinueStepResult').textContent = '';
            
            // Create visualization boxes
            let html = '';
            for (let i = 0; i < 10; i++) {
                html += `<div class="box" id="break-box-${i}">${i}</div>`;
            }
            document.getElementById('breakContinueVisualization').innerHTML = html;
        }

        function stepBreakContinueLoop() {
            if (breakContinueState.current < 10 && !breakContinueState.complete) {
                // Clear previous active
                const boxes = document.querySelectorAll('#breakContinueVisualization .box');
                boxes.forEach(box => {
                    box.classList.remove('active');
                    box.classList.remove('skipped');
                });
                
                const current = breakContinueState.current;
                
                // Check for break condition
                if (current === breakContinueState.breakAt) {
                    breakContinueState.output.push(`Breaking loop at ${current}`);
                    document.getElementById('breakContinueOutput').textContent = breakContinueState.output.join('\n');
                    document.getElementById('breakContinueStepResult').textContent = `Breaking loop at i = ${current}`;
                    
                    // Highlight break box
                    const box = document.getElementById(`break-box-${current}`);
                    if (box) box.classList.add('active');
                    
                    breakContinueState.complete = true;
                }
                // Check for continue condition
                else if (current === breakContinueState.continueAt) {
                    breakContinueState.output.push(`Skipping ${current}`);
                    document.getElementById('breakContinueOutput').textContent = breakContinueState.output.join('\n');
                    document.getElementById('breakContinueStepResult').textContent = `Skipping i = ${current}`;
                    
                    // Highlight continue box
                    const box = document.getElementById(`break-box-${current}`);
                    if (box) box.classList.add('skipped');
                    
                    // Move to next
                    breakContinueState.current++;
                }
                // Normal iteration
                else {
                    breakContinueState.output.push(`console.log(${current}); // Iteration ${breakContinueState.output.length + 1}`);
                    document.getElementById('breakContinueOutput').textContent = breakContinueState.output.join('\n');
                    document.getElementById('breakContinueStepResult').textContent = `Current value of i: ${current}`;
                    
                    // Highlight current box
                    const box = document.getElementById(`break-box-${current}`);
                    if (box) box.classList.add('active');
                    
                    // Move to next
                    breakContinueState.current++;
                }
                
                // Scroll output to bottom
                const output = document.getElementById('breakContinueOutput');
                output.scrollTop = output.scrollHeight;
            } else {
                document.getElementById('breakContinueStepResult').textContent = 'Loop complete';
            }
        }

        function runBreakContinueLoop() {
            resetBreakContinueLoop();
            while (breakContinueState.current < 10 && !breakContinueState.complete) {
                stepBreakContinueLoop();
            }
        }
    </script>
</body>
</html>

Open this file in your browser to experiment with different types of loops. The visualizer allows you to:

  • Configure loop parameters (start, end, step values)
  • See the code that will be executed
  • Run the entire loop at once or step through one iteration at a time
  • Visualize the current iteration with colored boxes
  • Watch the output being generated line by line

This interactive tool helps you understand how each loop type works and how break and continue statements affect the flow of execution.

Functions in JavaScript

Functions are reusable blocks of code that perform specific tasks. They help organize code, promote reusability, and create cleaner, more maintainable programs.

Function Declarations

Basic syntax:

function greet(name) {
    return "Hello, " + name;
}

// Calling the function
console.log(greet("Alice"));  // Outputs: "Hello, Alice"

The function declaration creates a named function that can be called anywhere in your code, even before the declaration itself (due to hoisting).

Parameters and arguments:

function add(a, b = 0) {       // Default parameter
    return a + b;
}

add(5, 3);                     // Arguments: a=5, b=3, returns 8
add(5);                        // Uses default value: a=5, b=0, returns 5

Default parameters (introduced in ES6) allow you to specify fallback values for parameters that aren’t provided when the function is called, making your functions more robust.

Try It Yourself: Function Explorer

Create a file called functions.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Functions</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
        .example { background-color: #f0f0f0; padding: 15px; margin-bottom: 20px; border-radius: 4px; }
        .input-group { margin-bottom: 10px; }
        label { display: inline-block; width: 100px; }
        input { padding: 5px; margin-right: 10px; width: 150px; }
        button { padding: 8px 16px; margin: 10px 0; }
        .result { margin-top: 10px; padding: 10px; background-color: #e8f4f8; border-radius: 4px; }
        .code { font-family: monospace; background-color: #eee; padding: 10px; border-radius: 4px; white-space: pre; overflow-x: auto; margin-top: 10px; }
    </style>
</head>
<body>
    <h1>JavaScript Functions Explorer</h1>
    
    <div class="example">
        <h2>Function Declaration</h2>
        <div class="input-group">
            <label for="nameInput">Name:</label>
            <input type="text" id="nameInput" value="World">
        </div>
        <button onclick="testGreet()">Run Function</button>
        <div id="greetResult" class="result"></div>
        <div id="greetCode" class="code"></div>
    </div>
    
    <div class="example">
        <h2>Default Parameters</h2>
        <div class="input-group">
            <label for="num1">First Number:</label>
            <input type="number" id="num1" value="5">
        </div>
        <div class="input-group">
            <label for="num2">Second Number:</label>
            <input type="number" id="num2" placeholder="Optional">
        </div>
        <button onclick="testAdd()">Calculate Sum</button>
        <div id="addResult" class="result"></div>
        <div id="addCode" class="code"></div>
    </div>
    
    <div class="example">
        <h2>Function Expression</h2>
        <div class="input-group">
            <label for="factorialInput">Number:</label>
            <input type="number" id="factorialInput" value="5" min="0" max="20">
        </div>
        <button onclick="testFactorial()">Calculate Factorial</button>
        <div id="factorialResult" class="result"></div>
        <div id="factorialCode" class="code"></div>
    </div>
    
    <div class="example">
        <h2>Arrow Functions</h2>
        <div class="input-group">
            <label for="base">Base:</label>
            <input type="number" id="base" value="2">
        </div>
        <div class="input-group">
            <label for="exponent">Exponent:</label>
            <input type="number" id="exponent" value="3">
        </div>
        <button onclick="testPower()">Calculate Power</button>
        <div id="powerResult" class="result"></div>
        <div id="powerCode" class="code"></div>
    </div>
    
    <script>
        // Display initial code
        document.getElementById('greetCode').textContent = 
            `function greet(name) {\n    return "Hello, " + name;\n}\n\nconsole.log(greet("World"));`;
            
        document.getElementById('addCode').textContent = 
            `function add(a, b = 0) {\n    return a + b;\n}\n\nconsole.log(add(5, 3));\nconsole.log(add(5));`;
            
        document.getElementById('factorialCode').textContent = 
            `const factorial = function(n) {\n    if (n <= 1) return 1;\n    return n * factorial(n - 1);\n};\n\nconsole.log(factorial(5));`;
            
        document.getElementById('powerCode').textContent = 
            `// Arrow function with expression body\nconst power = (base, exponent) => base ** exponent;\n\nconsole.log(power(2, 3)); // 8`;
        
        // Function Declaration example
        function greet(name) {
            return "Hello, " + name;
        }
        
        function testGreet() {
            const name = document.getElementById('nameInput').value || "World";
            const result = greet(name);
            document.getElementById('greetResult').textContent = result;
            
            const code = `function greet(name) {\n    return "Hello, " + name;\n}\n\ngreet("${name}"); // Returns: "${result}"`;
            document.getElementById('greetCode').textContent = code;
        }
        
        // Default Parameters example
        function add(a, b = 0) {
            return a + b;
        }
        
        function testAdd() {
            const a = Number(document.getElementById('num1').value);
            const bInput = document.getElementById('num2').value;
            let code;
            
            if (bInput === "") {
                // Using default parameter
                const result = add(a);
                document.getElementById('addResult').textContent = `${a} + (default) = ${result}`;
                code = `function add(a, b = 0) {\n    return a + b;\n}\n\nadd(${a}); // b uses default value (0)\n// Returns: ${result}`;
            } else {
                // Both parameters provided
                const b = Number(bInput);
                const result = add(a, b);
                document.getElementById('addResult').textContent = `${a} + ${b} = ${result}`;
                code = `function add(a, b = 0) {\n    return a + b;\n}\n\nadd(${a}, ${b}); // Both parameters provided\n// Returns: ${result}`;
            }
            
            document.getElementById('addCode').textContent = code;
        }
        
        // Function Expression example
        const factorial = function(n) {
            if (n <= 1) return 1;
            return n * factorial(n - 1);
        };
        
        function testFactorial() {
            const n = Number(document.getElementById('factorialInput').value);
            const result = factorial(n);
            document.getElementById('factorialResult').textContent = `Factorial of ${n} is ${result}`;
            
            let calculations = "";
            for (let i = n; i > 0; i--) {
                calculations += i + (i > 1 ? " × " : "");
            }
            
            const code = `const factorial = function(n) {\n    if (n <= 1) return 1;\n    return n * factorial(n - 1);\n};\n\nfactorial(${n});\n// Calculation: ${calculations} = ${result}`;
            document.getElementById('factorialCode').textContent = code;
        }
        
        // Arrow Function example
        const power = (base, exponent) => base ** exponent;
        
        function testPower() {
            const base = Number(document.getElementById('base').value);
            const exponent = Number(document.getElementById('exponent').value);
            const result = power(base, exponent);
            document.getElementById('powerResult').textContent = `${base}^${exponent} = ${result}`;
            
            const code = `// Arrow function with expression body\nconst power = (base, exponent) => base ** exponent;\n\npower(${base}, ${exponent}); // Returns: ${result}`;
            document.getElementById('powerCode').textContent = code;
        }
    </script>
</body>
</html>

Open this file in your browser to experiment with different types of functions. The interactive examples allow you to:

  • See the syntax for different function types
  • Provide input values to test the functions
  • View the results and understand how parameters work
  • Explore special features like default parameters and recursion

Function Expressions

Function expressions define functions as part of a larger expression, typically a variable assignment:

const multiply = function(x, y) {
    return x * y;
};

console.log(multiply(4, 5));  // Outputs: 20

Unlike function declarations, function expressions are not hoisted, meaning they can only be called after they’re defined in the code.

Arrow Functions

Arrow functions (introduced in ES6) provide a more concise syntax for writing functions:

const square = (x) => x * x;
const greet = name => `Hello, ${name}`;
const sum = (a, b) => {
    const result = a + b;
    return result;
};

Arrow functions have implicit returns when the function body is a single expression (no curly braces). They also don’t bind their own this value, which can be beneficial in certain contexts like callbacks and methods.

Function Scope

Functions create their own scope, and variables declared inside functions are not accessible outside:

function example() {
    let local = "I'm local";
    console.log(local);        // Works
}
// console.log(local);         // Would cause error: local is not defined

Understanding scope is crucial to avoid unintended variable access or modification. Variables declared with let and const are block-scoped, while those declared with var are function-scoped.

Functions can access variables from their containing scope (lexical scoping), but outer scopes cannot access variables declared within inner scopes.

What’s Next?

Congratulations on completing the JavaScript fundamentals section! You now have a solid understanding of JavaScript’s core language features, control structures, and functions.

In the next document, “JavaScript and the DOM,” we’ll explore how to use these JavaScript skills to interact with web pages through the Document Object Model (DOM). You’ll learn how to select, modify, create, and delete HTML elements, as well as how to respond to user interactions through event handling.

Ready to bring your web pages to life with JavaScript? Continue to the next section to learn about JavaScript and the DOM.

You May Also Like