Back

ปูพื้น JavaScript ด้วย Node.jsBlur image

บทความนี้จะพาคุณเรียนรู้พื้นฐาน 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)
จัดการ UIAPIs
ตรวจสอบฟอร์ม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.js
bash

1. 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);
javascript

1.2 รันโค้ด#

node 01_variables.js
bash

1.3 ผลลัพธ์ที่คาดหวัง#

Course: JavaScript + Node.js
Version: 1
Is fun? true
Next version: 2
Type of course: string
Type of version: number
Type of isFun: boolean
plaintext

1.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, isLoggedInUsername, user_name
descriptiveใช้ชื่อที่มีความหมายuserAge, totalPricex, data, temp
ขึ้นต้นด้วยตัวอักษรชื่อตัวแปรต้องขึ้นต้นด้วยตัวอักษร, $, หรือ _name, _private, $count1name, @var
ไม่มีช่องว่างใช้ camelCase แทนช่องว่างfirstName, lastNamefirst name
ตัวพิมพ์์เล็กใหญ่name กับ Name ต่างกันmyVar, myvarN/A
ไม่ใช้คำสงวนใช้ reserved words ไม่ได้userCount, classNamevar, function, return

Tip: เลือกชื่อที่บอก อะไร ของตัวแปร ไม่ใช่ ใช้อย่างไร เช่น ใช้ userName แทน data

1.7 แบบฝึกหัด#

  1. สร้าง 02_assignment.js
  2. เก็บ ชื่อ, อายุ, และ ภาษาโปรแกรมมิ่งที่ชอบ
  3. แสดงค่าทั้งหมด + แสดง 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;
javascript

2.2 รันโค้ด#

node 02_comments.js
bash

2.3 ผลลัพธ์ที่คาดหวัง#

Hello
Karn
25
plaintext

สังเกต: คอมเมนต์ไม่ถูกแสดง ในผลลัพธ์ 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 ไวยากรณ์คอมเมนต์#

SyntaxTypeใช้สำหรับ
// commentSingle-lineบันทึกสั้นๆ, คำอธิบายแบบ inline
/* comment */Multi-lineคำอธิบายยาวๆ, เอกสาร

2.6 แบบฝึกหัด + ใช้ Shortcut จาก IDE#

โจทย์: สร้าง 02_assignment.js และฝึกใช้ keyboard shortcuts สำหรับ comment

VS Code Shortcuts

ActionWindows/LinuxmacOS
Toggle Line CommentCtrl + /Cmd + /
Toggle Block CommentShift + Alt + AShift + Option + A
Copy Line UpShift + Alt + UpShift + Option + Up
Move Line Up/DownAlt + Up/DownOption + Up/Down

ขั้นตอนการฝึกหัด

  1. สร้างไฟล์ 02_assignment.js

  2. พิมพ์โค้ดต่อไปนี้ (ยังไม่ต้อง comment):

    const name = "YourName"
    const age = 25
    console.log(name)
    console.log(age)
    javascript
  3. ฝึกใช้ Shortcut:

    • ไปที่บรรทัด console.log(name) แล้วกด Ctrl + / (Windows) หรือ Cmd + / (Mac) → บรรทัดจะถูก comment
    • ไปที่บรรทัด const age = 25 แล้วกด Ctrl + / อีกครั้ง → บรรทัดถูก comment
    • กด Ctrl + / ซ้ำอีกครั้ง → เลิก comment
  4. ฝึก 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);
javascript

3.2 รันโค้ด#

node 03_operators.js
bash

3.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=30
plaintext

3.4 Operators อ้างอิง#

Operatorคำอธิบายตัวอย่าง
+บวก5 + 3 = 8
-ลบ5 - 3 = 2
*คูณ5 * 3 = 15
/หาร6 / 3 = 2
%หารเอาเศษ5 % 3 = 2
`Template literal`${var}`

3.5 แบบฝึกหัด#

  1. สร้าง 03_assignment.js
  2. กำหนด price=120 และ discount=15 (%), คำนวณราคาสุดท้าย
  3. แสดง 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");
}
javascript

4.2 รันโค้ด#

node 04_conditionals.js
bash

4.3 ผลลัพธ์ที่คาดหวัง#

Grade: B
plaintext

4.4 Comparison Operators#

Operatorคำอธิบายตัวอย่าง
===เท่ากันทั้งค่าและชนิด5 === "5"false
!==ไม่เท่ากันทั้งค่าและชนิด5 !== "5"true
>มากกว่า10 > 5true
<น้อยกว่า5 < 10true
>=มากกว่าหรือเท่ากับ5 >= 5true
<=น้อยกว่าหรือเท่ากับ5 <= 5true

4.5 Logical Operators#

Operatorคำอธิบายตัวอย่าง
&&และtrue && falsefalse
||หรือtrue || falsetrue
!ไม่!truefalse

4.6 แบบฝึกหัด#

  1. สร้าง 04_assignment.js
  2. ใช้ const hour = 14;
  3. ถ้า 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--;
}
javascript

5.2 รันโค้ด#

node 05_loops.js
bash

5.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 = 1
plaintext

5.4 ประเภทของ Loop#

Loopใช้เมื่อตัวอย่าง
forรู้จำนวนรอบที่จะวนซ้ำfor (let i = 0; i < 10; i++)
whileไม่รู้จำนวนรอบที่จะวนซ้ำwhile (condition)
for...ofวนซ้ำ arraysfor (item of array)
for...inวนซ้ำ objectsfor (key in object)

5.5 แบบฝึกหัด#

  1. สร้าง 05_assignment.js
  2. แสดงเลขคู่จาก 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));
javascript

6.2 รันโค้ด#

node 06_functions.js
bash

6.3 ผลลัพธ์ที่คาดหวัง#

add(2, 5) = 7
multiply(3, 4) = 12
plaintext

6.4 เปรียบเทียบ Function Syntax#

TypeSyntaxUse Case
Function Declarationfunction name() {}ใช้ทั่วไป
Function Expressionconst name = function() {}Callbacks
Arrow Functionconst name = () => {}สั้น, callbacks

6.5 การตั้งชื่อ Functions#

Conventionกฎตัวอย่างที่ถูกตัวอย่างที่ผิด
camelCaseคำแรกตัวพิมพ์์เล็ก คำต่อไปตัวใหญ่getUserData, calculateTotal, isValidGetUserData, get_user_data
Verb-firstเริ่มต้นด้วยคำกริยาfetchUser, saveData, deleteItemuser, data, item
Booleansใช้ is, has, can, should prefixisLoggedIn, hasPermission, canEditlogged, permission, editable
Handlersใช้ handle prefix สำหรับ event handlershandleSubmit, handleClicksubmit, onClick

ตัวอย่างดีและไม่ดี:

ไม่ดีดีเหตุผล
data()getUserData()อธิบายว่าข้อมูลอะไร
process()calculateTotal()อธิบายการคำนวณ
check()isValidEmail()อธิบายว่าตรวจสอบอะไร
bool()hasPermission()การตั้งชื่อ boolean
x()formatDate()ชื่อที่มีความหมาย

Tip: ชื่อ function ควรตอบคำถาม “ทำอะไร” — calculateTotal(price, tax) ชัดเจนกว่า calc(p, t)

6.6 แบบฝึกหัด#

  1. สร้าง 06_assignment.js
  2. เขียน isAdult(age) ที่คืนค่า true/false (adult >= 18)
  3. ทดสอบ 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(", "));
javascript

7.2 รันโค้ด#

node 07_arrays_objects.js
bash

7.3 ผลลัพธ์ที่คาดหวัง#

fruits: [ 'apple', 'banana', 'mango', 'orange' ]
first fruit: apple
count: 4
user name: Karn
user roles: admin, teacher
plaintext

7.4 Array Methods#

Methodคำอธิบายตัวอย่าง
push()เพิ่มท้ายarr.push(5)
pop()เอาออกจากท้ายarr.pop()
unshift()เพิ่มต้นarr.unshift(5)
shift()เอาออกจากต้นarr.shift()
map()แปลงค่าใน arrayarr.map(x => x*2)
filter()กรองค่าใน arrayarr.filter(x => x>5)

7.5 แบบฝึกหัด#

  1. สร้าง 07_assignment.js
  2. สร้าง array ของตัวเลข 5 ตัว
  3. คำนวณผลรวมโดยใช้ loop
  4. สร้าง 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);
javascript

8.2 รันโค้ด#

node 08_array_of_objects.js
bash

8.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' }
plaintext

8.4 Operations ที่ใช้บ่อย#

OperationMethodตัวอย่าง
เข้าถึง itemarr[index]users[0].name
หา itemarr.find()users.find(u => u.id === 1)
กรอง itemsarr.filter()users.filter(u => u.role === 'admin')
แปลง itemsarr.map()users.map(u => u.name)
เพิ่ม itemarr.push()users.push(newUser)

8.5 แบบฝึกหัด#

  1. สร้าง 08_assignment.js
  2. สร้าง array ของสินค้า 3 รายการ (แต่ละอันมี id, name, price)
  3. แสดงสินค้าทั้งหมด
  4. หาและแสดงสินค้าที่มี 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));
javascript

9.2 รันโค้ด#

node 09_modules.js
bash

9.3 ผลลัพธ์ที่คาดหวัง#

square(5) = 25
square(12) = 144
plaintext

9.4 Module Syntax#

SyntaxTypeตัวอย่าง
require()CommonJS (Node.js)const mod = require('./mod')
importES Modulesimport { mod } from './mod.js'
module.exportsCommonJS exportmodule.exports = { func }
exportES Module exportexport function func() {}

9.5 แบบฝึกหัด#

  1. เพิ่ม function cube(n) ใหม่ใน mathUtil.js
  2. ใช้ใน 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();
javascript

10.2 รันโค้ด#

node 10_async.js
bash

10.3 ผลลัพธ์ที่คาดหวัง#

Start
After 500ms
After 300ms
plaintext

10.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.js
bash

ผลลัพธ์ที่คาดหวัง

Fetching user...
Error caught: Invalid user ID
User: { id: 123, name: 'User 123' }
Program continues...
plaintext

Key Points:

  • try - โค้ดที่อาจเกิด error
  • catch - จัดการกับ 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
  • อย่าคอมเมนต์โค้ดที่เข้าใจง่าย
ปูพื้น JavaScript ด้วย Node.js
ผู้เขียน กานต์ ยงศิริวิทย์ / Karn Yongsiriwit
เผยแพร่เมื่อ January 17, 2026
ลิขสิทธิ์ CC BY-NC-SA 4.0

กำลังโหลดความคิดเห็น...

ความคิดเห็น 0