Home  >  Article  >  Web Front-end  >  Do you know these knowledge points of TypeOf_javascript skills

Do you know these knowledge points of TypeOf_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:14:331289browse

I played with my colleagues yesterday. They gave me a coding question, which was about typeof. I thought it was quite fun. I would like to share it with you here to consolidate my summary of the knowledge points of typeof. If something is wrong, please point it out and we can make progress together.

The code is 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, if you run this code, what will the chrome debugger print?

Please see the renderings


Why does this result occur?

First analyze the two nulls in the above picture


Because Javascript will pre-parse (hoisting) before executing the code.

What is hoisting?

That is, in JavaScript, you can declare multiple var statements anywhere in a function. They will function as if they were declared at the top of the function and will give the variable declared by var an initial value of undefined. This behavior is called hoisting.

So, before executing the above code, Javascript will first pre-parse (hoisting) all var variables (a, b, c). When a||null is executed, a is undefined, and because it is | | operation, so the result is null.

c||null is a truth.

Let’s take a look again, why typeof f is undefined? If f is not defined, shouldn't an error be reported?

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

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

What is the mechanism used by typeof to determine the value type? The summary is as follows:

1. For numeric type values, typeof will return number. Note: NaN is also a numeric type because it represents a special non-numeric value in JavaScript.

2. For string type values, typeof will return string.

3. For Boolean type values, typeof will return boolean.

4. For objects, arrays, and null, typeof will return object

5. For function types, typeof returns function

6. If the operand is not defined (does not exist or is not assigned a value), undefined will be returned.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn