About the use of null when defining objects

recently read in js books that when defining variables that will be used to store objects, it is recommended to pay an initial value null, to indicate an empty object, which is not a big problem, but in practical business applications, it is often required to take an attribute of the object to do the assignment operation (such as data processing after a successful network request):

let obj = null,
    peopleName = "";
peopleName = obj.name;

A syntax error: Cannot read property "name" of null
is reported, but this will not happen if the initial value of obj is assigned to {}.
so isn"t it impractical to assign initial values to null?

Mar.19,2021

The point of

null is precisely that an error is thrown here, rather than quietly swallowing it like an empty object and returning undefined .

< hr >

null is used to mark "does not exist" or "uninitialized". Trying to read a value from a non-existent or uninitialized variable is itself a programming error. Specific to the scenario of the subject (data processing after a successful network request):

  1. if the network request is successful, obj should not be null , but should have data;
  2. if the network request fails, obj is still null , and then peopleName = obj.name itself is bug.

if you continue to force rendering to the page, present the user with a "Welcome, undefined!" It's actually very embarrassing. Therefore, it is better to throw it directly. During the test, it is easy to find bug, and add a sentence if (obj) . Even if it is not found, it will stop in the login interface.


because obj= {} is not a completely empty object, it has an object inherited from the prototype chain, while null is a real empty object, there is nothing, so save memory space. Let's analyze the specific environment

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3d37c-34742.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3d37c-34742.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?