Home > Blockchain >  typeof code i think there is something weird
typeof code i think there is something weird

Time:06-24

When i delete just x from typeof x and runit gives numberobject as a output with no spaces when i just delete y from type y and run it gives nothing

<!DOCTYPE html>
<html>

<body>

  <h2>JavaScript Strings</h2>

  <p id="demo"></p>

  <script>
    // x is a string
    let x = "John";

    // y is an object
    let y = new String("John");

    document.getElementById("demo").innerHTML =
      typeof x   "<br>"   typeof y;
  </script>

</body>

</html>

CodePudding user response:

When you create a variable like this; var a = "hello world", you're using a string literal to create the string. But when you create a variable like this; new String("hello world"), you're actually instantiating the "String" object. When replacing a string object, a new object is created each time, but with a string literal, it is only replaced.

The problem that you're mentioning is happening because you are using the typeof() function without any paranthesis, which means your code is trying to use "<br>" as the arguments. The type of "<br>" is a number, that's why it's telling you it's a number in the same line as object (The <br> isn't being rendered because you used it in the function). Instead, use 'typeof' like typeof(VAR) instead of typeof VAR.

  • Related