JS Course › ទំព័រដើម
0 / 14
📖 JavaScript Course

ស្វែងយល់
JavaScript ពីដំបូង

មេរៀននេះ គ្របដណ្ដប់ JavaScript ចាប់ពីការប្រកាស Variable រហូតដល់ Async/Await, OOP, Functional Programming, Design Patterns និង Performance Optimization។

14
មេរៀន
3
កម្រឹត
80+
Code Examples
Live
Demo Editor
🟢 Basic (ចាប់ផ្តើម)
  • Variable, Data Types
  • Operators, Expressions
  • if/else, for, while loop
  • Functions, Arrow Function
  • Array & Object
🟠 Intermediate (មធ្យម)
  • DOM Manipulation
  • Events & Listeners
  • OOP, Classes, Inheritance
  • Async, Promise, Fetch API
🟣 Advanced (ខ្ពស់)
  • Closure, Scope, Hoisting
  • ES6+ Features
  • Functional Programming
  • Error Handling, Modules
  • Performance & Patterns
💡 ត្រូវការអ្វី?
  • Browser ទំនើប (Chrome, Firefox)
  • VS Code ឬ Text Editor
  • ចំណេះដឹង HTML/CSS មូលដ្ឋាន
  • ចិត្តចង់រៀន 😄
🟢 Basic — មេរៀនទី ១

Variable & Data Types

ការប្រកាស Variable ដោយប្រើ var, let, const និង Data Types ទូទៅក្នុង JavaScript។

var / let / const
KeywordScopeReassign?Hoisted?
varFunction✅ បាន✅ (undefined)
letBlock✅ បាន⛔ TDZ
constBlock⛔ មិនបាន⛔ TDZ
JS
// ✅ ប្រើ const ជាលំនាំ
const name = 'ដារា';
const age  = 22;

// ✅ ប្រើ let ពេល value ត្រូវផ្លាស់ប្ដូរ
let score = 0;
score = 95;

// ⚠️  var (ចៀសវាង — scope problem)
var old = 'legacy';
Data Types ៧ ប្រភេទ
JS
// 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 Literals & Type Conversion
JS
// 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
🔴 សាកល្បង Code ខាងក្រោម
// Output នឹងបង្ហាញត្រង់នេះ
🟢 Basic — មេរៀនទី ២

Operators & Expressions

Arithmetic, Comparison, Logical, Ternary, Nullish Coalescing, Optional Chaining។

Arithmetic & Assignment
JS
// 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)
Comparison & Logical
JS
// == 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 ?? 'មិនស្គាល់';
🟢 Basic — មេរៀនទី ៣

Control Flow — if / loop

if/else, switch, for, while, do-while, for...of, for...in, break, continue។

if / else if / else & switch
JS
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('ថ្ងៃផ្សេង');
}
Loops ទាំងអស់
JS
// 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);
}
🟢 Basic — មេរៀនទី ៤

Functions

Function Declaration, Expression, Arrow Function, Default Params, Rest, Spread, Callback។

ប្រភេទ Function
JS
// 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));
🔴 Live Demo
// Output
🟢 Basic — មេរៀនទី ៥

Array & Object

Array Methods, Destructuring, Spread, Object Methods, Optional Chaining។

Array Methods ខ្លឹមសារ
JS
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]
Object Methods
JS
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 }
🟠 Intermediate — មេរៀនទី ៦

DOM Manipulation

ការគ្រប់គ្រង HTML Elements ពីក្នុង JavaScript — Select, Create, Modify, Remove។

Select Elements
JS
// ជ្រើសរើស 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 & Remove Elements
JS
// 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);
🟠 Intermediate — មេរៀនទី ៧

Events & Listeners

addEventListener, Event Object, Delegation, Custom Events, Keyboard & Mouse Events។

addEventListener
JS
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);
🟠 Intermediate — មេរៀនទី ៨

OOP & Classes

Class, Constructor, Methods, Inheritance (extends), static, getter/setter, Private Fields។

Class & Inheritance
JS
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: ហ្វូ! 🐕
🟠 Intermediate — មេរៀនទី ៩

Async / Promise / Fetch

Callback Hell, Promise, .then/.catch, async/await, Fetch API, Error Handling។

Promise & async/await
JS
// 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)
]);
🟣 Advanced — មេរៀនទី ១០

Closure & Scope

Lexical Scope, Closure, Hoisting, IIFE, The Module Pattern។

Closure ជ្រៅ
JS
// 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!';
🟣 Advanced — មេរៀនទី ១១

ES6+ Modern JavaScript

Symbol, Iterator, Generator, Proxy, Reflect, WeakMap, WeakSet, Intl API។

Generator & Iterator
JS
// 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());
🟣 Advanced — មេរៀនទី ១២

Functional Programming

Pure Functions, Immutability, Composition, Currying, Memoization, Functor, Monad concept។

Pure Functions & Composition
JS
// 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));
🟣 Advanced — មេរៀនទី ១៣

Error Handling & Modules

try/catch/finally, Custom Errors, ES Modules (import/export), Dynamic Import។

Error Types & Custom Error
JS
// 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 បញ្ចប់');
  }
}
ES Modules
JS
// 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';
🟣 Advanced — មេរៀនទី ១៤

Performance & Patterns

Debounce, Throttle, Observer Pattern, Singleton, Factory, Module Pattern, Web Workers។

Debounce & Throttle
JS
// 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));
Design Patterns
JS
// 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!