Type Conversion in JavaScript [Tech Interview Quiz]
Type conversion in JavaScript is a tricky topic for beginners. If you don’t know it well, you’ll create may untentional bugs that could be invisible at a first glance. That’s why Senior interviewers like to start testing your JavaScript knowledge with the type system.
Consider the following code snippet.
Code snippet as a picture
|
|
What’s going to be printed to the console? (think well, then click for the answer and explanation)
Explanation
The first line, defines the variable
str
and initializes it as a string with the value'1'
.The second line of code does two typecasts, first the exclamation mark converts the string into boolean and negates it with
!str
. This gives youfalse
.Then the plus sign converts boolean into a number with
+false
which returns0
. The number 0 is saved into the variablestr
.Eventually, in the third line, the
typeof
operator looks up the current type ofstr
which isnumber
.
Answer
String
number
will be printed to the console.