jsartisan / frontend-challenges

FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
https://frontend-challenges.com
20 stars 3 forks source link

Logical Operators #61

Closed jsartisan closed 1 month ago

jsartisan commented 1 month ago

Info

difficulty: easy
title: Logical Operators
type: quiz
tags: javascript, logical operators

Question

What will the following code snippet log to the console?

let a = 1;
let b = "";
let c = 0;

console.log(a && b && c);
console.log(a || b || c);

Solution

The console output will be:

""
1

Explaination

In the code snippet, we are using the logical AND (&&) and logical OR (||) operators to evaluate expressions involving variables a, b, and c.

  1. Logical AND (&&) Operation:

    • The && operator returns the first falsy value it encounters, or the last value if all values are truthy.
    • Here's how a && b && c is evaluated:
      • a is 1, which is truthy.
      • b is "", which is falsy.
      • c is 0, which is falsy.
      • Therefore, a && b && c evaluates to the first falsy value encountered, which is "".
      • So, console.log(a && b && c); logs "".
  2. Logical OR (||) Operation:

    • The || operator returns the first truthy value it encounters, or the last value if all values are falsy.
    • Here's how a || b || c is evaluated:
      • a is 1, which is truthy.
      • b is "", which is falsy.
      • c is 0, which is falsy.
      • Therefore, a || b || c evaluates to the first truthy value encountered, which is 1.
      • So, console.log(a || b || c); logs 1.
github-actions[bot] commented 1 month ago

64 - Pull Request updated.