Web Development

JavaScript basics

JavaScript brings interactivity to websites. It runs in the browser and lets you respond to user actions, manipulate the DOM, and fetch data from APIs.


Variables and Data Types

JavaScript has three ways to declare variables: var, let, and const. Prefer const by default and use let when you need to reassign.

const name = 'John'
let count = 0
count = count + 1
const numbers = [1, 2, 3, 4, 5]
const user = { name: 'John', age: 30 }

Common Data Types

JavaScript values are one of: string, number, boolean, null, undefined, object, or symbol. Arrays and functions are also objects under the hood.

const ไม่ได้แปลว่าเปลี่ยนแปลงไม่ได้ทั้งหมด

const ป้องกันการ reassign ตัวแปร แต่ถ้าเป็น object หรือ array คุณยังสามารถแก้ไขข้อมูลข้างในได้ เช่น user.age = 31 ยังทำได้แม้ว่า user จะเป็น const


Functions

Functions let you group reusable logic. You can define them with the function keyword or as arrow functions.

function greet(name) {
return 'Hello, ' + name + '!'
}
const double = (n) => n * 2
console.log(greet('World')) // Hello, World!
console.log(double(5)) // 10

Arrow Functions

Arrow functions (=>) are a shorter way to write functions. They're especially common in callbacks and when working with arrays.

const numbers = [1, 2, 3, 4, 5]
const doubled = numbers.map((n) => n * 2) // [2, 4, 6, 8, 10]
const evens = numbers.filter((n) => n % 2 === 0) // [2, 4]
const sum = numbers.reduce((acc, n) => acc + n, 0) // 15

DOM Manipulation

The Document Object Model (DOM) is a tree representation of your HTML. JavaScript can read and modify it to update the page dynamically.

const button = document.querySelector('#my-button')
button.addEventListener('click', () => {
document.querySelector('#message').textContent = 'Button clicked!'
})

Selecting Elements

Use querySelector to select one element, or querySelectorAll to select multiple. Both accept any valid CSS selector.

const title = document.querySelector('h1')
const items = document.querySelectorAll('.list-item')
const form = document.querySelector('#signup-form')
title.style.color = 'blue'
items.forEach((item) => item.classList.add('active'))

Fetching Data

Use the fetch API to load data from a server without reloading the page.

async function loadUser(id) {
const response = await fetch('/api/users/' + id)
const user = await response.json()
return user
}
loadUser(1).then((user) => {
console.log(user.name)
})

fetch ใช้ async/await เสมอ

fetch เป็น asynchronous operation ถ้าไม่ใช้ await คุณจะได้ Promise object กลับมา ไม่ใช่ข้อมูลจริง

Previous
HTML & CSS