Trusted answers to developer questions

How to use ' use strict ' in JavaScript?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

widget

Previously, Javascript kept evolving without changing the old functionality. However, in 2009, ECMAScript 5 appeared and that fixed functionality. By default, the EXMAScript 5 is disabled, but if you use the use strict keyword, the modifications will be placed.

Strict mode makes several changes to JavaScript semantics including:

  • Prohibiting some syntax.
  • Fixing errors that previously made it difficult to perform optimizations on JavaScript engines.
  • Eliminating some JS silent errors by throwing exceptions.

The syntax is:

"use script"

//modern implementation of the code

Remember: use script should be at the top of the scripts to enable strict mode.

One key thing to note is that once in strict mode, you can not go back to old mode as no such command exists.

JavaScript classes and modules automatically make use of use script so that there is no need to shift to script mode.

If you assign values to an undeclared variable, it gives an error:

// adding value to an undeclared variable x
x = 300; //no error
print();
function print(){
"use strict";
y = 300; //undeclared- gives error
console.log(y)
}

Similarly, deleting a variable or a function also gives an error:

var x = 300;
print();
function print(){
"use strict";
y = 300; //undeclared- gives error
console.log(y)
}
//delete x //gives error
delete print //gives error

JS does not allow octal numeric literals, octal escape characters, or writing to a read-only property.

RELATED TAGS

javascript
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?