当前位置:网站首页>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.
边栏推荐
猜你喜欢
随机推荐
unityFps射击
Log4j2基本使用
复现dns外带数据结合sqlmap
CuteOneP 一款php的OneDrive多网盘挂载程序 带会员 同步等功能
Win32屏幕坐标转换Qt坐标
指纹浏览器在使用易路代理时常见的问题及解决办法
各位大佬 oracle cdc 默认配置 偶发会30秒才抓取到数据 这个怎么优化啊
排序二叉树代码
UnityShader入门精要-阴影
Myunity框架笔记2
3.事务篇【mysql高级】
Qt滚动条(QScrollBar)圆角样式问题跟踪
XV6系统调用实现
Make a boot floppy and boot with bochs emulator
求问各位大佬,FLink SQL读取source的时候去指定水位线的时间字段,如果指定的这个字段中格
Myunity框架笔记
关于Qt高频率信号槽合并的误解和方案
Qt使用私有接口绘制窗口阴影
Qt信号槽与事件循环的关系
语法基础(判断语句)









