当前位置:网站首页>The difference between initializing objects as null and empty objects in JS
The difference between initializing objects as null and empty objects in JS
2022-08-10 06:32:00 【代码魔鬼】
In JavaScript, object types are complex data types, also known as reference data types.When we declare an object, we can assign some basic data to the object,
const person = {name: 'liudehua',age: 23}But sometimes we declare an object and don't want to assign a value to the object, so there are two ways to initialize the object.
// Method 1, directly give an empty objectconst person = {};// Method 2, assign the object to nullconst person1 = nullBut there are some differences between the two methods:
- When converting to a boolean value, an empty object will be converted to true, and null will be converted to false. When we directly use the object variable name to make some judgments, we need to pay attention:
// Method 1, directly give an empty objectconst person = {};// Method 2, assign the object to nullconst person1 = nullif(person) {console.log("will execute");}if(person1) {console.log("will not execute");} - Understanding at the memory level, when it is declared as an empty object, it will still open up a memory space in the heap memory. When it is declared as null, the reference will point to a 0x0 memory location, not in the heap memory.Create a memory space.
- But when we use the typeof operator to operate on empty objects and values of type null, the return values are all of type object
// Method 1, directly give a nullobjectconst person = {};// Method 2, assign the object to nullconst person1 = nullconsole.log(typeof person); // objectconsole.log(typeof person1); // object
Summary: When declaring an object, if you don't need to assign a specific value, but only need to initialize it, it is recommended to assign it to null.
边栏推荐
猜你喜欢
随机推荐
npm搭建私服,上传下载包
强化学习_06_DataWhale深度Q网络
Ingress Controller performance test(1)
Myunity框架笔记3
OSPF的dr和bdr
新手使用 go channel 需要注意的问题
Analysis of minix_super_block.s_nzones of mkfs.minix.c
全网可达并设备加密
H3C文档NAT专题
UnityShader入门精要-透明效果
Why do games need hot updates
NetKeeper(创翼)开WIFI方法——2018.5
MySQL笔记
pthread编程重要知识点
webSocket教程
socket实现进程间通信
什么是MQTT网关?与传统DTU有哪些区别?
OpenGL学习笔记(LearnOpenGL)-第五部分 纹理
COLMAP+OpenMVS实现物体三维重建mesh模型
ArgumentException: GetComponent requires that the requested component ‘GameObject‘ derives from Mono









