JavaScript Interview Questions

23 Questions
JavaScript

JavaScript

Web DevelopmentFrontendBackend

Question 1

What does immutability mean in JavaScript?

Answer:

Immutability in JavaScript refers to objects whose state cannot be modified after they are created. Immutable objects help prevent unexpected side effects and make it easier to manage application state. This concept is essential in functional programming and helps in building predictable and maintainable applications. Primitive data types like strings and numbers are inherently immutable.

Here is an example demonstrating immutability:

// Immutable primitive values
let name = 'John';
let newName = name.toUpperCase();
console.log(name); // 'John'
console.log(newName); // 'JOHN'

// Object immutability using Object.freeze
let person = { name: 'John', age: 30 };
Object.freeze(person);
person.age = 31; // This will not change the age property
console.log(person.age); // 30

// Immutable array using spread operator
let numbers = [1, 2, 3];
let newNumbers = [...numbers, 4];
console.log(numbers); // [1, 2, 3]
console.log(newNumbers); // [1, 2, 3, 4]

In this example, we demonstrate immutability with primitive values, object immutability using Object.freeze, and creating an immutable array using the spread operator.

Recent job openings