Dark mode
JavaScript Fundamentals
How JavaScript Works
Step | แนวคิด | คำอธิบาย | จุดสำคัญ |
---|---|---|---|
1 | Single Threaded | JavaScript ทำงานบนเธรดเดียว | - ใช้ event loop สำหรับการทำงานแบบ asynchronous - การดำเนินการ I/O แบบไม่บล็อก |
2 | Execution Context | สภาพแวดล้อมที่โค้ดถูกประมวลผล | - สร้าง global execution context ก่อน - เพิ่ม function execution contexts เข้า call stack |
3 | Event Loop | จัดการการทำงานแบบ asynchronous | - ตรวจสอบ call stack และ callback queue - เรียกใช้ callback เมื่อ stack ว่าง |
4 | Hoisting | การย้ายประกาศตัวแปร/ฟังก์ชันไปด้านบน | - var ถูก hoisted- let /const ถูก hoisted แต่ไม่ถูกกำหนดค่า |
5 | Scope Chain | กำหนดการเข้าถึงตัวแปร | - Lexical scoping (ตามที่โค้ดเขียน) - ฟังก์ชันภายในเข้าถึงตัวแปรของฟังก์ชันภายนอก |
6 | Prototype Chain | กลไกการสืบทอด | - ออบเจ็กต์สืบทอดคุณสมบัติจาก prototypes - __proto__ ชี้ไปยัง prototype หลัก |
7 | Memory Management | การจัดการหน่วยความจำอัตโนมัติ | - นับการอ้างอิง - อัลกอริทึม mark-and-sweep |
Variables
Keyword | Scope | Reassignable | Hoisted | Best For |
---|---|---|---|---|
const | Block | No | No | Constants |
let | Block | Yes | No | Variables |
var | Function | Yes | Yes | Legacy code |
js
const PI = 3.14;
// PI = 3.1415; // Error!
// Object properties can change
const user = { name: 'John' };
user.name = 'Jane'; // Valid
js
let count = 0;
count = 1; // Valid
if (true) {
let local = 'only here';
}
// console.log(local); // Error!
js
function example() {
if (true) {
var x = 10; // Function-scoped
}
console.log(x); // 10 (not block-scoped)
}
Assignment
Data Types
Primitive Types
ประเภทข้อมูลพื้นฐานใน JavaScript ที่ไม่ใช่ object และไม่มี methods ของตัวเอง
Type | คำอธิบาย | ตัวอย่าง | typeof |
---|---|---|---|
String | ข้อความ | "Hello" | "string" |
Number | ตัวเลข | 42, 3.14 | "number" |
Boolean | ค่าทางตรรกะ (true/false) | true | "boolean" |
null | ค่าว่าง | null | "object" |
undefined | ยังไม่ได้กำหนดค่า | undefined | "undefined" |
Symbol | ค่า unique (ES6+) | Symbol('id') | "symbol" |
BigInt | ตัวเลขขนาดใหญ่ (ES2020+) | 123n | "bigint" |
js
const name = 'John';
const greeting = `Hello ${name}`; // Template literal
const multiLine = `Line 1
Line 2`;
js
const integer = 42;
const float = 3.14;
const scientific = 1e6; // 1,000,000
const binary = 0b1010; // 10
js
const isActive = true;
const hasPermission = false;
const truthy = !!'text'; // true
const falsy = !!0; // false
js
let empty = null;
let notDefined;
const sym = Symbol('unique');
const bigNum = 9007199254740991n;
Object Types
ประเภทข้อมูลที่สามารถเก็บ properties และ methods ได้
Type | คำอธิบาย | ตัวอย่าง |
---|---|---|
Object | คู่ key-value | {name: "John"} |
Array | ลำดับของข้อมูล | [1, 2, 3] |
Date | ค่าวันที่และเวลา | new Date() |
Function | วัตถุที่เรียกใช้งานได้ | function() {} |
RegExp | Regular expressions | /pattern/ |
js
const person = {
name: 'John',
age: 30,
greet() {
return `Hello, I'm ${this.name}`;
}
};
js
const numbers = [1, 2, 3];
numbers.push(4);
const doubled = numbers.map(n => n * 2);
js
function sum(a, b) {
return a + b;
}
const multiply = (x, y) => x * y;
js
const now = new Date();
const regex = /\d+/g;
const map = new Map([['key', 'value']]);
Loops
ประเภทลูป | คำอธิบาย | ใช้เมื่อไร | ตัวอย่าง |
---|---|---|---|
for | ลูปแบบใช้ตัวนับ | เมื่อต้องการควบคุม index | for(let i=0; i<10; i++) |
for...of | วนลูปผ่าน iterable objects | ทางเลือกสมัยใหม่แทน for | for(const item of array) |
forEach | เมธอดของ array สำหรับ side effects | วนลูป array อย่างง่าย | array.forEach(item => {}) |
for...in | วนลูปผ่าน properties ของ object | ใช้กับ object เท่านั้น (ไม่ใช้กับ array) | for(const key in obj) |
while | ลูปตามเงื่อนไข | เมื่อไม่รู้จำนวนครั้งที่แน่นอน | while(condition) |
do...while | ทำงานอย่างน้อย 1 ครั้ง | เมื่อต้องการรันครั้งแรกเสมอ | do {...} while(cond) |
js
for (let i = 0; i < 5; i++) {
console.log('รอบที่', i);
}
js
const colors = ['แดง', 'เขียว', 'น้ำเงิน'];
for (const color of colors) {
console.log(color);
}
js
const numbers = [1, 2, 3];
numbers.forEach(num => {
console.log(num * 2);
});
js
let count = 0;
while (count < 3) {
console.log('นับ', count);
count++;
}
js
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
Data Structures
Structure | Description | Methods/Properties |
---|---|---|
Array | รายการข้อมูลแบบลำดับ | push(), pop(), map(), length |
Object | คู่ key-value | Object.keys(), Object.values() |
Set | ข้อมูลที่ไม่ซ้ำกัน | add(), delete(), has() |
Map | คู่ key-value ที่ key เป็นอะไรก็ได้ | set(), get(), has() |
WeakMap | Map ที่เก็บ object เป็น key | set(), get(), has() |
WeakSet | Set ที่เก็บ object เท่านั้น | add(), delete(), has() |
js
const fruits = ['apple', 'banana'];
fruits.push('orange'); // Add
const last = fruits.pop(); // Remove
const filtered = fruits.filter(f => f.includes('a'));
js
const unique = new Set([1, 2, 2, 3]); // {1, 2, 3}
unique.add(4).delete(1);
console.log(unique.has(2)); // true
js
const map = new Map([['name', 'John']]);
map.set('age', 30);
console.log(map.get('name')); // 'John'
js
// Object keys are always strings/Symbols
const obj = {1: 'one'};
console.log(obj['1']); // 'one'
// Map keys can be any type
const map = new Map([[1, 'one']]);
console.log(map.get(1)); // 'one'
js
// Array
const arr = [1, 2, 3];
arr.push(4); // เพิ่มข้อมูลท้าย array
arr.pop(); // ลบข้อมูลท้าย array
// Object
const obj = {name: 'John'};
Object.keys(obj); // ['name']
// Set
const set = new Set([1, 2]);
set.add(3); // เพิ่มข้อมูล
// Map
const map = new Map();
map.set('key', 'value'); // กำหนดค่า
Debugging
วิธีการ | คำอธิบาย | ไวยากรณ์ |
---|---|---|
console.log() | การแสดงผลพื้นฐาน | console.log(value) |
debugger | หยุดการทำงานชั่วคราว | debugger; |
console.table() | แสดงข้อมูลแบบตาราง | console.table(data) |
console.trace() | แสดง call stack | console.trace() |
console.time() | วัดประสิทธิภาพ | console.time('label') |
breakpoints | จุดหยุดใน DevTools | - |
js
// Basic logging
console.log('Current state:', state);
// Table view
console.table([{id: 1, name: 'John'}]);
// Timing
console.time('fetch');
await fetch(url);
console.timeEnd('fetch');
js
function calculateTotal(items) {
debugger; // Execution pauses here
return items.reduce((sum, item) => sum + item.price, 0);
}
js
function processData(data) {
if (!data) {
console.trace('Missing data');
throw new Error('Invalid input');
}
// ...
}
Error Handling
วิธีการ | คำอธิบาย | ไวยากรณ์ |
---|---|---|
try/catch | จับข้อผิดพลาดพื้นฐาน | try {...} catch(err) {...} |
Promises | จับข้อผิดพลาดแบบ async | .catch(err => {...}) |
throw | สร้างข้อผิดพลาดเอง | throw new Error('message') |
Error Types | ประเภทข้อผิดพลาดต่างๆ | new TypeError() |
finally | รันโค้ดเสมอ | finally {...} |
js
try {
JSON.parse(invalidJson);
} catch (err) {
console.error('Parsing error:', err.message);
}
js
async function fetchData() {
try {
const res = await fetch(url);
return await res.json();
} catch (err) {
console.error('Fetch failed:', err);
throw err; // Re-throw for caller
}
}
js
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = 'ValidationError';
}
}
Conditionals
ประเภทเงื่อนไข | คำอธิบาย | ไวยากรณ์ |
---|---|---|
if...else | เงื่อนไขพื้นฐานทั้งหมด | if(cond) {...} else if(cond) {...} else {...} |
switch | ตรวจสอบหลายค่า | switch(value) |
เงื่อนไขแบบสั้น | cond ? a : b | |
เงื่อนไขและ | && | |
ค่าเริ่มต้น | ?? |
js
const age = 15;
if (age >= 18) {
console.log('ผู้ใหญ่');
} else if (age > 13) {
console.log('วัยรุ่น');
} else {
console.log('เด็ก');
}
js
const day = 'Tuesday';
switch(day) {
case 'Monday': console.log('วันจันทร์'); break;
case 'Tuesday': console.log('วันอังคาร'); break;
default: console.log('วันอื่นๆ');
}
js
const status = age >= 18 ? 'ผู้ใหญ่' : 'เด็ก';
console.log(status);
js
const isLogged = true;
isLogged && console.log('แสดงแดชบอร์ด');
js
const username = null;
const displayName = username ?? 'ผู้ใช้ไม่ระบุชื่อ';
console.log(displayName);
Operators
ประเภท | Operator | คำอธิบาย | ตัวอย่าง |
---|---|---|---|
Arithmetic | + | บวก | 5 + 3 → 8 |
- | ลบ | 5 - 3 → 2 | |
* | คูณ | 5 * 3 → 15 | |
/ | หาร | 6 / 3 → 2 | |
% | เศษจากการหาร | 5 % 3 → 2 | |
** | ยกกำลัง | 2 ** 3 → 8 | |
++ | เพิ่มค่า 1 | x++ | |
-- | ลดค่า 1 | x-- | |
Assignment | = | กำหนดค่า | x = 5 |
+= | บวกและกำหนดค่า | x += 3 | |
-= | ลบและกำหนดค่า | x -= 3 | |
*= | คูณและกำหนดค่า | x *= 2 | |
/= | หารและกำหนดค่า | x /= 2 | |
%= | หารเอาเศษและกำหนดค่า | x %= 2 | |
Comparison | == | เท่ากัน (ไม่ตรวจสอบ type) | 5 == '5' → true |
=== | เท่ากัน (ตรวจสอบ type) | 5 === '5' → false | |
!= | ไม่เท่ากัน (ไม่ตรวจสอบ type) | 5 != '5' → false | |
!== | ไม่เท่ากัน (ตรวจสอบ type) | 5 !== '5' → true | |
> | มากกว่า | 5 > 3 → true | |
< | น้อยกว่า | 5 < 3 → false | |
>= | มากกว่าหรือเท่ากับ | 5 >= 5 → true | |
<= | น้อยกว่าหรือเท่ากับ | 5 <= 3 → false | |
Logical | && | AND | true && false → false |
` | ` | ||
! | NOT | !true → false | |
Special | ?: | เงื่อนไขสั้น | x > 5 ? 'มาก' : 'น้อย' |
?? | Nullish coalescing | x ?? 'default' | |
... | Spread | [...arr] | |
in | ตรวจสอบ property | 'name' in obj | |
instanceof | ตรวจสอบ type | arr instanceof Array | |
typeof | ตรวจสอบ type | typeof 5 → 'number' |
js
let x = 5;
console.log(x + 3); // 8
console.log(x - 2); // 3
console.log(x * 4); // 20
console.log(x / 2); // 2.5
console.log(x % 2); // 1
console.log(x ** 3); // 125
x++;
console.log(x); // 6
js
console.log(5 == '5'); // true
console.log(5 === '5'); // false
console.log(5 != '5'); // false
console.log(5 !== '5'); // true
console.log(5 > 3); // true
console.log(5 < 3); // false
js
console.log(true && false); // false
console.log(true || false); // true
console.log(!true); // false
const age = 20;
const status = age >= 18 ? 'ผู้ใหญ่' : 'เด็ก';
console.log(status); // 'ผู้ใหญ่'
js
const user = { name: 'John' };
console.log('name' in user); // true
const arr = [1, 2, 3];
console.log(arr instanceof Array); // true
console.log(typeof arr); // 'object'
const settings = null;
const theme = settings ?? 'light';
console.log(theme); // 'light'
Functions
ประเภทฟังก์ชัน | คำอธิบาย | ไวยากรณ์ |
---|---|---|
การประกาศฟังก์ชันพื้นฐาน | function name() {} | |
ฟังก์ชันในตัวแปร | const name = function() {} | |
ฟังก์ชันแบบลูกศร | () => {} | |
ฟังก์ชันที่เรียกใช้ทันที | (function() {})() | |
ฟังก์ชันที่คืนค่าหลายครั้ง | function* name() {} | |
ฟังก์ชันแบบ asynchronous | async function() {} |
js
// Regular function
function add(a, b) {
return a + b;
}
// Arrow function
const multiply = (x, y) => x * y;
// Async function
async function getUser() {
try {
const res = await fetch('/user');
return await res.json();
} catch (err) {
console.error('Failed:', err);
}
}
Web APIs
Media APIs
API | คำอธิบาย | ตัวอย่าง |
---|---|---|
วาดกราฟิก | canvas.getContext('2d') | |
กราฟิก 3D | gl.drawArrays() | |
จัดการสื่อ | new Audio() | |
Text-to-Speech | speechSynthesis.speak() | |
Speech-to-Text | new SpeechRecognition() | |
ควบคุม animation | element.animate() |
Device APIs
API | คำอธิบาย | ตัวอย่าง |
---|---|---|
ตำแหน่งทางภูมิศาสตร์ | navigator.geolocation | |
ตรวจสอบการหมุนอุปกรณ์ | window.addEventListener('deviceorientation') | |
ตรวจสอบแบตเตอรี่ | navigator.getBattery() | |
ควบคุมการสั่น | navigator.vibrate() | |
ควบคุมเกม | navigator.getGamepads() | |
ป้องกันหน้าจอดับ | navigator.wakeLock |
Storage APIs
API | คำอธิบาย | ตัวอย่าง |
---|---|---|
localStorage/sessionStorage | localStorage.setItem() | |
ฐานข้อมูลใน browser | indexedDB.open() | |
อ่านไฟล์ | fileReader.readAsText() | |
คัดลอก/วาง | navigator.clipboard |
UI & Interaction APIs
API | คำอธิบาย | ตัวอย่าง |
---|---|---|
เปิด fullscreen | element.requestFullscreen() | |
ล็อกเมาส์ | canvas.requestPointerLock() | |
Speech recognition/synthesis | webkitSpeechRecognition | |
Lock resources | navigator.locks | |
ชำระเงิน | new PaymentRequest() | |
แชร์เนื้อหา | navigator.share() |
Advanced Features
API | คำอธิบาย | ตัวอย่าง |
---|---|---|
ประมวลผลพื้นหลัง | new Worker() | |
PWA/Offline | navigator.serviceWorker | |
สร้าง component | customElements.define() | |
การเข้ารหัส | crypto.subtle | |
Push notifications | PushManager | |
แจ้งเตือน | new Notification() | |
Authentication | navigator.credentials |
Hardware APIs
API | คำอธิบาย | ตัวอย่าง |
---|---|---|
เชื่อมต่อ Bluetooth | navigator.bluetooth | |
เชื่อมต่อ USB | navigator.usb | |
เชื่อมต่อ serial port | navigator.serial | |
เชื่อมต่อ NFC | navigator.nfc | |
เชื่อมต่อ MIDI | navigator.requestMIDIAccess() | |
VR/AR | navigator.xr |
Performance & Observer APIs
API | คำอธิบาย | ตัวอย่าง |
---|---|---|
วัดประสิทธิภาพ | performance.now() | |
ตรวจสอบ element ใน viewport | new IntersectionObserver() | |
ตรวจสอบการเปลี่ยนขนาด | new ResizeObserver() | |
ตรวจสอบ DOM changes | new MutationObserver() | |
ตรวจสอบ visibility | document.hidden |
Asynchronous
วิธีการ | คำอธิบาย | ไวยากรณ์ |
---|---|---|
รูปแบบดั้งเดิม | func(arg, callback) | |
การจัดการ async แบบใหม่ | new Promise() | |
สังเกตการณ์สำหรับ promises | async function() { await } | |
หลาย promises พร้อมกัน | Promise.all([p1, p2]) | |
ใช้ promise ที่เสร็จก่อน | Promise.race([p1, p2]) | |
โมเดลการทำงานของ JavaScript | - |
js
fs.readFile('file.txt', (err, data) => {
if (err) throw err;
console.log(data);
});
js
fetch(url)
.then(response => response.json())
.catch(err => console.error(err));
js
async function getUser() {
try {
const res = await fetch('/user');
return await res.json();
} catch (err) {
console.error('Failed:', err);
}
}
Modules
ประเภท | ไวยากรณ์ | คำอธิบาย |
---|---|---|
import/export | ระบบโมดูลมาตรฐาน | |
import() | โหลดโมดูลแบบ asynchronous | |
export const name | ส่งออกหลายค่า | |
export default | ส่งออกค่าเดียว |
js
import { name } from 'module';
import defaultExport from 'module';
export const name = value;
export default value;
js
const module = await import('./module.js');
js
// module.js
export const name1 = value1;
export const name2 = value2;
// usage.js
import { name1, name2 } from 'module';
js
// module.js
export default function() {};
// usage.js
import defaultExport from 'module';