A question about typeof operator in JS

Hello everyone. I’m curious to sort out a little curiosity about the typeof operator in JS. The typeof operator defines the type of a value/variable. My question is: why so? Isn’t that obvious? “33” is obviously a string, so “33” === 33 results unequal, therefore false. Now, so far I can think only of a case where it could be useful: can this operator force a type into another? If for instance I specify into a function that “Text” is actually a number, will I be able to run it in other parts of the code as defined by typeof? (I understand that this may be a quite useless question right now, but I can foresee that with a complex code this trick could be useful.) Thanks in advance for your answers!

typeof only retrieves type of value. If you do it like so:

typeof '33' === 'string'; // true

then it indeed makes very little sense. But consider this example:

function greet(name) {
  return `Hello ${typeof name === 'string' ? name : 'stranger'}!`;
}

Sometimes you won’t have control over what’s being passed to your function and you might wanna check the type.

There is no real way to force name here to be string, as there might be structures that are simply non-convertible.

The typeof operator is potentially useful because it tells you exactly the type of a variable or literal value. “33” is obviously a string, yes, but sometimes that value is stored in a variable and it changes, so the only way to know the type is by testing it in your code.

Also, note that "33" === 33 returning false means that either the operands are not equal or they are of different types. It does not tell you the type of one operand or the other. For that you’ll need to use typeof.

typeof does not convert a value from one type into another. It always returns a string, one of seven possible strings: string, number, boolean, function, undefined, symbol, or object. It returns object for objects, arrays, as well as null (which is a bug).

Could you please explain me the string above? :slight_smile:

Thanks for your clear explanation :slight_smile:

1 Like