JavaScript Beginner Guide

JavaScript for beginnersJavaScript สำหรับผู้เริ่มต้น

JavaScript Beginner Guide

The language of the web, from values to async/awaitภาษาของเว็บ ตั้งแต่ค่าพื้นฐานจนถึง async/await

JavaScript runs in every browser, on servers with Node.js, and in the build tools behind most websites. This guide covers the language itself: types, strings, arrays, objects, functions, classes, errors, asynchronous code, modules and the page (the DOM). Every example runs in your browser. Change the code, press Run, and see what happens. JavaScript ทำงานในทุกเบราว์เซอร์ บนเซิร์ฟเวอร์ด้วย Node.js และในเครื่องมือ build ของเว็บไซต์ส่วนใหญ่ คู่มือนี้สอนตัวภาษาเอง ได้แก่ ชนิดข้อมูล ข้อความ อาร์เรย์ ออบเจกต์ ฟังก์ชัน คลาส ข้อผิดพลาด โค้ดแบบ asynchronous โมดูล และตัวหน้าเว็บ (DOM) ทุกตัวอย่างรันในเบราว์เซอร์ได้ ลองแก้โค้ด กด Run แล้วดูว่าเกิดอะไรขึ้น

Each example first shows the output it printed with Node.js 22, and the same code was run in a real browser before this page was published, with identical output. if, loops and basic arrays are covered in Logic & Loops; this guide starts where that one ends. ทุกตัวอย่างแสดงผลลัพธ์ที่ได้จากการรันด้วย Node.js 22 ไว้ก่อน และก่อนเผยแพร่หน้านี้ โค้ดชุดเดียวกันถูกรันในเบราว์เซอร์จริงแล้วได้ผลตรงกัน เรื่อง if ลูป และอาร์เรย์เบื้องต้นอยู่ใน Logic & Loops คู่มือนี้เริ่มต่อจากตรงนั้น

Shortcut: pressคีย์ลัด: กด Ctrl+Enter (⌘+Enter Mac) inside a code box to run it.ในกล่องโค้ดเพื่อรันทันที

  • Recorded withบันทึกด้วย Node.js 22.21
  • Runs inรันใน your browserเบราว์เซอร์ของคุณ
  • Syntaxไวยากรณ์ ES2024

Lesson 1 · Setupบทที่ 1 · ติดตั้ง

Getting startedเริ่มต้นใช้งาน

You already have JavaScript: every browser runs it. Open the developer tools (F12, or ⌘+⌥+J on a Mac), click Console, and type 1 + 2. To run files on your computer, install Node.js (the LTS version), which runs JavaScript outside the browser. คุณมี JavaScript อยู่แล้ว เพราะทุกเบราว์เซอร์รันได้ เปิดเครื่องมือนักพัฒนา (F12 หรือ ⌘+⌥+J บน Mac) คลิก Console แล้วพิมพ์ 1 + 2 ถ้าจะรันไฟล์บนเครื่อง ให้ติดตั้ง Node.js (เวอร์ชัน LTS) ซึ่งรัน JavaScript นอกเบราว์เซอร์ได้

Terminalเทอร์มินัลnode v22.21.1 · macOS
$ node --version
v22.21.1

$ node hello.js
Hello, world!
1 + 2 = 3

On a web page, JavaScript goes in a <script> tag, usually just before </body> or in its own file: บนหน้าเว็บ JavaScript อยู่ในแท็ก <script> มักวางไว้ก่อน </body> หรือแยกเป็นไฟล์ของตัวเอง:

Tipเคล็ดลับ

console.log is your best debugging tool. When something doesn't work, print the value you're unsure about. In the browser the output appears in DevTools; in Node it appears in the terminal.console.log คือเครื่องมือดีบักที่ดีที่สุด เมื่อมีอะไรไม่ทำงาน ให้พิมพ์ค่าที่ไม่แน่ใจออกมาดู ในเบราว์เซอร์ผลลัพธ์จะอยู่ใน DevTools ส่วนใน Node จะอยู่ในเทอร์มินัล

Lesson 2 · The basicsบทที่ 2 · พื้นฐาน

Values & typesค่าและชนิดข้อมูล

Use const for values that won't be reassigned, and let for those that will. Avoid var, the old form. JavaScript has a handful of basic types; typeof tells you which one a value is. ใช้ const กับค่าที่จะไม่กำหนดใหม่ และ let กับค่าที่จะเปลี่ยน หลีกเลี่ยง var ซึ่งเป็นรูปแบบเก่า JavaScript มีชนิดข้อมูลพื้นฐานไม่กี่ชนิด และ typeof บอกได้ว่าค่าหนึ่งเป็นชนิดไหน

TypeชนิดExampleตัวอย่างNotesหมายเหตุ
number21, 1.62whole numbers and decimals are the same typeจำนวนเต็มและทศนิยมเป็นชนิดเดียวกัน
string"Mya"text, in ", ' or `ข้อความ ใน ", ' หรือ `
booleantruetrue or falseจริงหรือเท็จ
undefinedlet x;"no value was given""ยังไม่ได้ให้ค่า"
nullnull"empty on purpose""ว่างโดยตั้งใจ"
object{}, []objects and arrays (lessons 4–5)ออบเจกต์และอาร์เรย์ (บทที่ 4–5)

=== compares value and type; == converts types first, which surprises people. Every value also counts as truthy or falsy in an if: the falsy ones are false, 0, "", null, undefined and NaN. Everything else is truthy, even "0" and []. === เปรียบเทียบทั้งค่าและชนิด ส่วน == แปลงชนิดก่อน ซึ่งมักทำให้งง ทุกค่ายังนับเป็น truthy หรือ falsy เมื่ออยู่ใน if ค่าที่เป็น falsy ได้แก่ false, 0, "", null, undefined และ NaN นอกนั้นเป็น truthy ทั้งหมด แม้แต่ "0" และ []

Ruleกฎ

Always use === and !==. Use ?? rather than || for defaults when 0 or "" are valid values.ใช้ === และ !== เสมอ และใช้ ?? แทน || สำหรับค่าเริ่มต้น เมื่อ 0 หรือ "" เป็นค่าที่ใช้ได้

Lesson 3 · Textบทที่ 3 · ข้อความ

Stringsข้อความ (string)

Template literals use backticks and ${…} to put values into text, and can span several lines. Strings never change in place: every method returns a new string. template literal ใช้เครื่องหมาย backtick และ ${…} เพื่อใส่ค่าลงในข้อความ และเขียนหลายบรรทัดได้ string ไม่เปลี่ยนแปลงในตัวเอง ทุก method จะคืน string ใหม่

Thai text, emoji and formattingข้อความไทย อีโมจิ และการจัดรูปแบบ

length counts UTF-16 units. Thai letters are one unit each, so Thai is counted correctly, but an emoji takes two. Spread a string into an array ([...s]) to count real characters. Intl formats numbers and dates for any language. length นับเป็นหน่วย UTF-16 ตัวอักษรไทยใช้ตัวละหนึ่งหน่วย จึงนับภาษาไทยได้ถูกต้อง แต่อีโมจิใช้สองหน่วย ให้กระจาย string เป็นอาร์เรย์ ([...s]) เพื่อนับตัวอักษรจริง ส่วน Intl จัดรูปแบบตัวเลขและวันที่ได้ทุกภาษา

Lesson 4 · Listsบทที่ 4 · รายการ

Arraysอาร์เรย์

Modern JavaScript rarely loops over arrays by hand. map transforms every item, filter keeps some, reduce combines them into one value, and find returns the first match. They return new arrays and leave the original alone. JavaScript สมัยใหม่ไม่ค่อยวนลูปอาร์เรย์เอง map แปลงทุกสมาชิก filter เก็บไว้บางตัว reduce รวมทุกตัวเป็นค่าเดียว และ find คืนตัวแรกที่ตรง method เหล่านี้คืนอาร์เรย์ใหม่และไม่แตะอาร์เรย์เดิม

Spread (...) copies an array or merges several. Destructuring pulls values out by position. And watch out: sort() without a compare function sorts as text, and it changes the array itself. spread (...) ใช้คัดลอกอาร์เรย์หรือรวมหลายอาร์เรย์ destructuring ดึงค่าออกมาตามตำแหน่ง และระวัง: sort() ที่ไม่ได้ส่งฟังก์ชันเปรียบเทียบจะเรียงแบบข้อความ และเปลี่ยนอาร์เรย์เดิมด้วย

Lesson 5 · Recordsบทที่ 5 · ระเบียนข้อมูล

Objects & JSONออบเจกต์และ JSON

An object groups named values. Read with user.name or user["name"]. Destructuring pulls fields into variables, spread makes a copy with changes, and optional chaining (?.) reads safely through values that might be missing. ออบเจกต์รวมค่าที่มีชื่อเข้าด้วยกัน อ่านค่าด้วย user.name หรือ user["name"] destructuring ดึงฟิลด์ออกมาเป็นตัวแปร spread สร้างสำเนาพร้อมการเปลี่ยนแปลง และ optional chaining (?.) อ่านค่าอย่างปลอดภัยผ่านค่าที่อาจไม่มีอยู่

JSON is the text format APIs use to send data. It looks like a JavaScript object, but keys must be in double quotes. JSON.stringify turns a value into JSON text and JSON.parse turns it back. JSON คือรูปแบบข้อความที่ API ใช้ส่งข้อมูล หน้าตาคล้ายออบเจกต์ของ JavaScript แต่คีย์ต้องอยู่ในเครื่องหมายคำพูดคู่ JSON.stringify แปลงค่าเป็นข้อความ JSON และ JSON.parse แปลงกลับ

Lesson 6 · Reuseบทที่ 6 · การนำกลับมาใช้ซ้ำ

Functionsฟังก์ชัน

Arrow functions ((a, b) => a + b) are the short form you'll see everywhere. Functions are values: you can store them, pass them to other functions (callbacks), and return them. A function that remembers variables from where it was created is a closure. arrow function ((a, b) => a + b) คือรูปแบบสั้นที่เห็นได้ทุกที่ ฟังก์ชันเป็นค่า จึงเก็บไว้ในตัวแปร ส่งให้ฟังก์ชันอื่น (callback) และคืนออกมาได้ ฟังก์ชันที่จำตัวแปรจากที่ที่มันถูกสร้างไว้ เรียกว่า closure

Lesson 7 · Objects with behaviourบทที่ 7 · ออบเจกต์ที่มีพฤติกรรม

Classesคลาส

A class is a template for objects that share methods. #balance is a private field: code outside the class can't read or change it. extends builds a new class on top of another. class คือแม่แบบของออบเจกต์ที่ใช้ method ร่วมกัน #balance คือ private field โค้ดนอกคลาสอ่านหรือแก้ไม่ได้ ส่วน extends สร้างคลาสใหม่ต่อยอดจากคลาสเดิม

Lesson 8 · When things go wrongบทที่ 8 · เมื่อเกิดปัญหา

Errorsข้อผิดพลาด

throw stops the current code and jumps to the nearest catch. Throw Error objects (not strings) so you get a name, a message and a stack trace. Extend Error to make your own kinds of error. throw หยุดโค้ดปัจจุบันแล้วกระโดดไปที่ catch ที่ใกล้ที่สุด ให้ throw ออบเจกต์ Error (ไม่ใช่ string) เพื่อจะได้ชื่อ ข้อความ และ stack trace และ extends Error เพื่อสร้างชนิดข้อผิดพลาดของตัวเอง

Lesson 9 · Waitingบทที่ 9 · การรอ

Async & awaitAsync และ await

JavaScript runs one piece of code at a time. Slow work (timers, network requests, files) is handed off, and its callback runs later, once the current code has finished. That's why the order below isn't top to bottom. JavaScript รันโค้ดทีละชิ้น งานที่ช้า (timer การเรียกเครือข่าย ไฟล์) จะถูกส่งต่อออกไป แล้ว callback ของมันจะทำงานทีหลัง เมื่อโค้ดปัจจุบันทำงานเสร็จ นี่คือเหตุผลที่ลำดับด้านล่างไม่ได้เรียงจากบนลงล่าง

A Promise is a value that arrives later. await pauses an async function until the promise settles, so asynchronous code reads like normal code. Promise.all waits for several at once, in parallel. Promise คือค่าที่จะมาถึงทีหลัง await หยุดฟังก์ชัน async ไว้จนกว่า promise จะเสร็จ ทำให้โค้ด asynchronous อ่านได้เหมือนโค้ดปกติ ส่วน Promise.all รอหลายตัวพร้อมกันแบบขนาน

In real code, the slow call is usually fetch, which loads data from a URL: ในโค้ดจริง การเรียกที่ช้ามักเป็น fetch ซึ่งโหลดข้อมูลจาก URL:

Lesson 10 · Organising codeบทที่ 10 · จัดระเบียบโค้ด

Modulesโมดูล

A module is a file that exports what other files may use; they import it. Each module has its own scope, so names don't clash. This ran in a real terminal with Node: the .mjs extension tells Node the files are modules. โมดูลคือไฟล์ที่ export สิ่งที่ไฟล์อื่นใช้ได้ แล้วไฟล์อื่น import เข้าไป แต่ละโมดูลมีขอบเขตของตัวเอง ชื่อจึงไม่ชนกัน ตัวอย่างนี้รันในเทอร์มินัลจริงด้วย Node นามสกุล .mjs บอก Node ว่าไฟล์เหล่านี้เป็นโมดูล

Terminalเทอร์มินัลnode v22.21.1 · macOS
$ node main.mjs
VAT 7%: ฿87.50
Total: ฿1,337.50
  • Named exports (export function vat) are imported by name in braces. A file has at most one default export, imported without braces.named export (export function vat) import ด้วยชื่อในวงเล็บปีกกา แต่ละไฟล์มี default export ได้ไม่เกินหนึ่งตัว และ import โดยไม่ต้องมีวงเล็บปีกกา
  • In a Node project, add "type": "module" to package.json to use .js instead of .mjs.ในโปรเจกต์ Node ให้เพิ่ม "type": "module" ใน package.json เพื่อใช้ .js แทน .mjs
  • In the browser, load the entry file with <script type="module" src="main.js">.ในเบราว์เซอร์ ให้โหลดไฟล์เริ่มต้นด้วย <script type="module" src="main.js">

Lesson 11 · The pageบทที่ 11 · หน้าเว็บ

The DOMDOM

The DOM is the page as JavaScript sees it: a tree of elements you can find, change and listen to. These labs run in a small sandboxed page under the editor. Press Run, then click the buttons yourself. DOM คือหน้าเว็บในมุมมองของ JavaScript เป็นต้นไม้ขององค์ประกอบที่ค้นหา เปลี่ยนแปลง และดักฟังเหตุการณ์ได้ แล็บเหล่านี้รันในหน้าเว็บเล็กๆ แบบ sandbox ใต้ตัวแก้โค้ด กด Run แล้วลองคลิกปุ่มด้วยตัวเอง

Create elements with document.createElement and add them with append. Put user text in with textContent, never innerHTML: textContent shows <b> as text instead of running it as HTML. สร้างองค์ประกอบด้วย document.createElement แล้วเพิ่มด้วย append ใส่ข้อความจากผู้ใช้ด้วย textContent ห้ามใช้ innerHTML เพราะ textContent แสดง <b> เป็นข้อความแทนการตีความเป็น HTML

Codeโค้ดDoesทำอะไร
document.querySelector("#id")the first element matching a CSS selectorองค์ประกอบแรกที่ตรงกับ CSS selector
document.querySelectorAll(".item")every match, as a listทุกตัวที่ตรง ในรูปรายการ
el.textContent = "…"set the text (safe)กำหนดข้อความ (ปลอดภัย)
el.classList.toggle("done")add or remove a CSS classเพิ่มหรือลบ CSS class
el.addEventListener("click", fn)run fn on every clickรัน fn ทุกครั้งที่คลิก
document.createElement("li")make a new elementสร้างองค์ประกอบใหม่

Lesson 12 · Your turnบทที่ 12 · ถึงตาคุณแล้ว

Practiceแบบฝึกหัด

Write the code, press Run, and compare with the solution when you're done. Every solution was run with Node, and its output is shown under it. เขียนโค้ด กด Run แล้วเทียบกับเฉลยเมื่อเสร็จ ทุกเฉลยถูกรันด้วย Node และแสดงผลลัพธ์ไว้ด้านล่าง

1. Shopping total1. ยอดรวมการซื้อ

Use reduce to total price × qty, then print it with two decimals.ใช้ reduce หาผลรวมของ ราคา × จำนวน แล้วพิมพ์เป็นทศนิยมสองตำแหน่ง

2. Group by first letter2. จัดกลุ่มตามตัวอักษรแรก

Build an object whose keys are first letters and whose values are arrays of names.สร้างออบเจกต์ที่คีย์เป็นตัวอักษรแรก และค่าเป็นอาร์เรย์ของชื่อ

3. Count the words3. นับคำ

Count each word in the sentence with a Map, then print the three most common.นับแต่ละคำในประโยคด้วย Map แล้วพิมพ์สามคำที่พบบ่อยที่สุด

4. Retry until it works4. ลองใหม่จนกว่าจะสำเร็จ

flaky() fails twice, then succeeds. Write retry(fn, times) that awaits fn, and tries again after an error.flaky() ล้มเหลวสองครั้งแล้วจึงสำเร็จ เขียน retry(fn, times) ที่ await fn และลองใหม่เมื่อเกิด error

5. A tiny bank class5. คลาสธนาคารขนาดเล็ก

Write a Wallet class with a private #coins field, add(n), spend(n) (throw if there aren't enough), and a coins getter.เขียนคลาส Wallet ที่มี private field #coins และ add(n), spend(n) (throw ถ้าไม่พอ) และ getter coins

Lesson 13 · Debuggingบทที่ 13 · การดีบัก

Common mistakesข้อผิดพลาดที่พบบ่อย

Every one of these trips up beginners. The comments show what Node 22 really printed. มือใหม่ทุกคนเคยสะดุดเรื่องเหล่านี้ คอมเมนต์แสดงสิ่งที่ Node 22 พิมพ์ออกมาจริง

Adding to a stringบวกเลขกับ string

If either side of + is a string, JavaScript joins text instead of adding. Values from forms and URLs are always strings: convert them first.ถ้าฝั่งใดฝั่งหนึ่งของ + เป็น string JavaScript จะต่อข้อความแทนการบวก ค่าจากฟอร์มและ URL เป็น string เสมอ ต้องแปลงก่อน

✗ Wrong✗ ผิด
✓ Right✓ ถูก

Thinking const means "can't change"คิดว่า const แปลว่า "เปลี่ยนไม่ได้"

const stops you reassigning the variable. The object it points to can still change.const ห้ามแค่การกำหนดค่าใหม่ให้ตัวแปร ออบเจกต์ที่มันชี้อยู่ยังเปลี่ยนได้

✗ Wrong✗ ผิด
✓ Right✓ ถูก

Forgetting awaitลืม await

An async function always returns a Promise. Without await you get the promise, not the value inside it.ฟังก์ชัน async คืน Promise เสมอ ถ้าไม่ await จะได้ตัว promise ไม่ใช่ค่าข้างใน

✗ Wrong✗ ผิด
✓ Right✓ ถูก

Losing thisthis หายไป

A normal method gets this from how it's called. Pass it around on its own (as a callback, or stored in a variable) and this is undefined. An arrow function keeps the this of where it was written.method ปกติได้ this จากวิธีที่ถูกเรียก ถ้าส่งมันไปใช้แยกต่างหาก (เป็น callback หรือเก็บในตัวแปร) this จะเป็น undefined ส่วน arrow function ใช้ this ของตำแหน่งที่มันถูกเขียน

✗ Wrong✗ ผิด
✓ Right✓ ถูก

Spread only copies one levelspread คัดลอกแค่ชั้นเดียว

{ ...a } copies the top level. Nested arrays and objects are still shared. structuredClone makes a full, deep copy.{ ...a } คัดลอกแค่ชั้นบนสุด อาร์เรย์และออบเจกต์ที่ซ้อนอยู่ยังใช้ร่วมกัน structuredClone คัดลอกลึกทั้งหมด

✗ Wrong✗ ผิด
✓ Right✓ ถูก

Reading a property of nullอ่าน property ของ null

The most common error message in JavaScript. Use ?. when a value might be missing, and ?? for a fallback.ข้อความผิดพลาดที่พบบ่อยที่สุดใน JavaScript ใช้ ?. เมื่อค่าอาจไม่มีอยู่ และ ?? สำหรับค่าสำรอง

✗ Wrong✗ ผิด
✓ Right✓ ถูก

Lesson 14 · Referenceบทที่ 14 · อ้างอิง

Glossaryคำศัพท์

MDN, error messages and job posts all use the English terms, so it pays to know both. MDN ข้อความแจ้งข้อผิดพลาด และประกาศรับสมัครงาน ล้วนใช้คำภาษาอังกฤษ จึงควรรู้ทั้งสองภาษา

EnglishไทยMeaningความหมาย
truthy / falsyค่าที่นับเป็นจริง / เท็จHow a value behaves inside ifพฤติกรรมของค่าเมื่ออยู่ใน if
template literaltemplate literalA backtick string with ${…} placeholdersstring ในเครื่องหมาย backtick ที่มีช่อง ${…}
destructuringการแยกค่าออกPulling fields or items into variablesการดึงฟิลด์หรือสมาชิกออกมาเป็นตัวแปร
spreadการกระจาย (spread)...: copy or merge arrays and objects...: คัดลอกหรือรวมอาร์เรย์และออบเจกต์
arrow functionฟังก์ชันลูกศรThe short form (x) => x * 2รูปแบบสั้น (x) => x * 2
callbackฟังก์ชันเรียกกลับA function passed in, to be called laterฟังก์ชันที่ส่งเข้าไปเพื่อให้ถูกเรียกทีหลัง
closureโคลเชอร์A function that remembers variables from where it was madeฟังก์ชันที่จำตัวแปรจากที่ที่มันถูกสร้าง
class / instanceคลาส / อินสแตนซ์A template / one object made from it with newแม่แบบ / ออบเจกต์หนึ่งตัวที่สร้างด้วย new
private fieldฟิลด์ส่วนตัวA #name field only the class can useฟิลด์ #name ที่ใช้ได้เฉพาะในคลาส
PromiseพรอมิสA value that will arrive later, or failค่าที่จะมาถึงทีหลัง หรือล้มเหลว
async / awaitasync / awaitWrite promise-based code that reads top to bottomเขียนโค้ดที่ใช้ promise ให้อ่านจากบนลงล่าง
event loopอีเวนต์ลูปWhat runs queued callbacks once the current code finishesกลไกที่รัน callback ในคิวเมื่อโค้ดปัจจุบันเสร็จ
moduleโมดูลA file with its own scope that exports and importsไฟล์ที่มีขอบเขตของตัวเอง ใช้ export และ import
JSONJSONA text format for data, used by almost every APIรูปแบบข้อความสำหรับข้อมูล ที่ API เกือบทุกตัวใช้
DOMDOMThe page as a tree of elements JavaScript can changeหน้าเว็บในรูปต้นไม้ขององค์ประกอบที่ JavaScript เปลี่ยนแปลงได้
event listenerตัวดักฟังเหตุการณ์A function that runs when something happens, like a clickฟังก์ชันที่ทำงานเมื่อมีเหตุการณ์ เช่น การคลิก