1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
1console.log("hello-world);
console.log("hello-world);
.container {
width: 80%;
}
<pre><code class="language-css">
.container {
width: 80%;
}
</code></pre>
Welcome to the JavaScript circus 🎪 where NULL, Undefined, and NaN do their high-wire act, and we teach them to land safely on 0! In this fun-filled guide, we juggle through JavaScript basics, toss around various conversion techniques, and throw in some common pitfalls (with safety nets, of course). Perfect for coding clowns and serious developers alike, this is your ticket to the show where JavaScript's quirks become your tricks! 🎪💻🤹Lets dive in! 👨💻
Before we start converting Null/Undefined/NaN to Zero in JavaScript, lets refresh few concepts. Data Types: JavaScript categorizes values into types, which define their characteristics and behaviors. The basic types include:
"Hello, world!"
.42
, 3.14
.true
, false
.{name: "Alice", age: 30}
.[1, 2, 3]
.console.log(typeof "Hello, world!"); // Outputs: string
console.log(typeof 42); // Outputs: number
console.log(typeof true); // Outputs: boolean
Understanding Falsy Values: Falsy values are values that are considered false when encountered in a Boolean context. These include:
false
0
(zero)""
(empty string)null
undefined
NaN
(Not a Number)if (false || 0 || "" || null || undefined || NaN) {
console.log("This will not print.");
} else {
console.log("Falsy value encountered."); // Outputs: Falsy value encountered.
}
Basic JavaScript Operators: JavaScript operators are symbols used to perform operations on variables and values. Basic operators include:
+
, -
, *
, /
)==
, ===
, !=
, !==
)&&
, ||
, !
)=
, +=
, -=
)let a = 10;
let b = 5;
console.log(a + b); // Outputs: 15 (Addition)
console.log(a === b); // Outputs: false (Strict equality)
console.log(a && b); // Outputs: 5 (Logical AND)
Difference between ==
and ===
: The ==
operator checks for equality after performing type coercion (if types are different). The ===
operator, known as strict equality, checks for equality without type coercion.
console.log(1 == "1"); // Outputs: true (type coercion)
console.log(1 === "1"); // Outputs: false (no type coercion)
Lets see various techniques to convert JavaScript Null or Undefined to Zero. We’ll see from the most straightforward to the most concise implementations.
val
is strictly equal to null
or undefined
. If true, val
is set to 0. This is a clear, explicit way to handle conversion, especially beneficial for beginners to understand how conditional checks work in JavaScript.let val = undefined;
if (val === null || val === undefined) {
val = 0;
}
console.log(val); // Outputs: 0
?
), then the expression to execute if the condition is truthy, followed by a colon (:
), and finally the expression to execute if the condition is falsy.val
is null
or undefined
. If so, val
is set to 0; otherwise, it retains its original value. This one-liner is an efficient way to handle conditional assignments.let val = null;
val = val === null || val === undefined ? 0 : val;
console.log(val); // Outputs: 0
null
, undefined
, 0
, ""
(empty string), NaN
, and false
are considered falsy values. The logical OR (||
) operator returns the first operand if it’s truthy, or the second operand if the first is falsy.val
is null
or undefined
(both falsy), the operator returns 0. This approach is less explicit than the if statement but is a common pattern in JavaScript for setting default values.""
(empty string), 0
, NaN
and false
, also to zero.let val = null;
val = val || 0;
console.log(val); // Outputs: 0
null
or undefined
, and otherwise returns its left-hand side operand.null
or undefined
. It’s more precise than the logical OR, as it doesn’t treat other falsy values (like 0 or ”) as nullish.let val = undefined;
val = val ?? 0;
console.log(val); // Outputs: 0
=
) and the nullish coalescing operator (??
). It assigns the right-hand operand to the variable only if the variable is null
or undefined
.null
or undefined
. It’s a newer addition to JavaScript and enhances code readability and brevity.let val = null;
val ??= 0;
console.log(val); // Outputs: 0
JavaScript treats NaN
uniquely. Like, NaN
is the only value in JavaScript that is not equal to itself. So direct comparison with equality sign is not gonna work for sure.
So, lets learn various reliable ways, to identify and convert NaN
to a more manageable form (like 0).
Number.isNaN()
is a method to check if a value is NaN
(Not a Number). This is important because NaN
is a unique type in JavaScript; it is the only value that is not equal to itself (i.e., NaN === NaN
is false).
Using Number.isNaN()
in a conditional statement or ternary operator is a clear and reliable way to check for NaN
.
let val = NaN;
// Using 'if' conditional:
if (Number.isNaN(val)) {
val = 0;
}
console.log(val); // Outputs: 0
// Or using ternary operator
val = Number.isNaN(val) ? 0 : val;
console.log(val); // Outputs: 0
The logical OR operator returns the first truthy value it encounters or the last value if all are falsy. Since NaN
is a falsy value, this operator can be used for conversion.
let val = NaN;
val = val || 0;
console.log(val); // Outputs: 0
The Number
function in JavaScript can convert various data types to a number. When passed null
, undefined
, or NaN
, it returns 0.
Caution: This method also converts other falsy values (like an empty string) to 0, so its use should be context-dependent.
let val = NaN;
val = Number(val);
console.log(val); // Outputs: 0
Creating a custom function allows for more control and specificity in the conversion process. You can define a function that checks for NaN
using Number.isNaN()
and returns 0, or returns the value itself if it’s not NaN
, or do whatever you like.
function convertToZeroIfNaN(value) {
return Number.isNaN(value) ? 0 : value;
}
let val = NaN;
val = convertToZeroIfNaN(val);
console.log(val); // Outputs: 0
When dealing with arrays, the reduce
method can be used to apply a conversion for each element. This is specially useful for aggregating values, such as summing an array while converting NaN
to 0.
let array = [1, NaN, 3];
let sum = array.reduce(
(acc, val) => acc + (Number.isNaN(val) ? 0 : val),
0,
);
console.log(sum); // Outputs: 4 (1 + 0 + 3)
===
checks both value and type, preventing unintended type conversions. This is crucial in JavaScript, where type coercion can lead to unexpected results.
console.log(0 == "0"); // true, due to type coercion
console.log(0 === "0"); // false, no type coercion
NaN
Properly:Since NaN
is the only value in JavaScript that is not equal to itself, use Number.isNaN()
for accurate detection.
let val = 0 / 0; // NaN
console.log(val === NaN); // false, incorrect way to check
console.log(Number.isNaN(val)); // true, correct way to check
It returns the first truthy operand or the last operand if all are falsy. This can be misleading when dealing with values like 0
, ""
, or false
, which are falsy but might be valid in your context.
Falsy with OR (JavaScript)
let count = 0;
console.log(count || 10); // 10, might not be intended
??
only checks for null
or undefined
, making it more precise than ||
for default value assignments.
let name = "";
console.log(name || "Unknown"); // "Unknown", might not be intended
console.log(name ?? "Unknown"); // "", more accurate
Be aware of JavaScript’s automatic type conversion (or coercion) in arithmetic and comparisons (even when involving Null, Undefined, or NaN). Like:
With null
: In arithmetic operations, null
is converted to 0
. However, this implicit conversion might lead to bugs if not intended. For instance, null + 5
results in 5
, which may or may not be the desired outcome.
With undefined
: Any arithmetic operation with undefined
results in NaN
. This is because undefined
is not implicitly converted to a number, unlike null
. For example, undefined + 5
results in NaN
.
With NaN
: Once a value becomes NaN
, it remains NaN
through most operations and can propagate through your calculations. For example, NaN + 5
also results in NaN
.
// Implicit conversion with null
console.log(null + 5); // Outputs: 5 (null is converted to 0)
console.log(null * 3); // Outputs: 0 (null is converted to 0)
// Implicit conversion with undefined
console.log(undefined + 5); // Outputs: NaN (undefined not converted to a number)
console.log(undefined * 3); // Outputs: NaN (undefined not converted to a number)
// Operations involving NaN
console.log(NaN + 5); // Outputs: NaN (NaN propagates through arithmetic operations)
console.log(NaN * 2); // Outputs: NaN (NaN propagates through arithmetic operations)
// Using 'null' and 'undefined' in string concatenation
console.log("Value is " + null); // Outputs: "Value is null" (null is converted to "null")
console.log("Value is " + undefined); // Outputs: "Value is undefined" (undefined is converted to "undefined")
// Conversion using Logical OR (||) Operator
console.log(null || 0); // Outputs: 0 (null is falsy, so 0 is returned)
console.log(undefined || 0); // Outputs: 0 (undefined is falsy, so 0 is returned)
console.log(NaN || 0); // Outputs: 0 (NaN is falsy, so 0 is returned)
In the spirit of Test Driven Learning ( 😁), lets test our understanding by solving a problem.
You’re tasked with creating a function for a playful wizard who loves the number 3. This function should take an array of numbers and replace any occurrence of
null
,undefined
, orNaN
with the number 3.
Problem (JavaScript)
function magicNumberReplacer(numbersArray) {
// > > > 👉 Write code here 👈 < < <
}
console.log(magicNumberReplacer([1, null, 2, NaN, 3]));
// Outputs: [1, 3, 2, 3, 3]
console.log(magicNumberReplacer([undefined, 4, NaN]));
// Outputs: [3, 4, 3]
console.log(magicNumberReplacer([5, 6]));
// Outputs: [5, 6]
Please attempt before seeing the Answer:
function magicNumberReplacer(numbersArray) {
return numbersArray.map((val) =>
val === null || val === undefined || Number.isNaN(val)
? 3
: val,
);
}
Explanation: The function magicNumberReplacer
takes an array of numbers and uses the map
method to transform it. It checks each element: if the element is null
, undefined
, or NaN
, it replaces it with the number 3. Otherwise, it keeps the original number.
Now you are an expert in handling NaN, Null or Undefined in JavaScript.
Keep learning, keep experimenting and keep coding! 🚀👨💻
Feel free to reach out!