search
HomeWeb Front-endJS TutorialSeven value types and typeof operator in JavaScript

Seven value types and typeof operator in JavaScript

Feb 28, 2017 pm 02:34 PM
javascripttypeofoperator

I plan to review JavaScript from the basics,

By the way, I will share and summarize the knowledge I have learned


Built-in types

There are seven types in JavaScript Built-in types, including six basic types and one reference type

  • Basic types

    • number (number)

    • string (string)

    • boolean (boolean)

    • undefined (undefined)

    • null (null value)

    • symbol (symbol) [New to ES6 specification]

  • Reference type

    • object (object)

Note: array array and function function are special objects, also That is to say, they are "subtypes" of objects and are also reference values.

The basic type is a simple data segment stored in the stack memory and has a fixed space in the memory.
The reference type is stored in the heap Objects in memory are accessed by reference. The stack memory stores the pointer to the object (the access address of the object is stored)
The reason why the stack is divided into memory is because it is related to the browser's garbage collection mechanism to ensure operation It occupies the smallest amount of memory
It doesn’t matter if you don’t understand the above, as long as you know thatthe basic type is stack data,the reference type is heap data

typeof Operator

can also be said to be the typeof operator. The operator operator refers to the same thing
Through this typeof we can check the value type
It returns a string of type (lowercase English ), but not all types can be identified

console.log(typeof 123);
// "number"console.log(typeof '123');
// "string"console.log(typeof true);
// "boolean"console.log(typeof undefined);
// "undefined"console.log(typeof Symbol());
// "symbol"console.log(typeof null);
// "object"  <-注意看这里console.log(typeof {demo: 123});
// "object"

We printed these seven types to the console and found a problem
typeof null actually returned "object"
Well, it is not what we expected It's too the same
It was promised to return "null"
In fact, this is a historical issue. This bug has existed for more than 20 years (older than me)
Probably never It has been fixed, because it involves too many Web systems, and the cost of "fixing" it is unimaginable


But we can judge the null value type in this way

var foo = null;if(!foo && typeof foo === &#39;object&#39;){    console.log(&#39;这是一个空值...&#39;);
}

Because no matter what the object is, Even if it is an empty object, it will be true when converted to a Boolean value (I will talk about it later when I write type conversion)
So you can judge null in this way, but I don’t seem to have used it


Back to the issue of typeof Coming up, we also found a problem

console.log(typeof function(){});// "function"

typeof has special treatment for functions, which are first-class citizens in JavaScript - executable objects.
So although functions are objects, the typeof operator can distinguish And return "function"
As for why the function can be called, it is because it has an internal attribute [[call]], so it is a "callable object". We will talk about it later
Oh, by the way, although arrays are also special objects , but typeof doesn’t recognize it
If you want to distinguish arrays, you can take a look at how I wrote how to identify arrays
So the return value of typeof has these strings
number, string, boolean, undefined, object, function, symbol


Now that we are talking about typeof, there is another little knowledge point

console.log(typeof NaN)// "number"

It is also easy to make mistakes, and there may be some in interview questions
But this is not a bug
Not a number NaN in EnglishNot a Number 'Not a number'
That means: a number that is not a number is a number
It doesn't matter if you don't see it
Now just remember that NaN is a number type Okay


Oh, by the way, I’ll add something that suddenly occurred to me
Although typeof can be used like thistypeof(a + b)
But it’s not a function, it’s not a function, it’s not Function (say important things three times)
is a unary operator, remember
The above usage is only a type check for the result of the operand operation in the expression

Value and type

Here I will explain such a problem
In JavaScript, variables do not have types, only values ​​have types
The typeof operator returns a string of the type of value held by the variable
Because we are Weakly typed language
So we can change the type of the value held by the variable

var foo = 123;console.log(typeof foo);
// "number"foo = true;console.log(typeof foo);
// "boolean"foo = &#39;abc&#39;;console.log(typeof foo);
// "string"

Although the variable value type can be changed, we must not do this when writing projects
We can add prefixes to variables or Add special symbols to let us remember what type of variable we are declaring
For example, retArr, bFlag, strLen and the like

typeof undeclared

This undeclared is of course a keyword that does not exist
But why should I write like this?
Let’s look at a question

console.log(foo);

我没定义foo就打印,于是
Seven value types and typeof operator in JavaScript
果不其然,浏览器蒙圈了
给大家翻译成中文:未捕获引用错误: foo没有定义
可能大家都不会去注意,其实这是很容易让人误会的
在这了 is not defined != is undefind
因为我连声明都没声明,怎么谈定义
所以如果浏览器报出is not declared或许更准确
我们暂且把这种连定义都没定义的变量看作“undeclared”变量
但是对于这种“undeclared”未定义的变量,typeof有特殊的安全防范机制

console.log(typeof foo);// "undefined"

出乎意料的,它对于undeclared变量并没有报错,而是返回了“undefined”
虽然我们觉得它返回“undeclared”更容易理解一些(我们的要求太高了)
其实它没有报错就相当不错了
这种容错对于我们来说还是很有帮助的
比如说我们想知道全局空间有没有变量foo

if(foo){  //若不存在会报错
    //...}if(typeof foo !== &#39;undefined&#39;){  //不存在也不会报错
    //...}if(window.foo){  //不存在同样不会报错
    //...}

最后一种通过window对象调用与undeclared变量不同
访问不存在的对象属性是不会报错的,而是返回undefined(是类型而不是字符串)
不过如果我们全局对象不是window的话,就不能使用这种方法了(比如,node.js)

总结

JavaScript内置类型:

  • 基本类型(栈数据):number、string、boolean、undefined、null、object、symbol(ES6规范新增)

  • 引用类型(堆数据):object

typeof操作符返回值:

  • “number”

  • “string”

  • “boolean”

  • “undefined”

  • “object”

  • “function”【sp】

  • “symbol”

typeof null -> “object” 历史遗留bug

typeof NaN -> ‘number’ 注意

变量没有类型,其持有值有类型

typeof的容错机制可以用来检查undeclared(未声明)变量

 以上就是JavaScript中的七种值类型与typeof运算符的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.