Automatically translated.View original post

if..else../javascript

# Web Site Writing Basics

# javascript

# ifcondutional

if statement...Else in JavaScript is a control flow statement that allows your code to decide which code to execute a block based on a given condition. 🤖

Working principle ⚙️

If condition check: The system checks whether the condition in parentheses () is true.

The case is true: if the condition is true, the code in the block if ({...}) will be executed.

Case is false (else): If the condition is false (falsy), the code in the other block (which is an alternative part) will be executed instead.

Syntax structure 📝

JavaScript

If (condition _ to _ check) {

/ / Block Code A: Works if the 'condition' is true.

} else {

/ / Block Code B: Works if 'condition' is false

}

Example 💡

Suppose we want to check whether the exam score passed.

JavaScript

Let score = 75;

Let passingScore = 50;

If (score > = passingScore) {

console.log ("Congratulations! You passed the exam."); / / will work because 75 > = 50 is true.

} else {

console.log ("Sorry! You failed the exam.");

}

/ / Results: Congratulations! You passed the exam.

2025/10/12 Edited to

... Read moreนอกจากการใช้งานคำสั่ง if...else เบื้องต้นแล้ว ฉันอยากแชร์ประสบการณ์ที่เจอเมื่อเริ่มเขียนโปรแกรมด้วย JavaScript ซึ่งพบว่าการเข้าใจว่าค่าที่ตรวจสอบในเงื่อนไขเป็น "truthy" หรือ "falsy" ถือเป็นเรื่องสำคัญมาก เพราะค่าบางค่า เช่น 0, "", null, undefined จะถูกตีความเป็น false ทำให้โค้ดในบล็อก else ถูกเรียกใช้ อีกอย่างที่สำคัญคือการใช้คำสั่ง if...else ซ้อนกัน (nested if...else) เพื่อจัดการเงื่อนไขหลายกรณีอย่างมีประสิทธิภาพ เช่น การตรวจสอบคะแนนสอบหลายระดับเพื่อแยกระดับเกรด นอกจากนี้ยังมีวิธีอื่นๆ อย่างการใช้คำสั่ง switch ซึ่งบางครั้งจะเหมาะสมกว่าเมื่อมีหลายกรณีที่ต้องตรวจสอบ สำหรับผู้ที่เพิ่งเริ่มต้น แนะนำให้ลองเขียนโปรแกรมเล็กๆ เช่น ตรวจสอบว่าราคาสินค้ามีส่วนลดหรือไม่ หรือตรวจสอบอายุเพื่อแยกว่าคนคนนั้นเป็นเด็ก วัยรุ่น หรือผู้ใหญ่ เพื่อฝึกความเข้าใจในโครงสร้างควบคุม if...else ให้คล่อง จากคำแนะนำด้านบนและโค้ดตัวอย่างในบทความนี้ ฉันมั่นใจว่าคุณจะเข้าใจและใช้คำสั่ง if...else ใน JavaScript ได้ดีขึ้นอย่างแน่นอน และยังช่วยให้เขียนโปรแกรมที่มีความยืดหยุ่นและตอบสนองตามเงื่อนไขที่ต้องการได้อย่างถูกต้อง