JavaScript has two special values to represent "no value": null and undefined. They might look similar, but they have different meanings and uses. Let's break them down.
What is undefined?
In JavaScript, a variable is undefined when:
It has been declared but not assigned a value.
A function does not return anything.
You're accessing a non-existent object property.
let x;
console.log(x); // undefined
function greet() {}
console.log(greet()); // undefined
const person = { name: "Alice" };
console.log(person.age); // undefined
So, undefined is the default state of variables or values that are missing.
What is null?
null is an intentional absence of any value. It's a value that you assign to a variable to show that it's empty on purpose.
let user = null;
console.log(user); // null
Use null when you want to clear a variable or explicitly say "this should be empty."
Checking null and undefined
Use strict comparison (===) to distinguish them:
let a;
let b = null;
console.log(a === undefined); // true
console.log(b === null); // true
console.log(a == b); // true (loose comparison)
console.log(a === b); // false (strict comparison)
Avoid using == because it can lead to unexpected results when comparing null and undefined.
Best Practices
- Use undefined for missing values (automatically happens).
- Use null when you want to intentionally reset or empty a value.
- Always prefer === over == for clarity and safety.
- Bonus: How to Check if a Variable is null or undefined
if (value == null) {
// true if value is either null or undefined
}
Or check both explicitly:
if (value === null || value === undefined) {
// handle missing value
}
What Are Template Literals?
Template literals are strings enclosed by backticks (`), not quotes (' or "). They allow:
String interpolation (inserting variables).
Multiline strings.
Embedded expressions.
Syntax
Hello, ${name}!`;
const name = "Alice";
const greeting =
console.log(greeting); // Hello, Alice!
`
Examples of Use
1.String Interpolation
Insert variables or expressions directly in the string using ${}:
The sum of ${a} and ${b} is ${a + b}.
const a = 5;
const b = 10;
console.log();
// Output: The sum of 5 and 10 is 15.
2.Multiline Strings
No need for \n or +:
const message =
This is line 1
This is line 2
This is line 3
;
console.log(message);
3.Function Calls or Calculations Inside
Hello, ${getName()}!`;
function getName() {
return "Charlie";
}
const msg =
console.log(msg); // Hello, Charlie!
`
Top comments (0)