// Basic function
function greet(name) {
return `Hello, ${name}!`
}
// Call / invoke
greet("Min") // "Hello, Min!"
greet("Aye") // "Hello, Aye!"
// Multiple parameters
function add(a, b) {
return a + b
}
add(3, 4) // 7
// No return = undefined
function sayHi() {
console.log("Hi!")
// no return
}
let result = sayHi() // result = undefined
function greet(name = "Guest", greeting = "Hello") {
return `${greeting}, ${name}!`
}
greet() // "Hello, Guest!"
greet("Min") // "Hello, Min!"
greet("Min", "Mingalaba") // "Mingalaba, Min!"
// Real example
function createUser(name, role = "user", active = true) {
return { name, role, active }
}
createUser("Ko Min")
// { name: "Ko Min", role: "user", active: true }
// Function Expression — variable မှာ သိမ်း
const multiply = function(a, b) {
return a * b
}
multiply(4, 5) // 20
// Arrow Function — modern, shorter
const multiply = (a, b) => a * b
// Arrow function styles
const double = x => x * 2 // 1 param, no ()
const square = (x) => x * x // 1 param with ()
const add = (a, b) => a + b // 2 params
const greet = (name) => { // multi-line
const msg = `Hello, ${name}!`
return msg
}
// No params
const now = () => new Date().toLocaleTimeString()
// ...rest collects extra args into array
function sum(...numbers) {
let total = 0
for (const n of numbers) total += n
return total
}
sum(1, 2, 3) // 6
sum(1, 2, 3, 4, 5) // 15
sum(10, 20) // 30
// Mix with regular params
function introduce(greeting, ...names) {
return `${greeting}: ${names.join(", ")}`
}
introduce("Hi", "Min", "Aye", "Kyaw")
// "Hi: Min, Aye, Kyaw"
// Function ကို argument အနေနဲ့ pass နိုင်တယ်
function doMath(a, b, operation) {
return operation(a, b)
}
const add = (a, b) => a + b
const sub = (a, b) => a - b
const mul = (a, b) => a * b
doMath(10, 5, add) // 15
doMath(10, 5, sub) // 5
doMath(10, 5, mul) // 50
// setTimeout — callback function
setTimeout(() => {
console.log("3 seconds later!")
}, 3000)
// Array methods use callbacks
[1,2,3].forEach(n => console.log(n))
[1,2,3].map(n => n * 2) // [2,4,6]
[1,2,3].filter(n => n > 1) // [2,3]
let globalVar = "I'm global" // ဘယ်နေရာမှာမဆို ရမယ်
function myFunc() {
let localVar = "I'm local" // ဒီ function ထဲမှာပဲ ရမယ်
console.log(globalVar) // ✅ Global ရမယ်
console.log(localVar) // ✅ Local ရမယ်
}
myFunc()
console.log(globalVar) // ✅ OK
console.log(localVar) // ❌ Error: localVar is not defined
// Block scope (let/const)
{
let blockVar = "block"
console.log(blockVar) // ✅ Inside block
}
console.log(blockVar) // ❌ Error: outside block
| Type | Syntax | this binding | Hoisting |
|---|---|---|---|
| Declaration | function fn() {} | Own this | ✅ Hoisted |
| Expression | const fn = function() {} | Own this | ❌ No |
| Arrow | const fn = () => {} | Lexical this | ❌ No |
this
← JS 03 | Next: JS Lesson 05 → Arrays →