skip to Main Content
let num = 1
let st = 'data'
console.log(typeof `${num}`, typeof `${st}`)

the output of the first variable should be number but it’s printing string when I am using string interpolation console.log(typeof `${num}`) it’s printing string, but when I am writing console.log(typeof num) it’s printing number
can someone plz expalin why

2

Answers


  1. The result of string interpolation (called a template literal) is by definition a string, so that’s what typeof returns. The type of the original expression that was interpolated is not available. Usually you’re not just putting one expression into the template, there will be multiple expression and/or other text, so it wouldn’t even be meaningful for the type to come from the interpolated expression. E.g. if you did

    console.log(typeof `num = ${num}, st = ${st}`);
    

    why would you expect the result to be related to the types of num or st?

    Login or Signup to reply.
  2. The backtick converts your number into a string. If you are deadset on using backticks, you can implicitly cast it back to a number like so:

    console.log(typeof +`${num}`);
    

    One of the few use cases I’d see for this is if you got number variables as different digits. Example:

    // Compose the number "57" and print the type
    const tensDigit = 5;
    const onesDigit = 7;
    console.log(typeof +`${tensDigit}${onesDigit}`)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search