跳到主要内容

JavaScript Core Concepts

Asynchronous Programming

1. Promises

// Creating a promise
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
const data = { id: 1, name: 'John' };
resolve(data);
// reject(new Error('Failed to fetch'));
}, 1000);
});

// Using promises
fetchData.then((data) => console.log(data)).catch((error) => console.error(error));

2. Async/Await

async function getData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}

Modules

1. ES Modules

// math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

// main.js
import { add, subtract } from './math.js';

2. Module Patterns

// Default exports
export default class User {
constructor(name) {
this.name = name;
}
}

// Named exports
export const config = {
apiUrl: 'https://api.example.com',
};

Modern JavaScript Features

1. Destructuring

// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];

// Object destructuring
const { name, age, ...other } = person;

// Nested destructuring
const {
address: { city, country },
} = user;

2. Spread Operator

// Array spread
const combined = [...array1, ...array2];

// Object spread
const updated = { ...object, newProp: value };

// Function arguments
const numbers = [1, 2, 3];
Math.max(...numbers);

3. Optional Chaining

// Without optional chaining
const city = user && user.address && user.address.city;

// With optional chaining
const city = user?.address?.city;

// With function calls
const result = obj.method?.();

Classes and OOP

1. Class Syntax

class Animal {
constructor(name) {
this.name = name;
}

speak() {
return `${this.name} makes a sound`;
}

static create(name) {
return new Animal(name);
}
}

class Dog extends Animal {
speak() {
return `${this.name} barks`;
}
}

2. Private Fields

class BankAccount {
#balance = 0;

deposit(amount) {
this.#balance += amount;
}

get balance() {
return this.#balance;
}
}

Functional Programming

1. Higher-Order Functions

// Map, Filter, Reduce
const numbers = [1, 2, 3, 4, 5];

const doubled = numbers.map((n) => n * 2);
const evens = numbers.filter((n) => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);

2. Pure Functions

// Pure function
const add = (a, b) => a + b;

// Impure function (avoid)
let total = 0;
const addToTotal = (n) => (total += n);

Memory Management

1. Garbage Collection

// Memory is automatically managed
let obj = { data: 'some data' };
obj = null; // Object becomes eligible for garbage collection

2. Memory Leaks

// Common memory leak (avoid)
const elements = [];
document.querySelectorAll('div').forEach((el) => {
elements.push(el); // Keeps references to DOM elements
});

Best Practices

1. Code Organization

  • Use modules for better organization
  • Follow single responsibility principle
  • Implement proper error handling
  • Write maintainable async code

2. Performance

  • Use appropriate data structures
  • Optimize async operations
  • Implement proper caching
  • Minimize DOM operations

3. Security

  • Validate input data
  • Sanitize output
  • Use secure dependencies
  • Implement proper authentication

Next Steps

  1. Practice with real-world projects
  2. Learn popular frameworks and libraries
  3. Explore advanced JavaScript patterns