JavaScript Strict Mode
JavaScript's strict mode, introduced in ECMAScript 5, is a way to opt-in to a restricted variant of JavaScript, thereby implicitly opting-out of "sloppy mode". Strict mode isn't just a subset: it intentionally has different semantics from normal code.
Strict mode implements several changes to normal JS code semantics:
1. Eliminates some JavaScript silent errors by changing them to throw errors.
2. Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode.
3. Prohibits some syntax likely to be defined in future versions of ECMAScript
How does one go about invoking strict mode in their code? There are several places you can do this and these include in functions, for whole scripts and since ECMAScript 2015, in modules.
To invoke strict mode in functions, simply add 'use strict'; OR "use strict"; to the beginning of your function as shown in figure 3 below:
Figure 4 depicts strict mode in scripts:
Modules automatically enforce strict mode and so there is no need to use the 'use strict' keywords.
We cannot talk about strict mode in JS without talking aboout TypeScript(TS). TS is a programming language that is a strict syntactical superset of JavaScript and adds optional static typing to the language. Static typing means that there is a strict monitoring of the interaction of data types and no overlap between data types is allowed. For example, if you declare a variable as a string in a statically typed language, declaring the same variable later as a number will throw an error.
Unsurprisingly, TS makes use of interfaces to enforce typing in TS. This endows TS with the powerful ability to define contracts('rules') within code in and outside of a project.
To understand the the use of interfaces in TS, let us look at an example:
In figure 5 above, type checker checks the call to printLabel. The printLabel function has a single parameter that requires that the object passed in has a property called label of type string. Notice that our object actually has more properties than this, but the compiler only checks that at least the ones required are present and match the types required.
In figure 6 below, we write the example again, this time using an interface to describe the requirement of having the label property that is a string:
The interface LabeledValue above is a name we can now use to describe the requirement in the previous example. It still represents having a single property called label that is of type string. Notice we didn’t have to explicitly say that the object we pass to printLabel implements this interface like we might have to in other languages. Here, it’s only the shape that matters. If the object we pass to the function meets the requirements listed, then it’s allowed.





Comments
Post a Comment