In JavaScript, null
is a primitive value that represents the intentional absence of any object value. It is often used to indicate that a variable should hold an object but currently does not.
Key Points about null
in JavaScript:
- Type
typeof null; // "object"
- This is a well-known quirk in JavaScript. Although
null
is a primitive,typeof null
returns"object"
. This is due to a bug in the original version of JavaScript and is kept for compatibility.
- Assignment
let user = null;
- This indicates that
user
is intentionally set to have no value, perhaps until a valid object is assigned later.
- Comparison with undefined
null == undefined; // true
null === undefined; // false
-
==
does type coercion, so it considers them equal. -
===
is strict comparison, so they are not equal because their types differ (null
is object,undefined
is undefined).
- Use Cases
- Resetting a variable
- Representing missing data
- Checking the result of DOM operations (e.g.,
document.getElementById("nonexistent")
returnsnull
)
In JavaScript, undefined
is a primitive value that means a variable has been declared but not yet assigned a value.
🔹 What is undefined
?
undefined
is automatically assigned to variables that have been declared but not initialized.
let x;
console.log(x); // undefined
It also appears in other situations when a value is missing or not provided.
🔸 Common Cases When undefined
Appears
1. Uninitialized Variables
let name;
console.log(name); // undefined
2. Missing Function Return
If a function does not explicitly return a value:
function sayHi() {
console.log("Hi!");
}
let result = sayHi(); // Logs "Hi!"
console.log(result); // undefined
3. Missing Function Arguments
function greet(name) {
console.log("Hello, " + name);
}
greet(); // Hello, undefined
🔷 Template Literals in JavaScript (ES6)
Template literals (also called template strings) are a cleaner, more powerful way to create strings in JavaScript. They were introduced in ES6 (ECMAScript 2015) and are enclosed by backticks (`
) instead of single ('
) or double ("
) quotes.
✅ Key Features of Template Literals
1. Multi-line Strings
const poem = `Roses are red,
Violets are blue,
JavaScript is awesome,
And so are you.`;
console.log(poem);
No need for \n
or string concatenation.
2. String Interpolation (Variable/Expression Insertion)
Use ${}
to insert variables or expressions directly inside the string.
const name = "Alice";
const age = 25;
const greeting = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(greeting);
You can even put expressions inside:
const a = 5;
const b = 10;
console.log(`The sum of ${a} and ${b} is ${a + b}.`);
3. Function Calls Inside ${}
function getTime() {
return new Date().toLocaleTimeString();
}
console.log(`The current time is: ${getTime()}`);
Top comments (0)