ฟังก์ชัน JavaScript สามารถมีคำสั่ง return ที่เป็นทางเลือก เช่น สามารถเลือกคืนค่าได้ คำสั่งนี้ควรเป็นคำสั่งสุดท้ายในฟังก์ชัน
ตัวอย่างเช่น คุณสามารถส่งตัวเลขสองตัวในฟังก์ชันหนึ่ง จากนั้นคุณสามารถคาดหวังให้ฟังก์ชันส่งคืนการคูณไปยังโปรแกรมการโทรของคุณ
ตัวอย่าง
ลองตัวอย่างต่อไปนี้ มันกำหนดฟังก์ชันที่รับสองพารามิเตอร์และเชื่อมเข้าด้วยกันก่อนที่จะส่งกลับผลลัพธ์ในโปรแกรมการเรียก
สาธิตสด
<html>
<head>
<script type = "text/javascript">
function concatenate(first, last){
var full;
full = first + last;
return full;
}
function secondFunction(){
var result;
result = concatenate('John', 'Doe');
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "secondFunction()" value = "Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>