자바스크립트 NaN

In JavaScript, NaN stands for Not a Number. It is a special value that represents the result of an invalid mathematical operation or an undefined or unrepresentable value.

NaN is often returned when trying to perform arithmetic operations with values that are not numbers. For example:

let result = 10 / "hello";
console.log(result); // NaN

In this code snippet, we try to divide the number 10 by the string “hello”. Since this operation doesn’t make sense, JavaScript returns NaN.

NaN has some unique properties that may come in handy when working with mathematical operations. Here are a few key points to remember:

  1. NaN is not equal to any other value, including itself. This means that the comparison NaN === NaN will result in false.

  2. The isNaN() function can be used to check if a value is NaN. It returns true if the given value is NaN; otherwise, it returns false.

    console.log(isNaN(NaN)); // true
    console.log(isNaN(10)); // false
    
  3. NaN is considered a falsy value in JavaScript. This means that it is treated as false in logical operations.

    if (NaN) {
      console.log("This won't be executed");
    }
    

    In this example, the if condition evaluates to false, so the code block inside won’t be executed.

It’s important to handle NaN accordingly when writing JavaScript code. You might want to check for NaN before performing mathematical operations or use it as a condition for certain scenarios. Remember, NaN can propagate through calculations, so it’s crucial to handle it appropriately to avoid unexpected results in your code.

In conclusion, NaN is a special value in JavaScript that represents an invalid or undefined mathematical operation. By understanding its properties and using appropriate checks, you can handle NaN effectively in your JavaScript code.