Skip to content

JavaScript Fundamentals

How JavaScript Works

Stepแนวคิดคำอธิบายจุดสำคัญ
1Single ThreadedJavaScript ทำงานบนเธรดเดียว- ใช้ event loop สำหรับการทำงานแบบ asynchronous
- การดำเนินการ I/O แบบไม่บล็อก
2Execution Contextสภาพแวดล้อมที่โค้ดถูกประมวลผล- สร้าง global execution context ก่อน
- เพิ่ม function execution contexts เข้า call stack
3Event Loopจัดการการทำงานแบบ asynchronous- ตรวจสอบ call stack และ callback queue
- เรียกใช้ callback เมื่อ stack ว่าง
4Hoistingการย้ายประกาศตัวแปร/ฟังก์ชันไปด้านบน- var ถูก hoisted
- let/const ถูก hoisted แต่ไม่ถูกกำหนดค่า
5Scope Chainกำหนดการเข้าถึงตัวแปร- Lexical scoping (ตามที่โค้ดเขียน)
- ฟังก์ชันภายในเข้าถึงตัวแปรของฟังก์ชันภายนอก
6Prototype Chainกลไกการสืบทอด- ออบเจ็กต์สืบทอดคุณสมบัติจาก prototypes
- __proto__ ชี้ไปยัง prototype หลัก
7Memory Managementการจัดการหน่วยความจำอัตโนมัติ- นับการอ้างอิง
- อัลกอริทึม mark-and-sweep

Variables

KeywordScopeReassignableHoistedBest For
developer.mozilla.org faviconconstBlockNoNoConstants
developer.mozilla.org faviconletBlockYesNoVariables
developer.mozilla.org faviconvarFunctionYesYesLegacy 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
developer.mozilla.org faviconStringข้อความ"Hello""string"
developer.mozilla.org faviconNumberตัวเลข42, 3.14"number"
developer.mozilla.org faviconBooleanค่าทางตรรกะ (true/false)true"boolean"
developer.mozilla.org faviconnullค่าว่างnull"object"
developer.mozilla.org faviconundefinedยังไม่ได้กำหนดค่าundefined"undefined"
developer.mozilla.org faviconSymbolค่า unique (ES6+)Symbol('id')"symbol"
developer.mozilla.org faviconBigIntตัวเลขขนาดใหญ่ (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คำอธิบายตัวอย่าง
developer.mozilla.org faviconObjectคู่ key-value{name: "John"}
developer.mozilla.org faviconArrayลำดับของข้อมูล[1, 2, 3]
developer.mozilla.org faviconDateค่าวันที่และเวลาnew Date()
developer.mozilla.org faviconFunctionวัตถุที่เรียกใช้งานได้function() {}
developer.mozilla.org faviconRegExpRegular 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

ประเภทลูปคำอธิบายใช้เมื่อไรตัวอย่าง
developer.mozilla.org faviconforลูปแบบใช้ตัวนับเมื่อต้องการควบคุม indexfor(let i=0; i<10; i++)
developer.mozilla.org faviconfor...ofวนลูปผ่าน iterable objectsทางเลือกสมัยใหม่แทน forfor(const item of array)
developer.mozilla.org faviconforEachเมธอดของ array สำหรับ side effectsวนลูป array อย่างง่ายarray.forEach(item => {})
developer.mozilla.org faviconfor...inวนลูปผ่าน properties ของ objectใช้กับ object เท่านั้น (ไม่ใช้กับ array)for(const key in obj)
developer.mozilla.org faviconwhileลูปตามเงื่อนไขเมื่อไม่รู้จำนวนครั้งที่แน่นอนwhile(condition)
developer.mozilla.org favicondo...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

StructureDescriptionMethods/Properties
developer.mozilla.org faviconArrayรายการข้อมูลแบบลำดับpush(), pop(), map(), length
developer.mozilla.org faviconObjectคู่ key-valueObject.keys(), Object.values()
developer.mozilla.org faviconSetข้อมูลที่ไม่ซ้ำกันadd(), delete(), has()
developer.mozilla.org faviconMapคู่ key-value ที่ key เป็นอะไรก็ได้set(), get(), has()
developer.mozilla.org faviconWeakMapMap ที่เก็บ object เป็น keyset(), get(), has()
developer.mozilla.org faviconWeakSetSet ที่เก็บ 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

วิธีการคำอธิบายไวยากรณ์
developer.mozilla.org faviconconsole.log()การแสดงผลพื้นฐานconsole.log(value)
developer.mozilla.org favicondebuggerหยุดการทำงานชั่วคราวdebugger;
developer.mozilla.org faviconconsole.table()แสดงข้อมูลแบบตารางconsole.table(data)
developer.mozilla.org faviconconsole.trace()แสดง call stackconsole.trace()
developer.mozilla.org faviconconsole.time()วัดประสิทธิภาพconsole.time('label')
developer.mozilla.org faviconbreakpointsจุดหยุดใน 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

วิธีการคำอธิบายไวยากรณ์
developer.mozilla.org favicontry/catchจับข้อผิดพลาดพื้นฐานtry {...} catch(err) {...}
developer.mozilla.org faviconPromisesจับข้อผิดพลาดแบบ async.catch(err => {...})
developer.mozilla.org faviconthrowสร้างข้อผิดพลาดเองthrow new Error('message')
developer.mozilla.org faviconError Typesประเภทข้อผิดพลาดต่างๆnew TypeError()
developer.mozilla.org faviconfinallyรันโค้ดเสมอ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

ประเภทเงื่อนไขคำอธิบายไวยากรณ์
developer.mozilla.org faviconif...elseเงื่อนไขพื้นฐานทั้งหมดif(cond) {...} else if(cond) {...} else {...}
developer.mozilla.org faviconswitchตรวจสอบหลายค่าswitch(value)
developer.mozilla.org faviconTernaryเงื่อนไขแบบสั้นcond ? a : b
developer.mozilla.org faviconLogical ANDเงื่อนไขและ&&
developer.mozilla.org faviconNullish Coalescingค่าเริ่มต้น??
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
++เพิ่มค่า 1x++
--ลดค่า 1x--
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&&ANDtrue && false → false
``
!NOT!true → false
Special?:เงื่อนไขสั้นx > 5 ? 'มาก' : 'น้อย'
??Nullish coalescingx ?? 'default'
...Spread[...arr]
inตรวจสอบ property'name' in obj
instanceofตรวจสอบ typearr instanceof Array
typeofตรวจสอบ typetypeof 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

ประเภทฟังก์ชันคำอธิบายไวยากรณ์
developer.mozilla.org faviconFunction Declarationการประกาศฟังก์ชันพื้นฐานfunction name() {}
developer.mozilla.org faviconFunction Expressionฟังก์ชันในตัวแปรconst name = function() {}
developer.mozilla.org faviconArrow Functionฟังก์ชันแบบลูกศร() => {}
developer.mozilla.org faviconIIFEฟังก์ชันที่เรียกใช้ทันที(function() {})()
developer.mozilla.org faviconGeneratorฟังก์ชันที่คืนค่าหลายครั้งfunction* name() {}
developer.mozilla.org faviconAsync Functionฟังก์ชันแบบ asynchronousasync 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คำอธิบายตัวอย่าง
developer.mozilla.org faviconCanvasวาดกราฟิกcanvas.getContext('2d')
developer.mozilla.org faviconWebGLกราฟิก 3Dgl.drawArrays()
developer.mozilla.org faviconAudio/Videoจัดการสื่อnew Audio()
developer.mozilla.org faviconSpeech SynthesisText-to-SpeechspeechSynthesis.speak()
developer.mozilla.org faviconSpeech RecognitionSpeech-to-Textnew SpeechRecognition()
developer.mozilla.org faviconWeb Animations APIควบคุม animationelement.animate()

Device APIs

APIคำอธิบายตัวอย่าง
developer.mozilla.org faviconGeolocationตำแหน่งทางภูมิศาสตร์navigator.geolocation
developer.mozilla.org faviconDevice Orientationตรวจสอบการหมุนอุปกรณ์window.addEventListener('deviceorientation')
developer.mozilla.org faviconBattery Statusตรวจสอบแบตเตอรี่navigator.getBattery()
developer.mozilla.org faviconVibration APIควบคุมการสั่นnavigator.vibrate()
developer.mozilla.org faviconGamepad APIควบคุมเกมnavigator.getGamepads()
developer.mozilla.org faviconScreen Wake Lockป้องกันหน้าจอดับnavigator.wakeLock

Storage APIs

APIคำอธิบายตัวอย่าง
developer.mozilla.org faviconWeb StoragelocalStorage/sessionStoragelocalStorage.setItem()
developer.mozilla.org faviconIndexedDBฐานข้อมูลใน browserindexedDB.open()
developer.mozilla.org faviconFile APIอ่านไฟล์fileReader.readAsText()
developer.mozilla.org faviconClipboard APIคัดลอก/วางnavigator.clipboard

UI & Interaction APIs

APIคำอธิบายตัวอย่าง
developer.mozilla.org faviconFullscreen APIเปิด fullscreenelement.requestFullscreen()
developer.mozilla.org faviconPointer Lock APIล็อกเมาส์canvas.requestPointerLock()
developer.mozilla.org faviconWeb Speech APISpeech recognition/synthesiswebkitSpeechRecognition
developer.mozilla.org faviconWeb Locks APILock resourcesnavigator.locks
developer.mozilla.org faviconPayment Request APIชำระเงินnew PaymentRequest()
developer.mozilla.org faviconWeb Share APIแชร์เนื้อหาnavigator.share()

Advanced Features

APIคำอธิบายตัวอย่าง
developer.mozilla.org faviconWeb Workersประมวลผลพื้นหลังnew Worker()
developer.mozilla.org faviconService WorkersPWA/Offlinenavigator.serviceWorker
developer.mozilla.org faviconWeb Componentsสร้าง componentcustomElements.define()
developer.mozilla.org faviconWeb Crypto APIการเข้ารหัสcrypto.subtle
developer.mozilla.org faviconPush APIPush notificationsPushManager
developer.mozilla.org faviconNotifications APIแจ้งเตือนnew Notification()
developer.mozilla.org faviconWeb Authentication APIAuthenticationnavigator.credentials

Hardware APIs

APIคำอธิบายตัวอย่าง
developer.mozilla.org faviconWeb Bluetoothเชื่อมต่อ Bluetoothnavigator.bluetooth
developer.mozilla.org faviconWebUSBเชื่อมต่อ USBnavigator.usb
developer.mozilla.org faviconWeb Serial APIเชื่อมต่อ serial portnavigator.serial
developer.mozilla.org faviconWeb NFC APIเชื่อมต่อ NFCnavigator.nfc
developer.mozilla.org faviconWeb MIDI APIเชื่อมต่อ MIDInavigator.requestMIDIAccess()
developer.mozilla.org faviconWebXRVR/ARnavigator.xr

Performance & Observer APIs

APIคำอธิบายตัวอย่าง
developer.mozilla.org faviconPerformance APIวัดประสิทธิภาพperformance.now()
developer.mozilla.org faviconIntersection Observerตรวจสอบ element ใน viewportnew IntersectionObserver()
developer.mozilla.org faviconResize Observerตรวจสอบการเปลี่ยนขนาดnew ResizeObserver()
developer.mozilla.org faviconMutation Observerตรวจสอบ DOM changesnew MutationObserver()
developer.mozilla.org faviconPage Visibility APIตรวจสอบ visibilitydocument.hidden

Asynchronous

วิธีการคำอธิบายไวยากรณ์
developer.mozilla.org faviconCallbacksรูปแบบดั้งเดิมfunc(arg, callback)
developer.mozilla.org faviconPromisesการจัดการ async แบบใหม่new Promise()
developer.mozilla.org faviconasync/awaitสังเกตการณ์สำหรับ promisesasync function() { await }
developer.mozilla.org faviconPromise.all()หลาย promises พร้อมกันPromise.all([p1, p2])
developer.mozilla.org faviconPromise.race()ใช้ promise ที่เสร็จก่อนPromise.race([p1, p2])
developer.mozilla.org faviconEvent Loopโมเดลการทำงานของ 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

ประเภทไวยากรณ์คำอธิบาย
developer.mozilla.org faviconES Moduleimport/exportระบบโมดูลมาตรฐาน
developer.mozilla.org faviconDynamic Importimport()โหลดโมดูลแบบ asynchronous
developer.mozilla.org faviconNamed Exportexport const nameส่งออกหลายค่า
developer.mozilla.org faviconDefault Exportexport 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';

Last updated: