Search⌘ K

Solution Review: "strict" Mode

Explore how JavaScript strict mode changes error handling and the behavior of the this keyword in functions. Understand why strict mode throws errors on illegal property modifications and how it affects function calls, helping you prepare for interview questions on this topic.

Question 1: Solution review #

In the previous lesson, you were given the following code:

Javascript (babel-node)
"use strict"
var obj1 = {};
Object.defineProperty(obj1, 'x', { value: 42, writable: false });
obj1.x = 9;

For the code above, you had to answer the following question.

Explanation #

Let’s run the code to see what happens.

Node.js
"use strict"
var obj1 = {};
Object.defineProperty(obj1, 'x', { value: 42, writable: false });
obj1.x = 9;

As you can see, an error is thrown when the code is run; this means Option A is correct. Why do you see an error?

The answer might seem obvious; since, on line 3, when we define the property x, we set its writable property to false; this means it is a read-only property.

On ...