As a scripting language, JavaScript may occasionally yield the correct output despite containing errors within the code. To address this issue, one effective approach is to employ JavaScript's strict mode.
JavaScript offers the "use strict"; directive to activate strict mode. When this mode is enabled, any silent errors or missteps in the code will result in an error being thrown.
Note - The "use strict"; expression can only be placed as the first statement in a script or in a function.
JavaScript use strict Example
Example 1
Let's see the example without using strict mode.
<script>
x=10;
console.log(x);
</script>
Output:
In this instance, we have not specified the variable type. Nevertheless, we are still able to obtain an output.
Let us examine the identical example while activating strict mode.
<script>
"use strict";
x=10;
console.log(x);
</script>
Output:
At this point, an error will be raised because the type of x has not been specified.
Example 2
Let us examine an additional illustration that demonstrates how to calculate the sum of two numbers.
<script>
console.log(sum(10,20));
function sum(a,a)
{
"use strict";
return a+a;
}
</script>
Output:
In this instance, an error arises due to the presence of duplicate elements.