How to use ' use strict ' in JavaScript?

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.

Copyright ©2024 Educative, Inc. All rights reserved