← कोर्स पर वापस जाएँ: JavaScript from scratch

Conditionals: if, else, switch and the ternary operator

वीडियो जल्द आ रहा है

Until now your programs ran from top to bottom without deviating. Useful programs need to decide: if the user is an adult, show some content; if the password is wrong, show an error. That is what conditional structures are for: they run a block of code only when a condition is met. It is one of the most important ideas in all of programming.

if, else if and else

The if structure receives a condition in parentheses and a block in braces. If the condition is truthy, the block runs. With else you define what to do otherwise and with else if you chain more conditions. JavaScript evaluates from top to bottom and runs only the first block that matches, so order matters: put the most specific conditions first.

javascript
const score = 78;

if (score >= 90) {
  console.log('Excellent');
} else if (score >= 70) {
  console.log('Good');
} else if (score >= 50) {
  console.log('Pass');
} else {
  console.log('Try again');
}
// Output: Good

const age = 17;
const hasPermission = true;
if (age >= 18 || hasPermission) {
  console.log('Access granted');
}

The ternary operator

When you only need to choose between two values, the ternary operator condition ? valueIfTrue : valueIfFalse is a compact way to write it. It is used inside expressions, for example to assign a variable or build a message. Use it for simple cases; if you start nesting ternaries, an if is more readable.

switch for many cases

When you compare the same variable with many concrete values, switch is cleaner than a chain of else if. Each case compares with strict equality. You must end each case with break; if you forget, execution continues into the next case (fall-through), a classic mistake. The default block runs if no case matches.

javascript
const day = 'sat';

switch (day) {
  case 'sat':
  case 'sun':
    console.log('Weekend');
    break;
  case 'mon':
    console.log('Start of the week');
    break;
  default:
    console.log('Regular weekday');
}
// Output: Weekend

const temperature = 31;
const advice = temperature > 30 ? 'Drink water' : 'Enjoy the day';
console.log(advice); // Drink water

// Optional chaining + default
const user = { name: 'Leo' };
console.log(user.address?.city ?? 'Unknown city'); // Unknown city

Look at the last example: the ?. operator (optional chaining) avoids an error when an intermediate property does not exist, and ?? provides a default value. We will study it with objects in week 6, but it already helps write safer conditions.

Well-written conditions

Writing clear conditions is an art. Avoid repeating the same thing in different forms: if (active === true) is the same as if (active). Use boolean variable names that read like a sentence, such as isLoggedIn or hasStock. Prefer early return inside functions: check the invalid cases first and leave, so the normal path stays unnested. And remember falsy values: if (list.length) works because 0 is falsy, but if (list.length > 0) communicates your intent better. Code that is easy to read has fewer errors and is easier to change.

✎ मेरे नोट्स

केवल इस ब्राउज़र में सहेजा गया। खाते में रखने के लिए साइन इन करें।0/5000 अक्षर

← पिछलाअगला →