简体   繁体   English

在JavaScript中使用“null”初始化变量是一个好习惯

[英]Is it a good practice to initialize a variable with “null” in JavaScript

Which one makes more sense 哪一个更有意义

var myVar = null;

myVar = someLogic(); //someLogic() might return a primitive or an object

if(myVar){
  //other logic
}

OR 要么

var myVar;

myVar = someLogic(); //someLogic() might return a primitive or an object

if(myVar){
  //other logic
}

In JavaScript, there is generally no good reason to initialize variables to null . 在JavaScript中,通常没有充分的理由将变量初始化为null

In languages like C, variables should always be initialized before use because there is no guarantee as to the value of an uninitialized variable – it could be 0, 1, 2, or 283942, or anything. 在像C这样的语言中,变量应该在使用前始终初始化,因为无法保证未初始化变量的值 - 它可以是0,1,2或283942,或任何东西。 However, JavaScript has no such problem. 但是,JavaScript没有这样的问题。 In JavaScript, variables that have been declared but not initialized will always have the value undefined . 在JavaScript中,已声明但未初始化的变量将始终具有undefined的值。

undefined is it's own type in JavaScript. undefined是JavaScript中自己的类型。 When cast to a boolean, it becomes false . 当转换为布尔值时,它变为false

undefined == null returns true , but undefined === null returns false . undefined == null返回true ,但undefined === null返回false

Semantically, undefined means that a value has not been set, whereas null means that there is no value, but we might expect one. 从语义上讲, undefined意味着没有设置一个值,而null意味着没有值,但我们可能会期望一个。 However, there is no hard rule for this, as you can always assign the value undefined to a variable manually – I wouldn't recommend this. 但是,对此没有硬性规则,因为您始终可以手动将值undefined分配给变量 - 我不建议这样做。

In general, setting uninitialized variables to null would be a waste of time. 通常,将未初始化的变量设置为null将浪费时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM