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
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 didwhy would you expect the result to be related to the types of
num
orst
?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:
One of the few use cases I’d see for this is if you got number variables as different digits. Example: