Differentiate between immutable and mutable data types

Immutable data types are those whose values cannot be changed once they are created. Any operation on an immutable data type will create a new value rather than modifying the existing one. Examples of immutable data types in JavaScript include numbers, strings, and booleans.

Mutable data types, on the other hand, are those whose values can be changed after they are created. Operations on mutable data types directly modify the existing value. Examples of mutable data types in JavaScript include arrays and objects.

Here is a concise and structured answer differentiating between immutable and mutable data types using JavaScript:

<!DOCTYPE html>
<html>
<body>
<h2>Immutable vs Mutable Data Types</h2>
<script>
// Immutable data types
let number = 5; // Number
let string = "Hello"; // String
let boolean = true; // Boolean
// Attempting to modify immutable data types
number = 10; // Creates a new value, does not modify the original
string = "World"; // Creates a new value, does not modify the original
boolean = false; // Creates a new value, does not modify the original
console.log(number); // Output: 10
console.log(string); // Output: "World"
console.log(boolean); // Output: false
// Mutable data types
let array = [1, 2, 3]; // Array
let object = { name: "John", age: 25 }; // Object
// Modifying mutable data types
array.push(4); // Modifies the original array
object.age = 26; // Modifies the original object
console.log(array); // Output: [1, 2, 3, 4]
console.log(object); // Output: { name: "John", age: 26 }
</script>
</body>
</html>

In the above example, we demonstrate the difference between immutable and mutable data types. We first declare variables for each data type and then attempt to modify them. For immutable data types, assigning a new value creates a new value without modifying the original. However, for mutable data types, we can directly modify the original value.