1.2 JavaScript BasicsJavaScript基础

Web Development Fundamentals

🌐 What is JavaScript?

JavaScript is a versatile programming language primarily used for web development. It enables interactive pages, dynamic updates, and powers modern web applications. It runs in browsers and can also be used server-side. JavaScript 是一种用途广泛的编程语言,主要用于 Web 开发。它能实现页面交互、动态更新,是现代 Web 应用的基础;既可在浏览器端运行,也可用于服务器端。

graph TD A[JavaScript] --> B[Client-side] A --> C[Server-side] A --> D[Mobile Apps] A --> E[Desktop Apps] B --> B1[DOM Manipulation] B --> B2[Event Handling] B --> B3[Form Validation] C --> C1[Node.js] C --> C2[Express.js] C --> C3[API Development] style A fill:#e07a5f,stroke:#333,stroke-width:2px style B fill:#81b29a,stroke:#333,stroke-width:2px style C fill:#f2cc8f,stroke:#333,stroke-width:2px

📦 Variables and Data Types

Variable Declaration

// Modern ES6+ variable declarations
let message = "Hello, World!";        // Can be reassigned
const PI = 3.14159;                   // Cannot be reassigned
var oldStyle = "Still works";          // Old style, avoid

// Variable naming conventions
let userName = "evan";                 // camelCase
let user_age = 19;                     // snake_case (less common)
let UserEmail = "evan@example.com";    // PascalCase (for constructors)

Data Types

// Primitive types
let name = "Evan";                     // String
let age = 19;                          // Number
let isStudent = true;                  // Boolean
let course = null;                     // Null
let subject;                           // Undefined
let id = Symbol("unique");             // Symbol (ES6)

// Reference types
let grades = [85, 92, 78];             // Array
let person = {                         // Object
    name: "Evan",
    age: 19,
    courses: ["COMP1531", "COMP1511"]
};

let greet = function() {              // Function
    return "Hello!";
};

⚡ Functions

Function Declarations

// Function declaration
function add(a, b) {
    return a + b;
}

// Function expression
const multiply = function(a, b) {
    return a * b;
};

// Arrow function (ES6+)
const divide = (a, b) => a / b;

// Arrow function with multiple statements
const calculate = (a, b, operation) => {
    switch(operation) {
        case 'add': return a + b;
        case 'subtract': return a - b;
        case 'multiply': return a * b;
        case 'divide': return a / b;
        default: return 0;
    }
};

Function Parameters

// Default parameters
function greet(name = "Student") {
    return `Hello, ${name}!`;
}

// Rest parameters
function sum(...numbers) {
    return numbers.reduce((total, num) => total + num, 0);
}

// Destructuring parameters
function displayUser({name, age, courses}) {
    return `${name} (${age}) is taking ${courses.join(', ')}`;
}

const user = {
    name: "Evan",
    age: 19,
    courses: ["COMP1531", "COMP1511"]
};

🔄 Control Flow

Conditional Statements

// If-else statements
let grade = 85;

if (grade >= 90) {
    console.log("A+");
} else if (grade >= 80) {
    console.log("A");
} else if (grade >= 70) {
    console.log("B");
} else {
    console.log("C or below");
}

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

// Ternary operator
let status = age >= 18 ? "Adult" : "Minor";

Loops

// For loop
for (let i = 0; i < 5; i++) {
    console.log(`Iteration ${i}`);
}

// While loop
let count = 0;
while (count < 5) {
    console.log(`Count: ${count}`);
    count++;
}

// For...of loop (for arrays)
let courses = ["COMP1531", "COMP1511", "MATH1081"];
for (let course of courses) {
    console.log(course);
}

// For...in loop (for objects)
let student = {name: "Evan", age: 19, grade: "A"};
for (let key in student) {
    console.log(`${key}: ${student[key]}`);
}

// Array methods (functional approach)
courses.forEach(course => console.log(course));
let upperCourses = courses.map(course => course.toUpperCase());

📋 Objects and Arrays

Working with Objects

// Object creation
let student = {
    name: "Evan",
    age: 19,
    courses: ["COMP1531", "COMP1511"],
    isActive: true,
    
    // Method
    getInfo: function() {
        return `${this.name} is ${this.age} years old`;
    }
};

// Accessing properties
console.log(student.name);           // Dot notation
console.log(student["age"]);         // Bracket notation

// Adding/modifying properties
student.grade = "A";
student.courses.push("MATH1081");

// Object methods
console.log(Object.keys(student));   // Get all keys
console.log(Object.values(student)); // Get all values
console.log(Object.entries(student)); // Get key-value pairs

// Destructuring
let {name, age, courses} = student;
console.log(name);                   // "Evan"

Working with Arrays

// Array creation
let numbers = [1, 2, 3, 4, 5];
let fruits = new Array("Apple", "Banana", "Orange");

// Array methods
numbers.push(6);                     // Add to end
numbers.unshift(0);                  // Add to beginning
numbers.pop();                       // Remove from end
numbers.shift();                     // Remove from beginning

// Array iteration
numbers.forEach(num => console.log(num));

// Array transformation
let doubled = numbers.map(num => num * 2);
let evenNumbers = numbers.filter(num => num % 2 === 0);
let sum = numbers.reduce((total, num) => total + num, 0);

// Array searching
let found = numbers.find(num => num > 3);
let foundIndex = numbers.findIndex(num => num > 3);
let includesThree = numbers.includes(3);

🎨 DOM Manipulation

Selecting Elements

// Selecting elements
let element = document.getElementById("myId");
let elements = document.getElementsByClassName("myClass");
let tags = document.getElementsByTagName("div");
let selector = document.querySelector(".myClass");
let selectors = document.querySelectorAll("div.myClass");

// Example HTML structure
/*
<div id="container">
    <h1 class="title">Hello World</h1>
    <p class="content">This is a paragraph</p>
    <button id="clickMe">Click Me</button>
</div>
*/

Modifying Elements

// Changing content
document.querySelector(".title").textContent = "New Title";
document.querySelector(".content").innerHTML = "<strong>Bold</strong> text";

// Changing styles
document.getElementById("container").style.backgroundColor = "#f0f0f0";
document.querySelector(".title").style.color = "#e07a5f";

// Adding/removing classes
document.getElementById("container").classList.add("highlight");
document.getElementById("container").classList.remove("old-class");
document.getElementById("container").classList.toggle("active");

// Creating elements
let newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph";
newParagraph.classList.add("content");
document.getElementById("container").appendChild(newParagraph);

🎯 Event Handling

Event Listeners

// Adding event listeners
document.getElementById("clickMe").addEventListener("click", function() {
    alert("Button clicked!");
});

// Using arrow function
document.getElementById("clickMe").addEventListener("click", () => {
    console.log("Button was clicked");
});

// Event object
document.getElementById("clickMe").addEventListener("click", (event) => {
    console.log("Event type:", event.type);
    console.log("Target element:", event.target);
    console.log("Mouse position:", event.clientX, event.clientY);
});

// Multiple events
let button = document.getElementById("clickMe");
button.addEventListener("click", handleClick);
button.addEventListener("mouseover", handleMouseOver);
button.addEventListener("mouseout", handleMouseOut);

function handleClick() {
    console.log("Button clicked");
}

function handleMouseOver() {
    this.style.backgroundColor = "#e07a5f";
}

function handleMouseOut() {
    this.style.backgroundColor = "";
}

Common Events

// Form events
document.getElementById("myForm").addEventListener("submit", (e) => {
    e.preventDefault();  // Prevent form submission
    console.log("Form submitted");
});

// Input events
document.getElementById("username").addEventListener("input", (e) => {
    console.log("Input value:", e.target.value);
});

// Keyboard events
document.addEventListener("keydown", (e) => {
    console.log("Key pressed:", e.key);
});

// Window events
window.addEventListener("resize", () => {
    console.log("Window resized");
});

window.addEventListener("load", () => {
    console.log("Page fully loaded");
});

🚀 Practical Example: Interactive To-Do List

<!-- HTML Structure -->
<!DOCTYPE html>
<html>
<head>
    <title>To-Do List</title>
    <style>
        .todo-item { 
            padding: 10px; 
            margin: 5px 0; 
            background: #f0f0f0; 
            border-radius: 5px; 
        }
        .completed { 
            text-decoration: line-through; 
            opacity: 0.6; 
        }
        .delete-btn { 
            float: right; 
            background: #e07a5f; 
            color: white; 
            border: none; 
            padding: 5px 10px; 
            border-radius: 3px; 
            cursor: pointer; 
        }
    </style>
</head>
<body>
    <div id="app">
        <h1>My To-Do List</h1>
        <input type="text" id="todoInput" placeholder="Add a new task">
        <button id="addBtn">Add</button>
        <div id="todoList"></div>
    </div>

    <script>
        // JavaScript functionality
        let todos = [];
        const todoInput = document.getElementById("todoInput");
        const addBtn = document.getElementById("addBtn");
        const todoList = document.getElementById("todoList");

        // Add new todo
        function addTodo() {
            const text = todoInput.value.trim();
            if (text !== "") {
                todos.push({
                    id: Date.now(),
                    text: text,
                    completed: false
                });
                todoInput.value = "";
                renderTodos();
            }
        }

        // Toggle todo completion
        function toggleTodo(id) {
            todos = todos.map(todo => 
                todo.id === id ? { ...todo, completed: !todo.completed } : todo
            );
            renderTodos();
        }

        // Delete todo
        function deleteTodo(id) {
            todos = todos.filter(todo => todo.id !== id);
            renderTodos();
        }

        // Render todos
        function renderTodos() {
            todoList.innerHTML = "";
            todos.forEach(todo => {
                const todoItem = document.createElement("div");
                todoItem.className = `todo-item ${todo.completed ? "completed" : ""}`;
                
                todoItem.innerHTML = `
                    <span onclick="toggleTodo(${todo.id})">${todo.text}</span>
                    <button class="delete-btn" onclick="deleteTodo(${todo.id})">Delete</button>
                `;
                
                todoList.appendChild(todoItem);
            });
        }

        // Event listeners
        addBtn.addEventListener("click", addTodo);
        todoInput.addEventListener("keypress", (e) => {
            if (e.key === "Enter") {
                addTodo();
            }
        });

        // Initial render
        renderTodos();
    </script>
</body>
</html>

📋 Summary总结

💭 Thinking Thinking & Practice Practice思考与实践