The "use strict" directive is new in JavaScript ECMAScript version 5 that Defines JavaScript code must be executed in "strict mode". This strict context prevents certain actions from being taken and throws more exceptions.
Strict mode makes it easier to write "secure" JavaScript.
strict mode can be applied in javascript page or in particular functions.
"use strict"; must use at the beginning of a script or a function.
if you use strict mode, you must define a variable by using var keyword.
Ex : demo1.html (without using strict mode)
demo2.html (with using strict mode)
from this demo your code will generate error and execution will stop because before a, b and c variable var keyword required in strict mode.
Deleting a variable is not allowed in strict mode.
You also can not use the variable name from the following list in strict mode.
public
private
protected
static
package
implements
interface
yield
let
Strict mode makes it easier to write "secure" JavaScript.
strict mode can be applied in javascript page or in particular functions.
"use strict"; must use at the beginning of a script or a function.
if you use strict mode, you must define a variable by using var keyword.
Ex : demo1.html (without using strict mode)
<html>
<body>
<h2>Without using strict mode</h2>
<script>
function sum() {
a = 20;
b = 15;
c = a+b;
alert(c);
}
sum();
</script>
</body>
</html>
from this demo, your code will execute and run successfully without any error because there is no need to use var keyword before a, b and c variable.<body>
<h2>Without using strict mode</h2>
<script>
function sum() {
a = 20;
b = 15;
c = a+b;
alert(c);
}
sum();
</script>
</body>
</html>
demo2.html (with using strict mode)
<html>
<body>
<h2>With using strict mode</h2>
<script>
"use strict";
function sum() {
a = 20;
b = 15;
c = a+b;
alert(c);
}
sum();
</script>
</body>
</html>
<body>
<h2>With using strict mode</h2>
<script>
"use strict";
function sum() {
a = 20;
b = 15;
c = a+b;
alert(c);
}
sum();
</script>
</body>
</html>
from this demo your code will generate error and execution will stop because before a, b and c variable var keyword required in strict mode.
Error : Uncaught ReferenceError: a is not defined
Deleting a variable is not allowed in strict mode.
Ex:
"use strict";
var a = 50;
delete a; // This will cause an error
"use strict";
var a = 50;
delete a; // This will cause an error
You also can not use the variable name from the following list in strict mode.
public
private
protected
static
package
implements
interface
yield
let
Ex:
"use strict";
var public = 50; // This will cause an error
"use strict";
var public = 50; // This will cause an error
No comments:
Post a Comment