Skip to content
beginnerPhase 32 · JavaScript Fundamentals

Conditions

Use if/else, switch, ternary, and short-circuit evaluation effectively.

30m
0 problems
Topic Progress0%

if/else

if/else

Basic if

const age = 18;

if (age >= 18) {
  console.log('Adult');
}

if/else

const age = 15;

if (age >= 18) {
  console.log('Adult');
} else {
  console.log('Minor');
}

if/else if/else

const grade = 85;

if (grade >= 90) {
  console.log('A');
} else if (grade >= 80) {
  console.log('B');
} else if (grade >= 70) {
  console.log('C');
} else if (grade >= 60) {
  console.log('D');
} else {
  console.log('F');
}

Nested if

const isLoggedIn = true;
const isAdmin = true;

if (isLoggedIn) {
  if (isAdmin) {
    console.log('Admin dashboard');
  } else {
    console.log('User dashboard');
  }
} else {
  console.log('Login page');
}

Truthy/Falsy Conditions

const name = '';

if (name) {
  console.log('Has name');
} else {
  console.log('No name'); // This runs
}

// Check explicitly
if (name !== undefined && name !== null && name !== '') {
  console.log('Has name');
}

Block Scope

if (true) {
  let x = 10;
  const y = 20;
  var z = 30;
}

console.log(z); // 30 (var is function scoped)
// console.log(x); // Error: x is not defined

Guard Clauses

// Instead of nesting
function process(user) {
  if (!user) return;
  if (!user.isActive) return;
  if (!user.hasPermission) return;
  
  // Main logic
  doSomething();
}

switch Statement

switch Statement

Basic Syntax

const day = 'Monday';

switch (day) {
  case 'Monday':
    console.log('Start of week');
    break;
  case 'Friday':
    console.log('TGIF!');
    break;
  case 'Saturday':
  case 'Sunday':
    console.log('Weekend!');
    break;
  default:
    console.log('Regular day');
}

Fall-Through

// Without break, cases fall through
const month = 2;

switch (month) {
  case 1:
  case 2:
  case 3:
    console.log('Q1');
    break;
  case 4:
  case 5:
  case 6:
    console.log('Q2');
    break;
}

Strict Comparison

// switch uses === (strict equality)
const x = '5';

switch (x) {
  case 5:
    console.log('Number 5'); // Not matched
    break;
  case '5':
    console.log('String 5'); // Matched
    break;
}

When to Use switch vs if/else

// Use switch for multiple discrete values
const getDayType = (day) => {
  switch (day) {
    case 'Saturday':
    case 'Sunday':
      return 'Weekend';
    default:
      return 'Weekday';
  }
};

// Use if/else for ranges and conditions
const getGrade = (score) => {
  if (score >= 90) return 'A';
  if (score >= 80) return 'B';
  if (score >= 70) return 'C';
  return 'F';
};

switch Expressions (Modern)

// Using in assignments
const type = switch (code) {
  case 200: 'success';
  case 404: 'not found';
  default: 'error';
};
// Note: This syntax is not yet standard

Ternary Operator

Ternary Operator

Basic Syntax

// condition ? valueIfTrue : valueIfFalse
const age = 20;
const status = age >= 18 ? 'Adult' : 'Minor';

Equivalent to if/else

// Long form
let result;
if (score >= 60) {
  result = 'Pass';
} else {
  result = 'Fail';
}

// Ternary
const result = score >= 60 ? 'Pass' : 'Fail';

Nested Ternary

const grade = 85;
const result = grade >= 90 ? 'A'
  : grade >= 80 ? 'B'
  : grade >= 70 ? 'C'
  : grade >= 60 ? 'D'
  : 'F';

Ternary in JSX

// React conditional rendering
function App({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn ? <Dashboard /> : <LoginForm />}
    </div>
  );
}

Ternary vs && Operator

// When you only need true case
const message = isLoggedIn && 'Welcome!';

// vs ternary
const message = isLoggedIn ? 'Welcome!' : '';

// && is simpler for conditional rendering
{isLoggedIn && <UserProfile />}

Best Practices

// Good: Simple ternary
const color = isActive ? 'blue' : 'gray';

// Bad: Complex ternary (use if/else instead)
const result = condition1 ? value1 
  : condition2 ? value2 
  : condition3 ? value3 
  : value4; // Too complex!

In Template Literals

const name = 'John';
const message = `Hello, ${name ? name : 'Guest'}!`;

Practice Problems

0/3solved
Build Conditions Component

Create a reusable React component implementing Conditions. Include proper state management and accessibility.

Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where needed
Conditions Testing

Write unit and integration tests for Conditions using React Testing Library.

Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility tests
Conditions Performance

Optimize Conditions for performance. Consider memoization, code splitting, and bundle size.

Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysis

Quiz

1. What is the syntax of the ternary operator?

Question 1 options

2. What happens if you forget break in a switch case?

Question 2 options

3. When should you use switch over if/else?

Question 3 options

4. What does switch use for comparison?

Question 4 options

5. Which is better for simple conditional rendering in JSX?

Question 5 options

Flashcards

Question

What is the ternary operator?

Answer

A shorthand for if/else: condition ? valueIfTrue : valueIfFalse

Question

When does switch fall through?

Answer

When you forget the break statement, execution continues to the next case.

Question

When should you use if/else over switch?

Answer

When checking ranges, complex conditions, or multiple different variables.

Question

What is a guard clause?

Answer

An early return at the start of a function to handle edge cases before main logic.

Question

How do you handle multiple switch cases?

Answer

Stack cases without break statements between them to execute the same code.

Revision Notes

Key Takeaways

  • 1.if/else is for complex conditions and ranges
  • 2.switch is for discrete value comparison
  • 3.Ternary is shorthand for simple if/else
  • 4.Always use break in switch cases
  • 5.Guard clauses reduce nesting

Interview Tips

  • Know when to use switch vs if/else
  • Understand ternary operator syntax
  • Explain switch fall-through behavior
  • Be able to write guard clauses

Cheat Sheet

Conditions Cheat Sheet

if/else

if (condition) {
  // code
} else if (condition2) {
  // code
} else {
  // code
}

switch

switch (value) {
  case 'a':
    // code
    break;
  case 'b':
  case 'c':
    // code for both
    break;
  default:
    // code
}

Ternary

const result = condition ? valueIfTrue : valueIfFalse;

Guard Clauses

function process(data) {
  if (!data) return;
  // main logic
}