ปูพื้น JavaScript ด้วย Node.js
เรียนรู้พื้นฐาน JavaScript ด้วย Node.js
บทความนี้จะพาคุณเรียนรู้พื้นฐาน JavaScript ตั้งแต่แนวคิดพื้นฐานด้วย Node.js เหมาะสำหรับผู้เริ่มต้นที่ต้องการเรียน JavaScript เพื่อการพัฒนาทั้ง frontend และ backend
0. เริ่มต้น#
0.1 สิ่งที่คุณจะได้เรียนรู้#
- เข้าใจพื้นฐาน JavaScript: comments, variables, data types, และ operators
- เรียนรู้ control flow: conditionals และ loops
- ใช้งาน functions และ modules
- จัดการกโค้ด asynchronous ด้วย Promises และ async/await
0.2 JavaScript คืออะไร?#
JavaScript (JS) เป็นภาษาโปรแกรมมิ่งที่ออกแบบมาเพื่อใช้บน web browsers วันนี้สามารถรันบน servers ได้โดยใช้ Node.js
| Frontend (Browser) | Backend (Server) |
|---|---|
| จัดการ UI | APIs |
| ตรวจสอบฟอร์ม | Authentication |
| ดึงข้อมูล | Database access |
| React/Next.js apps | ประมวลผลไฟล์ |
0.3 ทำไมต้องใช้ JavaScript สำหรับ Full-Stack?#
- ภาษาเดียว ทั้ง stack
- Ecosystem ขนาดใหญ่ผ่าน npm (Node Package Manager)
- พัฒนาเร็วด้วย libraries มากมาย
- เหมาะสำหรับสร้าง APIs และ web applications
0.4 ติดตั้งโปรเจกต์#
ข้อกำหนด: ติดตั้ง Node.js (LTS) จาก nodejs.org ↗
# สร้างโฟลเดอร์โปรเจกต์
mkdir js-node-tutorial
cd js-node-tutorial
# รันไฟล์ JavaScript ใดๆ
node filename.jsbash1. Variables & Data Types#
1.1 ตัวอย่างโค้ด#
ไฟล์: 01_variables.js
// 01_variables.js
const course = "JavaScript + Node.js";
let version = 1;
let isFun = true;
console.log("Course:", course);
console.log("Version:", version);
console.log("Is fun?", isFun);
version = version + 1;
console.log("Next version:", version);
console.log("Type of course:", typeof course);
console.log("Type of version:", typeof version);
console.log("Type of isFun:", typeof isFun);javascript1.2 รันโค้ด#
node 01_variables.jsbash1.3 ผลลัพธ์ที่คาดหวัง#
Course: JavaScript + Node.js
Version: 1
Is fun? true
Next version: 2
Type of course: string
Type of version: number
Type of isFun: booleanplaintext1.4 อธิบายประเภทของตัวแปร#
| Keyword | คำอธิบาย | ตัวอย่าง |
|---|---|---|
const | กำหนดค่าได้ครั้งเดียว | const name = "John"; |
let | กำหนดค่าใหม่ได้ | let age = 25; |
var | แบบเก่า (ไม่ควรใช้) | var old = "legacy"; |
1.5 Data Types#
| Type | คำอธิบาย | ตัวอย่าง |
|---|---|---|
string | ข้อความ | "Hello" |
number | ตัวเลข | 42, 3.14 |
boolean | จริง/เท็จ | true, false |
object | คอลเลกชัน | {}, [] |
undefined | ยังไม่ได้กำหนดค่า | undefined |
1.6 การตั้งชื่อ (Naming Conventions)#
| Convention | กฎ | ตัวอย่างที่ถูก | ตัวอย่างที่ผิด |
|---|---|---|---|
| camelCase | คำแรกตัวพิมพ์์เล็ก คำต่อไปตัวใหญ่ | userName, totalPrice, isLoggedIn | Username, user_name |
| descriptive | ใช้ชื่อที่มีความหมาย | userAge, totalPrice | x, data, temp |
| ขึ้นต้นด้วยตัวอักษร | ชื่อตัวแปรต้องขึ้นต้นด้วยตัวอักษร, $, หรือ _ | name, _private, $count | 1name, @var |
| ไม่มีช่องว่าง | ใช้ camelCase แทนช่องว่าง | firstName, lastName | first name |
| ตัวพิมพ์์เล็กใหญ่ | name กับ Name ต่างกัน | myVar, myvar | N/A |
| ไม่ใช้คำสงวน | ใช้ reserved words ไม่ได้ | userCount, className | var, function, return |
Tip: เลือกชื่อที่บอก อะไร ของตัวแปร ไม่ใช่ ใช้อย่างไร เช่น ใช้
userNameแทนdata
1.7 แบบฝึกหัด#
- สร้าง
02_assignment.js - เก็บ ชื่อ, อายุ, และ ภาษาโปรแกรมมิ่งที่ชอบ
- แสดงค่าทั้งหมด + แสดง
typeofของแต่ละตัวแปร
2. Comments (คอมเมนต์)#
คอมเมนต์คือบันทึกย่อยในโค้ดที่ JavaScript จะเพิกเฉย ช่วยอธิบายว่าโค้ดของคุณทำอะไร
2.1 ประเภทของคอมเมนต์#
ไฟล์: 02_comments.js
// This is a single-line comment
// ใช้ // สำหรับบันทึกสั้นๆ บนบรรทัดเดียว
/*
This is a multi-line comment.
ใช้สำหรับคำอธิบายยาวๆ
ที่ครอบคลุมหลายบรรทัด
*/
// คอมเมนต์ก่อนบรรทัดโค้ด
const greeting = "Hello";
const name = "Karn"; // คอมเมนต์หลังโค้ด
/* คอมเมนต์หลายบรรทัด
สามารถใช้แบบ inline ได้ */
const age = 25;javascript2.2 รันโค้ด#
node 02_comments.jsbash2.3 ผลลัพธ์ที่คาดหวัง#
Hello
Karn
25plaintextสังเกต: คอมเมนต์ไม่ถูกแสดง ในผลลัพธ์ JavaScript เพิกเฉยคอมเมนต์ทั้งหมด
2.4 เมื่อไหร่ควรใช้คอมเมนต์#
| Use Case | ตัวอย่าง |
|---|---|
| อธิบาย ทำไม ไม่ใช่ ทำอะไร | // Check if user is admin before allowing access |
| อธิบาย logic ที่ซับซ้อน | // คำนวณดอกเบี้ยทบต้น: A = P(1 + r/n)^nt |
| แจ้งเตือน TODO | // TODO: เพิ่ม error handling สำหรับ edge cases |
| ปิดการใช้งานโค้ดชั่วคราว | // console.log(debugValue); |
Tip: อย่าคอมเมนต์โค้ดที่เข้าใจง่าย
let x = 5; // กำหนด x เป็น 5ไม่มีประโยชน์
2.5 ไวยากรณ์คอมเมนต์#
| Syntax | Type | ใช้สำหรับ |
|---|---|---|
// comment | Single-line | บันทึกสั้นๆ, คำอธิบายแบบ inline |
/* comment */ | Multi-line | คำอธิบายยาวๆ, เอกสาร |
2.6 แบบฝึกหัด + ใช้ Shortcut จาก IDE#
โจทย์: สร้าง 02_assignment.js และฝึกใช้ keyboard shortcuts สำหรับ comment
VS Code Shortcuts
| Action | Windows/Linux | macOS |
|---|---|---|
| Toggle Line Comment | Ctrl + / | Cmd + / |
| Toggle Block Comment | Shift + Alt + A | Shift + Option + A |
| Copy Line Up | Shift + Alt + Up | Shift + Option + Up |
| Move Line Up/Down | Alt + Up/Down | Option + Up/Down |
ขั้นตอนการฝึกหัด
-
สร้างไฟล์
02_assignment.js -
พิมพ์โค้ดต่อไปนี้ (ยังไม่ต้อง comment):
javascriptconst name = "YourName" const age = 25 console.log(name) console.log(age) -
ฝึกใช้ Shortcut:
- ไปที่บรรทัด
console.log(name)แล้วกดCtrl + /(Windows) หรือCmd + /(Mac) → บรรทัดจะถูก comment - ไปที่บรรทัด
const age = 25แล้วกดCtrl + /อีกครั้ง → บรรทัดถูก comment - กด
Ctrl + /ซ้ำอีกครั้ง → เลิก comment
- ไปที่บรรทัด
-
ฝึก Block Comment:
- เลือกหลายบรรทัด (เช่น
console.log(name)ถึงconsole.log(age)) - กด
Shift + Alt + A(Windows) หรือShift + Option + A(Mac) - โค้ดที่เลือกจะถูก comment ด้วย
/* ... */
- เลือกหลายบรรทัด (เช่น
Tip: การใช้ shortcuts เป็นนิสัยจะช่วยให้เขียนโค้ดได้เร็วขึ้นมาก ลองกด
Ctrl + Shift + Pแล้วค้นหา “Keyboard Shortcuts” เพื่อดู shortcuts ทั้งหมด
3. Operators & String Templates#
3.1 ตัวอย่างโค้ด#
ไฟล์: 03_operators.js
// 03_operators.js
const a = 10;
const b = 3;
console.log("a + b =", a + b);
console.log("a - b =", a - b);
console.log("a * b =", a * b);
console.log("a / b =", a / b);
console.log("a % b =", a % b);
const name = "Karn";
const msg = `Hello ${name}, a=${a}, b=${b}, a*b=${a * b}`;
console.log(msg);javascript3.2 รันโค้ด#
node 03_operators.jsbash3.3 ผลลัพธ์ที่คาดหวัง#
a + b = 13
a - b = 7
a * b = 30
a / b = 3.3333333333333335
a % b = 1
Hello Karn, a=10, b=3, a*b=30plaintext3.4 Operators อ้างอิง#
| Operator | คำอธิบาย | ตัวอย่าง |
|---|---|---|
+ | บวก | 5 + 3 = 8 |
- | ลบ | 5 - 3 = 2 |
* | คูณ | 5 * 3 = 15 |
/ | หาร | 6 / 3 = 2 |
% | หารเอาเศษ | 5 % 3 = 2 |
` | Template literal | `${var}` |
3.5 แบบฝึกหัด#
- สร้าง
03_assignment.js - กำหนด
price=120และdiscount=15(%), คำนวณราคาสุดท้าย - แสดง template string:
ราคาสุดท้ายคือ ...
4. Conditionals (if / else)#
4.1 ตัวอย่างโค้ด#
ไฟล์: 04_conditionals.js
// 04_conditionals.js
const score = 72;
if (score >= 80) {
console.log("Grade: A");
} else if (score >= 70) {
console.log("Grade: B");
} else if (score >= 60) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}javascript4.2 รันโค้ด#
node 04_conditionals.jsbash4.3 ผลลัพธ์ที่คาดหวัง#
Grade: Bplaintext4.4 Comparison Operators#
| Operator | คำอธิบาย | ตัวอย่าง |
|---|---|---|
=== | เท่ากันทั้งค่าและชนิด | 5 === "5" → false |
!== | ไม่เท่ากันทั้งค่าและชนิด | 5 !== "5" → true |
> | มากกว่า | 10 > 5 → true |
< | น้อยกว่า | 5 < 10 → true |
>= | มากกว่าหรือเท่ากับ | 5 >= 5 → true |
<= | น้อยกว่าหรือเท่ากับ | 5 <= 5 → true |
4.5 Logical Operators#
| Operator | คำอธิบาย | ตัวอย่าง |
|---|---|---|
&& | และ | true && false → false |
|| | หรือ | true || false → true |
! | ไม่ | !true → false |
4.6 แบบฝึกหัด#
- สร้าง
04_assignment.js - ใช้
const hour = 14; - ถ้า
hour < 12แสดง"Good morning", ถ้าไม่เป็น"Good afternoon"
5. Loops (for / while)#
5.1 ตัวอย่างโค้ด#
ไฟล์: 05_loops.js
// 05_loops.js
for (let i = 1; i <= 5; i++) {
console.log("for loop i =", i);
}
let n = 3;
while (n > 0) {
console.log("while loop n =", n);
n--;
}javascript5.2 รันโค้ด#
node 05_loops.jsbash5.3 ผลลัพธ์ที่คาดหวัง#
for loop i = 1
for loop i = 2
for loop i = 3
for loop i = 4
for loop i = 5
while loop n = 3
while loop n = 2
while loop n = 1plaintext5.4 ประเภทของ Loop#
| Loop | ใช้เมื่อ | ตัวอย่าง |
|---|---|---|
for | รู้จำนวนรอบที่จะวนซ้ำ | for (let i = 0; i < 10; i++) |
while | ไม่รู้จำนวนรอบที่จะวนซ้ำ | while (condition) |
for...of | วนซ้ำ arrays | for (item of array) |
for...in | วนซ้ำ objects | for (key in object) |
5.5 แบบฝึกหัด#
- สร้าง
05_assignment.js - แสดงเลขคู่จาก 2 ถึง 20 (2, 4, 6, …, 20)
6. Functions#
6.1 ตัวอย่างโค้ด#
ไฟล์: 06_functions.js
// 06_functions.js
function add(x, y) {
return x + y;
}
const multiply = (x, y) => x * y;
console.log("add(2, 5) =", add(2, 5));
console.log("multiply(3, 4) =", multiply(3, 4));javascript6.2 รันโค้ด#
node 06_functions.jsbash6.3 ผลลัพธ์ที่คาดหวัง#
add(2, 5) = 7
multiply(3, 4) = 12plaintext6.4 เปรียบเทียบ Function Syntax#
| Type | Syntax | Use Case |
|---|---|---|
| Function Declaration | function name() {} | ใช้ทั่วไป |
| Function Expression | const name = function() {} | Callbacks |
| Arrow Function | const name = () => {} | สั้น, callbacks |
6.5 การตั้งชื่อ Functions#
| Convention | กฎ | ตัวอย่างที่ถูก | ตัวอย่างที่ผิด |
|---|---|---|---|
| camelCase | คำแรกตัวพิมพ์์เล็ก คำต่อไปตัวใหญ่ | getUserData, calculateTotal, isValid | GetUserData, get_user_data |
| Verb-first | เริ่มต้นด้วยคำกริยา | fetchUser, saveData, deleteItem | user, data, item |
| Booleans | ใช้ is, has, can, should prefix | isLoggedIn, hasPermission, canEdit | logged, permission, editable |
| Handlers | ใช้ handle prefix สำหรับ event handlers | handleSubmit, handleClick | submit, onClick |
ตัวอย่างดีและไม่ดี:
| ไม่ดี | ดี | เหตุผล |
|---|---|---|
data() | getUserData() | อธิบายว่าข้อมูลอะไร |
process() | calculateTotal() | อธิบายการคำนวณ |
check() | isValidEmail() | อธิบายว่าตรวจสอบอะไร |
bool() | hasPermission() | การตั้งชื่อ boolean |
x() | formatDate() | ชื่อที่มีความหมาย |
Tip: ชื่อ function ควรตอบคำถาม “ทำอะไร” —
calculateTotal(price, tax)ชัดเจนกว่าcalc(p, t)
6.6 แบบฝึกหัด#
- สร้าง
06_assignment.js - เขียน
isAdult(age)ที่คืนค่าtrue/false(adult >= 18) - ทดสอบ 2 อายุ
7. Arrays & Objects#
7.1 ตัวอย่างโค้ด#
ไฟล์: 07_arrays_objects.js
// 07_arrays_objects.js
const fruits = ["apple", "banana", "mango"];
fruits.push("orange");
console.log("fruits:", fruits);
console.log("first fruit:", fruits[0]);
console.log("count:", fruits.length);
const user = {
id: 1,
name: "Karn",
roles: ["admin", "teacher"],
};
console.log("user name:", user.name);
console.log("user roles:", user.roles.join(", "));javascript7.2 รันโค้ด#
node 07_arrays_objects.jsbash7.3 ผลลัพธ์ที่คาดหวัง#
fruits: [ 'apple', 'banana', 'mango', 'orange' ]
first fruit: apple
count: 4
user name: Karn
user roles: admin, teacherplaintext7.4 Array Methods#
| Method | คำอธิบาย | ตัวอย่าง |
|---|---|---|
push() | เพิ่มท้าย | arr.push(5) |
pop() | เอาออกจากท้าย | arr.pop() |
unshift() | เพิ่มต้น | arr.unshift(5) |
shift() | เอาออกจากต้น | arr.shift() |
map() | แปลงค่าใน array | arr.map(x => x*2) |
filter() | กรองค่าใน array | arr.filter(x => x>5) |
7.5 แบบฝึกหัด#
- สร้าง
07_assignment.js - สร้าง array ของตัวเลข 5 ตัว
- คำนวณผลรวมโดยใช้ loop
- สร้าง object
{ title, year }และแสดงค่า
8. Array of Objects#
8.1 ตัวอย่างโค้ด#
ไฟล์: 08_array_of_objects.js
// 08_array_of_objects.js
const users = [
{ id: 1, name: "Karn", role: "admin" },
{ id: 2, name: "John", role: "user" },
{ id: 3, name: "Jane", role: "user" }
];
console.log("All users:", users);
console.log("First user:", users[0]);
console.log("User name:", users[0].name);
// Loop through array of objects
console.log("\n--- User List ---");
for (let i = 0; i < users.length; i++) {
console.log(`${users[i].id}: ${users[i].name} (${users[i].role})`);
}
// Find user by id
const userId = 2;
const foundUser = users.find(u => u.id === userId);
console.log("\nFound user:", foundUser);javascript8.2 รันโค้ด#
node 08_array_of_objects.jsbash8.3 ผลลัพธ์ที่คาดหวัง#
All users: [
{ id: 1, name: 'Karn', role: 'admin' },
{ id: 2, name: 'John', role: 'user' },
{ id: 3, name: 'Jane', role: 'user' }
]
First user: { id: 1, name: 'Karn', role: 'admin' }
User name: Karn
--- User List ---
1: Karn (admin)
2: John (user)
3: Jane (user)
Found user: { id: 2, name: 'John', role: 'user' }plaintext8.4 Operations ที่ใช้บ่อย#
| Operation | Method | ตัวอย่าง |
|---|---|---|
| เข้าถึง item | arr[index] | users[0].name |
| หา item | arr.find() | users.find(u => u.id === 1) |
| กรอง items | arr.filter() | users.filter(u => u.role === 'admin') |
| แปลง items | arr.map() | users.map(u => u.name) |
| เพิ่ม item | arr.push() | users.push(newUser) |
8.5 แบบฝึกหัด#
- สร้าง
08_assignment.js - สร้าง array ของสินค้า 3 รายการ (แต่ละอันมี
id,name,price) - แสดงสินค้าทั้งหมด
- หาและแสดงสินค้าที่มี
id = 2
9. Modules (import/export)#
9.1 ตัวอย่างโค้ด#
คุณจะสร้าง สองไฟล์ สำหรับหัวข้อนี้
ไฟล์: mathUtil.js
// mathUtil.js
function square(n) {
return n * n;
}
module.exports = { square };javascriptไฟล์: 09_modules.js
// 09_modules.js
const { square } = require("./mathUtil");
console.log("square(5) =", square(5));
console.log("square(12) =", square(12));javascript9.2 รันโค้ด#
node 09_modules.jsbash9.3 ผลลัพธ์ที่คาดหวัง#
square(5) = 25
square(12) = 144plaintext9.4 Module Syntax#
| Syntax | Type | ตัวอย่าง |
|---|---|---|
require() | CommonJS (Node.js) | const mod = require('./mod') |
import | ES Modules | import { mod } from './mod.js' |
module.exports | CommonJS export | module.exports = { func } |
export | ES Module export | export function func() {} |
9.5 แบบฝึกหัด#
- เพิ่ม function
cube(n)ใหม่ในmathUtil.js - ใช้ใน
09_assignment.jsและแสดงผลลัพธ์
10. Async JavaScript (Promises / async-await)#
10.1 ตัวอย่างโค้ด#
ไฟล์: 10_async.js
// 10_async.js
const { setTimeout } = require("node:timers/promises");
async function main() {
console.log("Start");
await setTimeout(500);
console.log("After 500ms");
await setTimeout(300);
console.log("After 300ms");
}
main();javascript10.2 รันโค้ด#
node 10_async.jsbash10.3 ผลลัพธ์ที่คาดหวัง#
Start
After 500ms
After 300msplaintext10.4 Async Concepts#
| Concept | คำอธิบาย |
|---|---|
Promise | แทนผลลัพธ์ที่จะเกิดขึ้นในอนาคต |
async | ประกาศฟังก์ชันแบบ async |
await | รอจนกว่า Promise สำเร็จ |
setTimeout() | คำสั่งหน่วงเวลาแบบ Promise ในตัว Node.js (Node 16+) |
Note:
setTimeoutจากnode:timers/promisesใช้ได้ใน Node.js 16+ สำหรับ browser code ต้องห่อsetTimeoutใน Promise เอง
10.5 Error Handling (try/catch)#
ไฟล์: 11_errors.js
// 11_errors.js
async function fetchUserData(userId) {
// Simulate API call that might fail
if (userId <= 0) {
throw new Error("Invalid user ID");
}
return { id: userId, name: `User ${userId}` };
}
async function main() {
try {
console.log("Fetching user...");
const user = await fetchUserData(-1); // This will throw an error
console.log("User:", user);
} catch (error) {
console.log("Error caught:", error.message);
}
// This will run successfully
try {
const user = await fetchUserData(123);
console.log("User:", user);
} catch (error) {
console.log("Error:", error.message);
}
console.log("Program continues...");
}
main();javascriptรันโค้ด
node 11_errors.jsbashผลลัพธ์ที่คาดหวัง
Fetching user...
Error caught: Invalid user ID
User: { id: 123, name: 'User 123' }
Program continues...plaintextKey Points:
try- โค้ดที่อาจเกิด errorcatch- จัดการกับ error ที่เกิดขึ้นthrow- สร้าง error ขึ้นมาเอง
10.6 แบบฝึกหัด#
สร้างไฟล์ชื่อ 12_assignment.js และเขียนฟังก์ชัน countdown ที่:
- รับตัวเลข
nเป็น input - แสดงตัวเลขจาก
nลงมาจนถึง 1 โดยห่างละ 300ms - หยุดอัตโนมัติเมื่อถึง 1
Hint: ใช้
setInterval()เพื่อรันโค้ดซ้ำและclearInterval()เพื่อหยุด
11. Best Practices#
11.1 สิ่งที่ควรทำ#
- ใช้
constเป็นค่าเริ่มต้น,letเมื่อต้องเปลี่ยนค่า - ใช้ arrow functions สำหรับ callbacks
- ใช้ template literals สำหรับ strings
- จัดการ errors ด้วย try/catch
- ใช้ชื่อตัวแปรที่มีความหมาย
- เพิ่มคอมเมนต์อธิบาย logic ที่ซับซ้อน
11.2 สิ่งที่ควรหลีกเลี่ยง#
- อย่าใช้
var(แบบเก่า) - อย่าข้ามการจัดการ errors
- อย่าสร้างตัวแปร global
- อย่าใช้ blocking operations ใน async code
- อย่าลืม return values
- อย่าคอมเมนต์โค้ดที่เข้าใจง่าย