Why JavaScript use “use strict” directive in programming?

Asked 19-Jul-2021
Viewed 235 times

1 Answer


0

'use strict' it is a literal expression. this expression is not present in earlier version javascript. Main purpose of this expression, you can't access variable, function, objects without declare.

Why are use 'use strict'

Strict Mode Makes It Easier to Write safe Code in JavaScript. we can find error very quickly. The variable will not be rewritten from it.

Syntax
<script>    
'use strict'; // mandatory
statement
</script>
'use strict';

x = 3.14; // This will cause an error because x is not declared
'use strict';

myFunction();
function myFunction() {
  y = 3.14; // This will also cause an error because y is not declared
}
x = 3.14;       // This will not cause an error.

myFunction();
function myFunction() {
  'use strict';
  y = 3.14; // This will cause an error
}

Example 

<!DOCTYPE html>

<html>
<body>
<h2>With 'use strict':</h2>
<script>
'use strict';
function x(p1, p1) {
} // This will cause an error
</script>
</body>
</html>

Why JavaScript use “use strict” directive in programming?