What is the difference between null and undefined in JavaScript?

In JavaScript, null and undefined are both used to represent the absence of a value, but they have slightly different meanings.

Undefined is a value automatically assigned to a variable that has been declared but has not been initialized with a value, or to a function parameter that has not been passed a value. For example:

let x;
console.log(x); // Output: undefined

function test(y) {
    console.log(y);
}
test(); // Output: undefined

In this example, we declare a variable "x" without initializing it and then log its value to the console, which is "undefined". We also define a function "test" with a parameter "y" but do not pass any value to it when calling the function, which also logs "undefined" to the console.

Null, on the other hand, is a value that represents the intentional absence of any object value. It is often used to indicate that a variable should have no value or that an object property should be set to null to indicate that it has no value. For example:

let y = null;
console.log(y); // Output: null

let person = {name: "John", age: 30};
person.age = null; // intentionally setting the age property to null
console.log(person.age); // Output: null

In this example, we declare a variable "y" and initialize it with the value "null". We also declare an object "person" with two properties, "name" and "age", and then intentionally set the "age" property to null to indicate that it has no value.

In summary, undefined is automatically assigned to a variable that has not been initialized or to a function parameter that has not been passed a value, while null is a value that represents the intentional absence of any object value.