函式是一段可重複使用的程式碼,能讓開發者把大型程式拆成多個小模組,提升可讀性與維護性。
function sayHello() {
alert('Hello there');
}
sayHello();
function sayHello(name, age) {
alert(name + ' is ' + age + ' years old.');
}
sayHello('Zara', 7);
function concatenate(first, last) {
const full = first + last;
return full;
}
const result = concatenate('Zara', 'Ali');
alert(result);
return 會結束函式並傳回結果。若沒有 return,函式預設傳回 undefined。