当前位置:网站首页>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 = null
But 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.
边栏推荐
猜你喜欢
随机推荐
UnityShader入门精要-立方体纹理、反射、折射、菲涅尔反射
unity在UI界面上展示旋转模型
XV6系统调用实现
order by注入与limit注入,以及宽字节注入
虚幻5简单第三人称游戏制作文档
手把手教你改内核源码--sysfs虚拟文件系统2
UnityShader入门精要-unity shader基础
Make a boot floppy and boot with bochs emulator
Qt程序字体初始化引起的白屏问题
vsnprint和snprintf的区别
OpenGL学习笔记(LearnOpenGL)-第五部分 纹理
Qt使用私有接口绘制窗口阴影
ACPI知识(高级配置和电源接口)
Qt中输入框在Win10上“Win+/“快捷键的一个Bug
BUUCTF笔记(web)
关于研究鼠标绘制平滑曲线的阶段总结
动态代理-cglib
交换机的功能和ipv4
elf文件与链接脚本
Win32屏幕坐标转换Qt坐标