المشاركات

Why should we use strict in JavaScript

A blog explaning the sctrict in Javascript. How to enable Strict Mode in javascript.

Strict in Javascript

What is Strict

StrictMode was a new feature in ECMAScript 5 that allows you to place a program or a function in a 'strict' operating context.


Benefits

- eliminates some Javascript silent errors by changing them to throw errors.

- prohibits some syntax likely to be defined in future versions of ECMAScript 

- prevents or throw errors when relatively "unsafe" actions are taken (such as gaining access to the global object)

- disables features that are confusing or poorly thought out.

- Strict Mode makes it easier to write "secure" Javascript.


Enable Strict Mode

Strict Mode is optional.

Keyword for strict Mode is the string "use strict"

You can put it at the beginning of a file, to apply it to all the code contained in the file 

Enable Strict Mode 

You can also enable Strict Mode for an individual function, by putting 'use strict' at the beginning of the function body.

Example

Keywords

Keywords reserved for future Javascript versions can NOT be used as variable names in Strict Mode 

implements   protected

interface       public 

let                 static

package         yield

private


Not Allowed

- Using a variable, without declaring it.

- Using an object, without declaring it 

- Deleting a variable (or object)

- deleting a function

- Duplicating a parameter name

 -Octal numeric literals

- Octal escape characters

- Writing to a read-only property

- Writing to get-only property

- Deleting an undeletable property 


Tips for Strict Mode

- If you want to enable Strict Mode in a global way, always put it in the first line "use strict"


- Modern Javascript supports "classes" and "modules" - advanced language structures that enable use strict automatically.

So we don't need to add the "use strict" directive if we use them.


إرسال تعليق

© Coding Hindi. All rights reserved. Premium By Raushan Design