当前位置:网站首页>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.
边栏推荐
- 3.事务篇【mysql高级】
- How is C# hot update better than Lua?
- Talking about the realization idea of "frame" of "frame synchronization online game"
- Share a professional TA's "Shader Reference"
- Parallax Mapping: More Realistic Texture Detail Representation (Part 1): Why Use Parallax Mapping
- Unity2d自动寻路(AI插件)
- UnityShader入门精要-纹理动画、顶点动画
- UnityShader入门精要-基础纹理
- 强化学习_12_Datawhale深度确定性策略梯度
- 全网可达并设备加密
猜你喜欢
随机推荐
DRM Memory Management
关于研究鼠标绘制平滑曲线的阶段总结
Qt滚动条(QScrollBar)圆角样式问题跟踪
CuteOneP 一款php的OneDrive多网盘挂载程序 带会员 同步等功能
强化学习_07_DataWhale深度Q网络进阶技巧
直接跳转与间接跳转
Kernel performance analysis summary
驱动的参数传入:module_param,module_param_array,module_param_cb
Two-dimensional cartoon rendering of strokes
qemu和主机共享磁盘
什么是MQTT网关?与传统DTU有哪些区别?
CAP介绍
2022河南萌新联赛第(五)场:信息工程大学 F - 分割草坪
Unity2D动画生成操作(简单)
VS Code插件国际化
ACPI知识(高级配置和电源接口)
高质量WordPress下载站模板5play主题
C语言文件操作
结构体初阶
COLMAP+OpenMVS实现物体三维重建mesh模型