ស្វែងយល់
JavaScript ពីដំបូង
មេរៀននេះ គ្របដណ្ដប់ JavaScript ចាប់ពីការប្រកាស Variable រហូតដល់ Async/Await, OOP, Functional Programming, Design Patterns និង Performance Optimization។
- Variable, Data Types
- Operators, Expressions
- if/else, for, while loop
- Functions, Arrow Function
- Array & Object
- DOM Manipulation
- Events & Listeners
- OOP, Classes, Inheritance
- Async, Promise, Fetch API
- Closure, Scope, Hoisting
- ES6+ Features
- Functional Programming
- Error Handling, Modules
- Performance & Patterns
- Browser ទំនើប (Chrome, Firefox)
- VS Code ឬ Text Editor
- ចំណេះដឹង HTML/CSS មូលដ្ឋាន
- ចិត្តចង់រៀន 😄
Variable & Data Types
ការប្រកាស Variable ដោយប្រើ var, let, const និង Data Types ទូទៅក្នុង JavaScript។
| Keyword | Scope | Reassign? | Hoisted? |
|---|---|---|---|
var | Function | ✅ បាន | ✅ (undefined) |
let | Block | ✅ បាន | ⛔ TDZ |
const | Block | ⛔ មិនបាន | ⛔ TDZ |
// ✅ ប្រើ const ជាលំនាំ const name = 'ដារា'; const age = 22; // ✅ ប្រើ let ពេល value ត្រូវផ្លាស់ប្ដូរ let score = 0; score = 95; // ⚠️ var (ចៀសវាង — scope problem) var old = 'legacy';
// Primitive Types const str = 'Hello World'; // String const num = 42; // Number const big = 9007199254740993n;// BigInt const bool = true; // Boolean const n = null; // Null const u = undefined; // Undefined const sym = Symbol('id'); // Symbol // Reference Type const obj = { x: 1, y: 2 }; // Object const arr = [1, 2, 3]; // Array // typeof console.log(typeof str); // "string" console.log(typeof null); // "object" ← bug ចាស់
// Template Literal (backtick) const greet = `សួស្ដី ${name}! អាយុ ${age} ឆ្នាំ`; // Type Conversion Number('42') // → 42 String(100) // → "100" Boolean(0) // → false Boolean('') // → false Boolean('hi') // → true parseInt('3.7px') // → 3 parseFloat('3.7px')// → 3.7
Operators & Expressions
Arithmetic, Comparison, Logical, Ternary, Nullish Coalescing, Optional Chaining។
// Arithmetic 10 + 3 // 13 10 - 3 // 7 10 * 3 // 30 10 / 3 // 3.333... 10 % 3 // 1 (modulo) 2 ** 8 // 256 (exponent) // Assignment shorthand let x = 10; x += 5; // x = 15 x -= 3; // x = 12 x++; // x = 13 (post-increment) ++x; // x = 14 (pre-increment)
// == vs === (ប្រើ === ជានិច្ច) 5 == '5' // true (coerce) 5 === '5' // false (strict) // Logical true && false // false (AND) true || false // true (OR) !true // false (NOT) // Ternary const result = age >= 18 ? 'មនុស្សពេញវ័យ' : 'ក្មេង'; // Nullish Coalescing (??) — ES2020 const user = null; const display = user ?? 'Guest'; // 'Guest' // Optional Chaining (?.) — ES2020 const city = user?.address?.city ?? 'មិនស្គាល់';
Control Flow — if / loop
if/else, switch, for, while, do-while, for...of, for...in, break, continue។
const score = 85; if (score >= 90) { console.log('A'); } else if (score >= 80) { console.log('B'); // ← នឹងចេញ } else { console.log('C'); } // switch switch (new Date().getDay()) { case 1: console.log('ចន្ទ'); break; case 2: console.log('អង្គារ'); break; default: console.log('ថ្ងៃផ្សេង'); }
// for loop ធម្មតា for (let i = 0; i < 5; i++) { console.log(i); // 0 1 2 3 4 } // while let n = 0; while (n < 3) { console.log(n++); } // for...of (Array, String, Map, Set) const fruits = ['ស្វាយ', 'ល្ហុង', 'មៀន']; for (const f of fruits) { console.log(f); } // for...in (Object keys) const person = { name: 'ដារា', age: 22 }; for (const key in person) { console.log(`${key}: ${person[key]}`); } // break & continue for (let i = 0; i < 10; i++) { if (i === 3) continue; // លោតរំលង if (i === 6) break; // ចេញពី loop console.log(i); }
Functions
Function Declaration, Expression, Arrow Function, Default Params, Rest, Spread, Callback។
// 1. Declaration (hoisted) function greet(name) { return `សួស្ដី ${name}!`; } // 2. Expression const add = function(a, b) { return a + b; }; // 3. Arrow Function ← ប្រើញឹកបំផុត const multiply = (a, b) => a * b; // 4. Default Parameters const power = (base, exp = 2) => base ** exp; power(3); // 9 power(2, 10);// 1024 // 5. Rest Parameters const sum = (...nums) => nums.reduce((acc, n) => acc + n, 0); sum(1, 2, 3, 4); // 10 // 6. Callback const nums = [1, 2, 3]; nums.forEach(n => console.log(n * 2));
Array & Object
Array Methods, Destructuring, Spread, Object Methods, Optional Chaining។
const nums = [1, 2, 3, 4, 5]; // map — បម្លែង element ទាំងអស់ nums.map(n => n * 2); // [2,4,6,8,10] // filter — ច្រោះ element nums.filter(n => n % 2 === 0); // [2,4] // reduce — បូកសរុប nums.reduce((acc, n) => acc + n, 0); // 15 // find / findIndex nums.find(n => n > 3); // 4 nums.findIndex(n => n > 3); // 3 // some / every nums.some(n => n > 4); // true nums.every(n => n > 0); // true // flat / flatMap [1, [2, [3]]].flat(Infinity); // [1,2,3] // Spread const more = [...nums, 6, 7]; // [1..7] // Destructuring const [first, second, ...rest] = nums; // first=1, second=2, rest=[3,4,5]
const person = { name: 'ដារា', age: 22, city: 'ភ្នំពេញ' }; Object.keys(person); // ['name','age','city'] Object.values(person); // ['ដារា', 22, 'ភ្នំពេញ'] Object.entries(person); // [['name','ដារា'],...] // Spread Object const updated = { ...person, age: 23 }; // Destructuring const { name, age: myAge = 0 } = person; // Shorthand property const x = 10, y = 20; const point = { x, y }; // { x: 10, y: 20 } // Computed keys const key = 'score'; const obj = { [key]: 95 }; // { score: 95 }
DOM Manipulation
ការគ្រប់គ្រង HTML Elements ពីក្នុង JavaScript — Select, Create, Modify, Remove។
// ជ្រើសរើស Element document.getElementById('myId'); document.querySelector('.myClass'); // ដំបូង document.querySelectorAll('p'); // ទាំងអស់ document.getElementsByClassName('btn'); // HTMLCollection // Modify content const el = document.querySelector('#title'); el.textContent = 'ចំណងជើងថ្មី'; el.innerHTML = '<b>Bold Text</b>'; // Modify styles el.style.color = 'red'; el.style.fontSize = '24px'; el.classList.add('active'); el.classList.remove('hidden'); el.classList.toggle('show'); // Attributes el.setAttribute('href', '#'); el.getAttribute('class'); el.removeAttribute('disabled');
// Create const li = document.createElement('li'); li.textContent = 'Item ថ្មី'; li.classList.add('item'); document.querySelector('ul').appendChild(li); // insertAdjacentHTML — លឿនជាង document.querySelector('#list') .insertAdjacentHTML('beforeend', `<li class="item">Item ថ្មី</li>`); // Remove li.remove(); // Clone const copy = li.cloneNode(true);
Events & Listeners
addEventListener, Event Object, Delegation, Custom Events, Keyboard & Mouse Events។
const btn = document.querySelector('#myBtn'); // Basic btn.addEventListener('click', () => { console.log('ចុចហើយ!'); }); // Event Object btn.addEventListener('click', (e) => { console.log(e.target); // element ដែលចុច console.log(e.type); // "click" e.preventDefault(); // បញ្ឈប់ default action e.stopPropagation(); // បញ្ឈប់ bubble }); // Event Delegation — performance ល្អ document.querySelector('#list') .addEventListener('click', (e) => { if (e.target.tagName === 'LI') { e.target.classList.toggle('done'); } }); // { once: true } — run ម្ដងតែ btn.addEventListener('click', handler, { once: true }); // Custom Event const myEvent = new CustomEvent('done', { detail: { msg: 'Task completed!' } }); btn.dispatchEvent(myEvent);
OOP & Classes
Class, Constructor, Methods, Inheritance (extends), static, getter/setter, Private Fields។
class Animal { // Private field (ES2022) #sound; constructor(name, sound) { this.name = name; this.#sound = sound; } // Getter get info() { return `${this.name} — ${this.#sound}`; } speak() { return `${this.name}: ${this.#sound}!`; } // Static method static compare(a, b) { return a.name.localeCompare(b.name); } } // Inheritance class Dog extends Animal { constructor(name) { super(name, 'ហ្វូ'); this.tricks = []; } learn(trick) { this.tricks.push(trick); return this; // Method chaining } speak() { return super.speak() + ' 🐕'; } } const rex = new Dog('Rex'); rex.learn('sit').learn('stay'); console.log(rex.speak()); // Rex: ហ្វូ! 🐕
Async / Promise / Fetch
Callback Hell, Promise, .then/.catch, async/await, Fetch API, Error Handling។
// Promise const fetchUser = (id) => new Promise((resolve, reject) => { if (id > 0) resolve({ id, name: 'ដារា' }); else reject(new Error('Invalid ID')); }); // .then / .catch fetchUser(1) .then(user => console.log(user.name)) .catch(err => console.error(err)) .finally(() => console.log('Done')); // async / await (ស្អាតជាង) async function loadData() { try { const user = await fetchUser(1); console.log(user.name); } catch (err) { console.error(err.message); } } // Fetch API async function getPosts() { const res = await fetch('https://jsonplaceholder.typicode.com/posts'); const data = await res.json(); return data.slice(0, 5); } // Promise.all — run parallel const [u1, u2] = await Promise.all([ fetchUser(1), fetchUser(2) ]);
Closure & Scope
Lexical Scope, Closure, Hoisting, IIFE, The Module Pattern។
// Closure: function "ចាំ" environment ដែលវាត្រូវបានបង្កើត function makeCounter(start = 0) { let count = start; // private variable return { increment: () => ++count, decrement: () => --count, reset: () => { count = start; }, value: () => count }; } const c = makeCounter(10); c.increment(); // 11 c.increment(); // 12 c.decrement(); // 11 c.value(); // 11 // IIFE — Immediately Invoked Function Expression const app = (function() { const private = 'secret'; return { getSecret: () => private }; })(); app.getSecret(); // 'secret' // Hoisting console.log(hello()); // ✅ — function declaration hoisted function hello() { return 'Hi!'; } console.log(hi); // ❌ ReferenceError — let not hoisted const hi = () => 'Hi!';
ES6+ Modern JavaScript
Symbol, Iterator, Generator, Proxy, Reflect, WeakMap, WeakSet, Intl API។
// Generator Function (*) function* range(start, end, step = 1) { for (let i = start; i <= end; i += step) { yield i; } } [...range(1, 10, 2)]; // [1,3,5,7,9] // Proxy — intercept object operations const handler = { get(target, key) { return key in target ? target[key] : `គ្មាន "${key}"`; }, set(target, key, val) { if (typeof val !== 'number') throw new TypeError('Numbers only!'); target[key] = val; return true; } }; const scores = new Proxy({}, handler); scores.math = 95; // WeakMap — garbage collected keys const cache = new WeakMap(); const key = {}; cache.set(key, 'cached data'); // Intl — Internationalization new Intl.NumberFormat('km-KH', { style: 'currency', currency: 'KHR' }) .format(50000); // ៥០.០០០,០០ ៛ new Intl.DateTimeFormat('km-KH').format(new Date());
Functional Programming
Pure Functions, Immutability, Composition, Currying, Memoization, Functor, Monad concept។
// Pure Function — no side effects const add = (a, b) => a + b; const double = x => x * 2; const addTax = x => x * 1.1; const round = x => Math.round(x); // Function Composition const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x); const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x); const calcPrice = pipe(double, addTax, round); calcPrice(100); // 220 // Currying const curry = fn => { const arity = fn.length; return function curried(...args) { return args.length >= arity ? fn(...args) : (...more) => curried(...args, ...more); }; }; const cAdd = curry((a, b, c) => a + b + c); cAdd(1)(2)(3); // 6 cAdd(1, 2)(3);// 6 // Memoization const memo = fn => { const cache = new Map(); return (...args) => { const key = JSON.stringify(args); if (cache.has(key)) return cache.get(key); const result = fn(...args); cache.set(key, result); return result; }; }; const memoFib = memo(n => n <= 1 ? n : memoFib(n-1) + memoFib(n-2));
Error Handling & Modules
try/catch/finally, Custom Errors, ES Modules (import/export), Dynamic Import។
// Custom Error Classes class ValidationError extends Error { constructor(message, field) { super(message); this.name = 'ValidationError'; this.field = field; } } class NetworkError extends Error { constructor(message, status) { super(message); this.name = 'NetworkError'; this.status = status; } } // try / catch / finally async function saveUser(data) { try { if (!data.email) { throw new ValidationError('Email required', 'email'); } const res = await fetch('/api/users', { method: 'POST' }); if (!res.ok) throw new NetworkError('Failed', res.status); return await res.json(); } catch (err) { if (err instanceof ValidationError) { console.warn(`Field ${err.field}: ${err.message}`); } else if (err instanceof NetworkError) { console.error(`HTTP ${err.status}: ${err.message}`); } else { throw err; } } finally { console.log('ទំព័រ Loading បញ្ចប់'); } }
// math.js — Named exports export const PI = Math.PI; export const add = (a, b) => a + b; export default class Calculator { ... } // main.js — Import import Calculator, { PI, add } from './math.js'; import * as Math2 from './math.js'; // Dynamic Import — Lazy loading const { add: lazyAdd } = await import('./math.js'); // Re-export export { PI, add } from './math.js';
Performance & Patterns
Debounce, Throttle, Observer Pattern, Singleton, Factory, Module Pattern, Web Workers។
// Debounce — wait ចាំ user ឈប់ type const debounce = (fn, delay) => { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; }; input.addEventListener('input', debounce(search, 300)); // Throttle — run ម្ដង ក្នុង interval const throttle = (fn, limit) => { let last = 0; return (...args) => { const now = Date.now(); if (now - last >= limit) { last = now; fn(...args); } }; }; window.addEventListener('scroll', throttle(onScroll, 100));
// Singleton class Store { static #instance; static getInstance() { return Store.#instance ??= new Store(); } #state = {}; set(key, val) { this.#state[key] = val; } get(key) { return this.#state[key]; } } // Observer Pattern class EventEmitter { #events = {}; on(event, fn) { (this.#events[event] ??= []).push(fn); } off(event, fn) { this.#events[event] = this.#events[event]?.filter(f => f !== fn); } emit(event, data) { this.#events[event]?.forEach(fn => fn(data)); } } const bus = new EventEmitter(); bus.on('login', user => console.log(`Welcome ${user.name}`)); bus.emit('login', { name: 'ដារា' });
សូមអបអរ! អ្នកបានបញ្ចប់មេរៀន JavaScript ទាំងអស់ ១៤ — ពី Variable រហូតដល់ Design Patterns! ជំហានបន្ទាប់: React, Node.js, TypeScript!