JavaScript Unary Operators: Converting Booleans with '+' and Strings with '!'. Asked in 2nd round Capgemini. Javascript interview question.

Let's break down Javascript concepts:

1. Evaluating console.log(+true);

  • Unary Plus Operator (+): This operator attempts to convert its operand into a number.
  • Operand: true: In JavaScript, the boolean value true is converted to the number 1 when using the unary plus operator.

    NOTE : true 
    → 1 & false → 0.

  • Evaluation:

    • +true1
  • Output:
    • The console.log function prints 1 to the console.

2. Evaluating console.log(!"ValueAdda");

  • Logical NOT Operator (!): This operator inverts the boolean value of its operand. If the operand is truthy, ! converts it to false; if falsy, to true.
  • Operand: "ValueAdda": In JavaScript, non-empty strings are considered truthy values.

    NOTE : falsy values in javascript are "", 0, false, null, undefined, NaN, and 0n. Here NaN means not a number and it's type if number and 0n mean representation of 0 in BigInt number.
  • Evaluation:
    • !"ValueAdda"false
  • Output:
    • The console.log function prints false to the console.

Summary of Outputs:

  • The first console.log outputs 1.
  • The second console.log outputs false.

Understanding these operators and their behavior with different data types is crucial for effective JavaScript programming.

Answer is :  A) 1 false

Post a Comment

Previous Post Next Post