DEV Community

P Mukila
P Mukila

Posted on

I Learned Today-Understanding null and undefined in JavaScript,Template Literals.

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.
Enter fullscreen mode Exit fullscreen mode
let x;
console.log(x); // undefined

function greet() {}
console.log(greet()); // undefined

const person = { name: "Alice" };
console.log(person.age); // undefined
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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
}

Enter fullscreen mode Exit fullscreen mode

Or check both explicitly:

if (value === null || value === undefined) {
  // handle missing value
}
Enter fullscreen mode Exit fullscreen mode

What Are Template Literals?

Template literals are strings enclosed by backticks (`), not quotes (' or "). They allow:

String interpolation (inserting variables).

Multiline strings.

Embedded expressions.
Enter fullscreen mode Exit fullscreen mode

Syntax


const name = "Alice";
const greeting =
Hello, ${name}!`;
console.log(greeting); // Hello, Alice!

`

Examples of Use

1.String Interpolation

Insert variables or expressions directly in the string using ${}:


const a = 5;
const b = 10;
console.log(
The sum of ${a} and ${b} is ${a + b}.);
// 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


function getName() {
return "Charlie";
}
const msg =
Hello, ${getName()}!`;
console.log(msg); // Hello, Charlie!

`

Top comments (0)