© Khmer Angkor Academy - sophearithput168

មុខងារ (Functions)

សេចក្តីផ្តើម

Functions គឺជាធាតុផ្សំមូលដ្ឋានបំផុតនៃ JavaScript។ វាអនុញ្ញាតឱ្យយើងដាក់កូដជាក្រុម reuse code និងធ្វើឱ្យកូដមានការរៀបចំប្រសើរ។ Functions ជាកូដដែលអាច execute ច្រើនដងដោយគ្រាន់តែហៅឈ្មោះវា។

ហេតុអ្វីត្រូវប្រើ Functions? 🤔

  • ♻️ Reusability: សរសេរម្តងប្រើច្រើនកន្លែង
  • 📦 Organization: ដាក់កូដជាក្រុមតាមមុខងារ
  • 🔧 Maintainability: ងាយស្រួលកែប្រែ និង debug
  • 🎯 Abstraction: លាក់ complexity ធ្វើឱ្យកូដងាយយល់
  • Testing: ងាយស្រួលធ្វើតេស្ត

១. បង្កើត Function

Syntax មូលដ្ឋាន

function functionName(parameters) {
  // code to execute
  return value; // optional
}

រចនាសម្ព័ន្ធ Function

  1. function keyword - ប្រកាសថាយើងកំពុងបង្កើត function
  2. Function name - ឈ្មោះរបស់ function (ត្រូវតាមច្បាប់ដាក់ឈ្មោះ variable)
  3. () Parentheses - ដាក់ parameters (optional)
  4. {} Curly braces - ដាក់កូដដែលត្រូវ execute
  5. return statement - ត្រឡប់តម្លៃ (optional)

ឧទាហរណ៍ពិសេស

Function គ្មាន Parameters

function greet() {
  console.log("ជំរាបសួរ!");
}

greet(); // Output: ជំរាបសួរ!

Function មាន Parameters

function greet(name) {
  console.log("ជំរាបសួរ " + name + "!");
}

greet("សុខា"); // Output: ជំរាបសួរ សុខា!
greet("ដារា"); // Output: ជំរាបសួរ ដារា!

Function មាន Return Value

function add(a, b) {
  return a + b;
}

let sum = add(5, 3); // sum = 8
console.log(sum); // Output: 8

ចំណាំ: Function ដែលមិនមាន return statement នឹង return undefined ដោយស្វ័យប្រវត្តិ។


២. Parameters និង Arguments

ភាពខុសគ្នារវាង Parameters និង Arguments

  • Parameters: អញ្ញាតដែលបញ្ជាក់ពេលបង្កើត function
  • Arguments: តម្លៃពិតប្រាកដដែលផ្តល់ពេលហៅ function
function calculate(x, y) {  // x, y ជា parameters
  return x * y;
}

calculate(5, 3);  // 5, 3 ជា arguments

Multiple Parameters

function createProfile(name, age, city) {
  return "ខ្ញុំឈ្មោះ " + name + " អាយុ " + age + " ឆ្នាំ នៅ" + city;
}

let profile = createProfile("សុខា", 25, "ភ្នំពេញ");
console.log(profile);
// Output: ខ្ញុំឈ្មោះ សុខា អាយុ 25 ឆ្នាំ នៅភ្នំពេញ

Default Parameters (ES6)

function greet(name = "បងប្អូន") {
  return "ជំរាបសួរ " + name;
}

console.log(greet());        // Output: ជំរាបសួរ បងប្អូន
console.log(greet("សុខា"));  // Output: ជំរាបសួរ សុខា

Rest Parameters (...args)

ប្រើសម្រាប់ទទួល arguments ច្រើនក្នុងរូបភាព array:

function sum(...numbers) {
  let total = 0;
  for (let num of numbers) {
    total += num;
  }
  return total;
}

console.log(sum(1, 2, 3));        // Output: 6
console.log(sum(10, 20, 30, 40)); // Output: 100

៣. Return Statement

អ្វីជា Return?

return statement ធ្វើឱ្យ function ត្រឡប់តម្លៃមួយទៅកាន់កន្លែងដែលហៅវា។ បន្ទាប់ពី return execute កូដខាងក្រោមនឹងមិនត្រូវ execute ទេ។

លក្ខណៈសំខាន់នៃ Return

  • 🛑 Stops execution: Function ឈប់ដំណើរការភ្លាមពេល return
  • ↩️ Returns value: ត្រឡប់តម្លៃទៅកន្លែងហៅ
  • Single value: អាច return តម្លៃតែមួយ (ប៉ុន្តែអាចជា object/array)
  • No return = undefined: ប្រសិនមិនមាន return នឹងត្រឡប់ undefined

ឧទាហរណ៍

Return Number

function square(num) {
  return num * num;
}

let result = square(5); // 25

Return String

function getGreeting(name) {
  return "សួស្តី " + name + "!";
}

let message = getGreeting("សុខា");

Return Object

function createUser(name, age) {
  return {
    name: name,
    age: age,
    country: "Cambodia"
  };
}

let user = createUser("ដារា", 22);
console.log(user.name); // Output: ដារា

Multiple Returns (Early Exit)

function checkAge(age) {
  if (age < 0) {
    return "អាយុមិនត្រឹមត្រូវ";
  }
  if (age < 18) {
    return "អនីតិជន";
  }
  return "ពេញវ័យ";
}

console.log(checkAge(15));  // Output: អនីតិជន
console.log(checkAge(25));  // Output: ពេញវ័យ
console.log(checkAge(-5));  // Output: អាយុមិនត្រឹមត្រូវ

សំខាន់: កូដបន្ទាប់ពី return មិនដំណើរការទេ! Code នោះគេហៅថា "unreachable code"។


៤. Function Scope (វិសាលភាព)

អ្វីជា Scope?

Scope កំណត់ថាតើ variable ណាអាចត្រូវបានប្រើនៅកន្លែងណា។ JavaScript មាន function scope និង block scope។

Local Variables (អញ្ញាតមូលដ្ឋាន)

Variables ដែលបង្កើតក្នុង function អាចប្រើបានតែក្នុង function នោះប៉ុណ្ណោះ:

function myFunction() {
  let localVar = "ខ្ញុំនៅក្នុង function";
  console.log(localVar); // ✅ Works
}

myFunction();
console.log(localVar); // ❌ Error: localVar is not defined

Global Variables (អញ្ញាតសកល)

Variables ដែលបង្កើតនៅខាងក្រៅ function អាចប្រើបានគ្រប់កន្លែង:

let globalVar = "ខ្ញុំជា global";

function showGlobal() {
  console.log(globalVar); // ✅ Works
}

showGlobal();
console.log(globalVar); // ✅ Works

Parameter Shadowing

Parameters នឹងជាន់លើ global variables ដែលមានឈ្មោះដូចគ្នា:

let name = "Global Name";

function greet(name) {
  // parameter name ជាន់លើ global name
  console.log(name); // ប្រើ parameter name
}

greet("Local Name"); // Output: Local Name
console.log(name);   // Output: Global Name

Best Practice: ជៀសវាងការប្រើ global variables ច្រើនពេក។ ប្រើ parameters និង local variables ជំនួស។


៥. Function Expressions

Function Declaration vs Function Expression

Function Declaration (របៀបធម្មតា)

function greet() {
  return "Hello";
}

Function Expression (កំណត់ទៅ variable)

const greet = function() {
  return "Hello";
};

// ហៅ function
greet();

ភាពខុសគ្នា

Feature Declaration Expression
Hoisting ✅ អាចហៅមុនពេលបង្កើត ❌ ត្រូវបង្កើតមុនពេលហៅ
Name Required ✅ ត្រូវមានឈ្មោះ ❌ អាចគ្មានឈ្មោះ (anonymous)
Usage Stand-alone Assigned to variable

ឧទាហរណ៍ Hoisting

// ✅ Works - Function Declaration
greet1(); // Output: Hello
function greet1() {
  console.log("Hello");
}

// ❌ Error - Function Expression
greet2(); // Error: greet2 is not defined
const greet2 = function() {
  console.log("Hello");
};

៦. Arrow Functions (ES6)

Syntax ថ្មីនិងខ្លី

Arrow functions ផ្តល់នូវវិធីសរសេរ functions ដែលខ្លីនិងទំនើប:

Traditional Function

const add = function(a, b) {
  return a + b;
};

Arrow Function

const add = (a, b) => {
  return a + b;
};

// ឬខ្លីជាងនេះទៀត (implicit return)
const add = (a, b) => a + b;

Syntax Variations

គ្មាន Parameters

const greet = () => "Hello!";

Parameter មួយ (parentheses optional)

const square = x => x * x;
// ឬ
const square = (x) => x * x;

Multiple Parameters

const multiply = (a, b) => a * b;

Multiple Statements

const calculate = (a, b) => {
  let sum = a + b;
  let product = a * b;
  return {sum, product};
};

លក្ខណៈពិសេសរបស់ Arrow Functions

  • 📝 Concise syntax: សរសេរខ្លីជាង
  • 🎯 Implicit return: auto return សម្រាប់ single expression
  • 🔗 Lexical this: មិន bind this ផ្ទាល់ខ្លួន
  • No arguments object: មិនមាន arguments object
  • Can't be constructors: មិនអាចប្រើជា constructor

៧. Callback Functions

អ្វីជា Callback?

Callback function គឺជា function ដែលត្រូវបានផ្តល់ជា argument ទៅ function មួយទៀត។ វាត្រូវបាន execute ពេលក្រោយ។

ឧទាហរណ៍មូលដ្ឋាន

function processUser(name, callback) {
  console.log("Processing " + name);
  callback(name); // ហៅ callback function
}

function greetUser(name) {
  console.log("Hello " + name + "!");
}

processUser("សុខា", greetUser);
// Output:
// Processing សុខា
// Hello សុខា!

Anonymous Callback

processUser("ដារា", function(name) {
  console.log("Welcome " + name);
});

Arrow Function Callback

processUser("ចន្ទា", name => console.log("Hi " + name));

Real-world Examples

Array Methods

// forEach
[1, 2, 3].forEach(num => console.log(num * 2));

// map
let doubled = [1, 2, 3].map(num => num * 2);
// [2, 4, 6]

// filter
let evens = [1, 2, 3, 4].filter(num => num % 2 === 0);
// [2, 4]

Event Handlers

button.addEventListener("click", function() {
  console.log("Button clicked!");
});

// Arrow function callback
button.addEventListener("click", () => {
  console.log("Button clicked!");
});

setTimeout / setInterval

setTimeout(function() {
  console.log("បន្ទាប់ពី 2 វិនាទី");
}, 2000);

// Arrow function
setTimeout(() => console.log("After 2s"), 2000);

សេចក្តីសង្ខេប

អ្វីដែលយើងបានរៀន 📚

១. Function Basics

  • ✅ Function declaration syntax
  • ✅ Parameters និង arguments
  • ✅ Return statements
  • ✅ Function scope

២. Advanced Concepts

  • ✅ Function expressions
  • ✅ Arrow functions (ES6)
  • ✅ Callback functions
  • ✅ Default parameters
  • ✅ Rest parameters

៣. Best Practices 💡

  • 📝 ដាក់ឈ្មោះ functions ឱ្យច្បាស់លាស់និងពណ៌នាបាន
  • 🎯 Function មួយគួរតែធ្វើមួយកិច្ចការ
  • ♻️ DRY principle - Don't Repeat Yourself
  • 📦 រក្សា functions តូចនិងងាយគ្រប់គ្រង
  • ✅ ប្រើ arrow functions សម្រាប់ callbacks
  • 🔍 ជៀសវាង global variables

មេរៀនបន្ទាប់: យើងនឹងសិក្សាអំពី Events, DOM Manipulation និង Asynchronous Programming!