Do you understand these points

  • 2020-12-26 05:33:46
  • OfStack

Yesterday, I played with a colleague. My colleague gave me a code topic about typeof, which was quite interesting. I would like to share it with you and consolidate my summary of typeof knowledge. If there is anything wrong, please point out and make progress together.

The code looks like this:


<!DOCTYPE html>
<head>
<title>typeof</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
</head>
<body>
<script>
var a= a||null; 
var b= c||null; 
var c= typeof f;
console.log(a);
console.log(b);
console.log(c);
</script>
</body>
</html>

So, what do you say the chrome debugger prints when you run this code?

Look at the renderings


Why does this happen?

First analyze the two null in the figure above


Because Javascript preparses the code (hoisting) before executing it.

What is pre-parsing (hoisting)?

It is in JavaScript that you can declare multiple var statements anywhere in the function. They act like a declaration at the top of the function and give the variable declared by var an initial value of undefined. This behavior is called preparsing (hoisting).

So, before executing the above code, Javascript preparses all var variables (a,b,c) (hoisting). When executing a||null, a is undefined, and because it is ||, the result is null.

c||null is the same thing.

Now, why is typeof f undefined? f is undefined. Shouldn't it report errors?

Yes, if we use an undefined variable, the browser will report an error.

However, when using typeof to determine an undefined variable, undefined is returned.

So what's the mechanism when typeof determines the value type? To sum up:

1. For numeric values, typeof returns number. Note that NaN is also a numeric value because it represents a special non-numeric value in JavaScript.

2. typeof returns string for string type values.

3. typeof returns boolean for Boolean values.

4. For objects, arrays, null, typeof returns object

5. For function types, typeof returns function

6. undefined will be returned if the operand is not defined (non-existent or unassigned).


Related articles: