STRICT MODE

JS

Javascript was born as a language to be simple even for inexperienced programmers, which is why it accepts code written with a range of issues. ES5 has introduced innovations that partly remedy this conception. The strict mode can be applied either to the entire javascript program or to individual functions. The modules introduced in ES6 already operate in strict mode.

Strict Mode
Copy to Clipboard

DIFFERENCES BETWEEN NORMAL MODE AND STRICT MODE

The code below illustrates some of the differences between normal mode and strict mode.

Copy to Clipboard

STRICT MODE AND THIS

This in normal mode is always a reference to an object. If we invoke the function on a primitive value, the value will be converted to an object. In strict mode there is no object forcing, and this is an advantage for performance. Also within a function this in strict mode does not reference the window object unless it is invoked on that object.

Copy to Clipboard

ERROR HANDLING INTRODUCTION

Proper error handling is a very important aspect of application development. When there are instructions that can generate errors these should be put in a block try (try execute the following instructions), if an error is generated control immediately passes to the block
catch
which receives as input the error object containing information about the nature of the error.

Copy to Clipboard

ERROR HANDLING THROW NEW AND BLOCK FINALLY

If an exception is raised ReferenceError such an object is a constructor function whose instances are created with the keyword new.The instance of that object is passed as an argument in the catch so that we can get all the detailed information about the error. The block finally is always executed, whether errors are present or absent.

Copy to Clipboard

ERROR HANDLING HANDLE APPLICATION ERRORS

Whether it is a user interface or a request to an external API errors can be triggered by the application and should be handled as such. Let’s look at an example.

Copy to Clipboard

DEEPENING AI

Strict mode in JavaScript is a feature introduced with ECMAScript 5 (ES5) that allows you to write more secure and less error-prone JavaScript code. When you enable strict mode, JavaScript adopts a number of additional restrictions and stricter behaviors to avoid common errors or ambiguities that could cause problems in your code.

How to enable strict mode

To enable strict mode in JavaScript, simply add the string “use strict”; to the beginning of a script or function. Here is an example:

1. Global application:

use strict“;

function myFunction() {
// Codice JavaScript in modalità strict
}

2. Local application (only inside a function):

function myFunction() {
use strict“;
// Solo questa funzione sarà eseguita in modalità strict
}

Features and restrictions of strict mode

1. Mandatory declaration of variables:

In strict mode, you cannot use variables without first declaring them (with var, let or const).

use strict“;
x = 10; // Genera un errore, perché x non è dichiarata

2. Safe deletion of properties:

You cannot delete a variable, function or object with the delete operator in strict mode.

use strict“;
var obj = {};
delete obj; // Genera un errore

3. Variable names and duplicate parameters not allowed:

You cannot have multiple parameters with the same name in a function or declare an existing variable.

use strict“;
function myFunction(x, x) {
// Genera un errore: parametri duplicati
}

4. Restrictions on eval():

Code executed inside eval() cannot declare variables or functions that are defined outside of it.

use strict“;
eval(“var x = 2;”);
console.log(x); // Genera un errore: x non è definito al di fuori di eval

5. Modification of read-only properties not allowed:

In strict mode, modifying the non-writable properties of an object generates an error.

use strict“;
var obj = {};
Object.defineProperty(obj, “prop“, { value: 42, writable: false });
obj.prop = 10; // Genera un errore

6. Avoid using future reserved words:

Reserved words for future versions of ECMAScript (such as implements, interface, let, package, private, protected, public, static, yield) cannot be used as identifiers.

use strict“;
var let = 10; // Genera un errore

Benefits of strict mode

-Silent errors made explicit: Situations that would normally be ignored by the JavaScript engine (such as using undeclared variables) generate clear and immediate errors, facilitating debugging.

-Improved performance: In some JavaScript engines, code in strict mode can be better optimized.

-Improved security: Strict mode prevents some vulnerabilities, such as modifying non-writable properties or declaring unintended global variables.

Error handling in JavaScript

In JavaScript, errors can be handled using the try…catch construct. This construct allows for controlled handling of exceptions that may be raised during code execution.

Basic syntax:

try {
// Codice che potrebbe generare un errore
} catch (err) {
// Codice per gestire l’errore
} finally {
// Codice che viene eseguito sempre, indipendentemente dall’errore
}

}

Components of the try…catch construct:

1. try: Contains code that could raise an error.

2. catch: Executed if an error is raised in the try block. The caught error is available as a parameter (often called err or error).

3. finally (optional): This block is executed whether or not an error has occurred. It is useful for performing cleanup operations, such as releasing resources.

Example:

use strict“;

try {
   let x = 10;
   x = y + 1; // Genera un errore, perché y non è definita
} catch (err) {
   console.log(“Errore catturato: ” + err.message);
} finally {
   console.log(“Questo verrà eseguito sempre“);
}

Creating custom errors

In JavaScript, you can also generate custom exceptions using the throw statement. This allows you to raise specific errors under certain conditions.

use strict“;

function checkAge(age) {
    if (age < 18) {
       throw new Error(“L’età deve essere almeno 18.“);
    }
    return true;
}

try {
     checkAge(15);
} catch (err) {
     console.log(“Errore: ” + err.message);
}

Types of errors in JavaScript

-ReferenceError: Raised when an attempt is made to access an undefined variable.

-TypeError: Raised when an operation is performed on an invalid data type.

-SyntaxError: Raised when the code contains syntax errors.

-RangeError: Raised when a number is out of the valid range.

-EvalError: Raised when there is a problem using eval() (this error is rare in modern versions of JavaScript).

Best practices in error handling:

1. Always use try…catch to handle potential errors, especially when working with external input, network requests, or code that could generate errors.

2. Avoid abusing try…catch: Do not wrap all code in a try…catch block for no reason, as it can make the code difficult to read and maintain.

3. Create clear error messages: When raising a custom error, provide a clear message describing the problem.

Strict mode, along with good error handling, helps make JavaScript code more robust, readable, and easy to maintain.

LINKS TO PREVIOUS POSTS

THE JAVASCRIPT LANGUAGE

LINK TO CODE ON GITHUB

GITHUB