JavaScript Primitives: Null, Undefined, Symbol, Boolean, and BigInt
JavaScript primitives are the most basic data types in the language. They are immutable and have no methods. In this guide, we'll cover the remaining primitives that haven't been discussed yet: null
, undefined
, symbol
, boolean
, and bigint
.
Concept and Use Cases
Null
Definition:
null
represents the intentional absence of any object value. It is often used to signify that a variable should have no value.
Common Use Cases:
- Representing a deliberate non-value or an empty object reference.
- Initializing variables that will hold objects.
Example:
let emptyObject = null;
console.log(emptyObject); // Output: null
Undefined
Definition:
undefined
indicates that a variable has been declared but not yet assigned a value. It is the default value for uninitialized variables.
Common Use Cases:
- Checking if a variable has been initialized.
- Handling optional function parameters.
Example:
let uninitialized;
console.log(uninitialized); // Output: undefined
function greet(name) {
if (name === undefined) {
console.log("Hello, stranger!");
} else {
console.log(`Hello, ${name}!`);
}
}
greet(); // Output: Hello, stranger!
Symbol
Definition:
Symbol
is a unique and immutable primitive value used to create unique identifiers for object properties. Symbols are guaranteed to be unique.
Common Use Cases:
- Creating unique property keys for objects to avoid property name collisions.
- Defining constants representing unique values.
Example:
let symbol1 = Symbol('description');
let symbol2 = Symbol('description');
console.log(symbol1 === symbol2); // Output: false
let obj = {
[symbol1]: 'value1',
[symbol2]: 'value2'
};
console.log(obj[symbol1]); // Output: value1
console.log(obj[symbol2]); // Output: value2
Boolean
Definition:
Boolean
represents a logical entity and can have two values: true
and false
.
Common Use Cases:
- Controlling flow in conditional statements.
- Representing binary states (e.g., on/off, yes/no).
Example:
let isLoggedIn = true;
if (isLoggedIn) {
console.log('User is logged in.');
} else {
console.log('User is not logged in.');
}
let hasAccess = false;
if (hasAccess) {
console.log('Access granted.');
} else {
console.log('Access denied.');
}
BigInt
Definition:
BigInt
is a primitive data type that can represent integers with arbitrary precision. It is used when integer values exceed the safe integer limit for the Number
type (2^53 - 1
).
Common Use Cases:
- Performing mathematical operations on large integers.
- Handling high-precision arithmetic.
Example:
let bigInt1 = BigInt(9007199254740991);
let bigInt2 = BigInt('9007199254740992');
let bigInt3 = 9007199254740993n; // Using the 'n' suffix
console.log(bigInt1 + bigInt2); // Output: 18014398509481983n
console.log(bigInt3 * 2n); // Output: 18014398509481986n
Practical Tips and Tricks
-
Distinguishing Between Null and Undefined: Use
null
to represent the intentional absence of a value andundefined
for uninitialized variables.Example:
let user = null; // No user data available let score; // Variable declared but not initialized
-
Using Symbols for Unique Object Keys: Use
Symbol
to create unique property keys in objects, avoiding name collisions.Example:
let obj = {}; let uniqueKey = Symbol('unique'); obj[uniqueKey] = 'value';
-
Boolean Type Coercion: JavaScript will coerce values to
true
orfalse
in boolean contexts. Be cautious with falsy values (0
,''
,null
,undefined
,NaN
, andfalse
). Example:if ('') { console.log('This will not execute'); } if (0) { console.log('This will not execute'); }
-
Handling BigInt Arithmetic: Be aware that
BigInt
cannot be mixed withNumber
types in operations directly.Example:
let bigInt = 1234567890123456789012345678901234567890n; let num = 10; // console.log(bigInt + num); // TypeError: Cannot mix BigInt and other types console.log(bigInt + BigInt(num)); // Output: 1234567890123456789012345678901234567900n
Common Gotchas
-
Comparing Null and Undefined:
null
andundefined
are equal using loose equality (==
) but not strict equality (===
).Example:
console.log(null == undefined); // Output: true console.log(null === undefined); // Output: false
-
Boolean Type Coercion Pitfalls: Be cautious with automatic type coercion to
boolean
in conditions.Example:
let obj = {}; if (obj.nonExistentProperty) { console.log('This will not execute'); }
-
Using Symbols in JSON: Symbols are not included in JSON.stringify() output.
Example:
let obj = { [Symbol('key')]: 'value' }; console.log(JSON.stringify(obj)); // Output: {}
-
Operations with BigInt: Operations with
BigInt
must be handled carefully to avoid mixing types.Example:
let bigInt = 123n; let num = 10; // console.log(bigInt + num); // TypeError console.log(bigInt + BigInt(num)); // Correct usage
Advanced Topics
Symbol.for() and Symbol.keyFor()
Example:
let globalSymbol1 = Symbol.for('global');
let globalSymbol2 = Symbol.for('global');
console.log(globalSymbol1 === globalSymbol2); // Output: true
let symbolKey = Symbol.keyFor(globalSymbol1);
console.log(symbolKey); // Output: 'global'
Using BigInt for Large Number Calculations
Example:
function factorial(n) {
if (n === 0n || n === 1n) return 1n;
return n * factorial(n - 1n);
}
console.log(factorial(20n)); // Output: 2432902008176640000n
console.log(factorial(100n)); // Output: 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000n
Interview Tips and Tricks
-
Know When to Use Null and Undefined: Use
null
for intentional absence of a value andundefined
for uninitialized variables.Example:
let user = null; let score;
-
Understand Symbol Use Cases: Use
Symbol
to create unique and non-colliding property keys.Example:
let uniqueId = Symbol('id');
-
Boolean Logic: Understand truthy and falsy values in JavaScript.
Example:
if (null) console.log('false'); if ('') console.log('false');
-
BigInt Precision: Use
BigInt
for high-precision integer arithmetic beyondNumber.MAX_SAFE_INTEGER
.Example:
let bigNumber = 1234567890123456789012345678901234567890n;
Common Mistakes
-
Mixing Null and Undefined: Understand the difference between
null
andundefined
and use them appropriately.Example:
let value = null; // Intentional absence let uninitialized; // Variable not assigned
-
Incorrect Boolean Comparisons: Be cautious with comparisons involving
null
andundefined
.Example:
let value = null; if (value == undefined) { console.log('Value is null or undefined'); }
-
Symbol Usage: Remember that symbols are not included in JSON serialization.
Example:
let obj = { [Symbol('key')]: 'value' }; console.log(JSON.stringify(obj)); // Output: {}
-
Mixing BigInt with Number: Avoid mixing
BigInt
andNumber
types directly in operations.Example:
let bigInt = 123n; let num = 10; // console.log(bigInt + num); // TypeError console.log(bigInt + BigInt(num)); // Correct usage
By mastering these JavaScript primitives and understanding their intricacies, you will be well-equipped to handle a variety of interview questions and real-world problems. Regular practice and a solid grasp of advanced topics will deepen your understanding and improve your problem-solving skills.
Practice Problems
Find the length of the last word in a given string, ignoring any trailing whitespace and handling cases where the string ends with whitespace or has only whitespace characters.
Loading...
Write a function to determine if all characters in a given string are capital or not, and return true if they are entirely uppercase or false otherwise.
Loading...
Given a target string and an input string, find the starting index of the first occurrence of the target string within the input string.
Loading...
Let's continue exploring the next page. Take your time, and proceed when you're ready.