Strict Mode - JavaScript Interview Questions
JavaScript Fundamentals: Strict Mode
What is Strict Mode?
View Answer:
"use strict";
// Example 1: Variable without declaration (throws an error in strict mode)
x = 10; // Throws a ReferenceError: x is not defined
// Example 2: Duplicate parameter names (throws an error in strict mode)
function multiply(a, b, a) { // Throws a SyntaxError: Duplicate parameter name not allowed in this context
return a * b;
}
// Example 3: Octal literals (throws an error in strict mode)
var num = 0123; // Throws a SyntaxError: Octal literals are not allowed in strict mode
// Example 4: 'this' in non-method functions (has different behavior in strict mode)
function myFunction() {
console.log(this); // In strict mode, 'this' is undefined
}
myFunction();
When was ECMAScript 5 (ES5) released for use?
View Answer:
How do you explicitly enable ES5 features and modifications?
View Answer:
"use strict";
// this code works the modern way
...
How you should implement strict mode in JavaScript?
View Answer:
Proper Usage:
- Strict mode in the whole script:
"use strict";
var x = 3.14; // This is okay
x = 3.14; // This is not okay without var, let or const
In this example, the "use strict";
declaration is at the top of the script, enabling strict mode for the entire script. When strict mode is enabled, JavaScript doesn't allow variables to be used unless they're declared with var
, let
, or const
.
- Strict mode in a function:
function strictFunc() {
"use strict";
var x = 3.14; // This is okay
y = 3.14; // This is not okay without var, let or const
}
In this example, strict mode is enabled only within strictFunc
. The "use strict";
statement is at the top of the function, so strict mode applies to the entire function scope. Any variables not declared with var
, let
, or const
will result in an error.
Incorrect Usage:
- Not placing the
"use strict";
directive at the top:
var x = 3.14;
"use strict";
In this example, the "use strict";
statement is not at the top of the script, so strict mode isn't activated. The "use strict";
statement must be at the top of the script or function for strict mode to be enabled.
- Using strict mode with non-compliant syntax:
"use strict";
x = 0177; // Octal literals are not allowed in strict mode
In this example, an octal literal (a number prefixed with a zero) is used, which is not allowed in strict mode. This will throw an error.
Can you cancel strict mode later in your code?
View Answer:
Does the browser developer console implement strict mode by default?
View Answer:
How do you implement strict mode in the browser console?
View Answer:
'use strict';
// <Shift+Enter for a newline>
// ...your code
// <Enter to run>
(function () {
'use strict';
// ...your code here...
})();