What does 'use strict' do in JavaScript, and what is the reasoning behind it?

Learn what is use of 'use strict' in JavaScript with examples.
Submitted by Pratishtha Saxena, on May 16, 2022

The "use strict" is used to implement the code in strict mode. In JavaScript, a variable can work even if the type of the variable is not declared. Like, if 'x=1.2' is declared, it will work and execute the rest of the code.

Example:

x=2.5;
console.log(x);

The above code will give the following output:

2.5

But, if we apply "use strict" mode then writing only 'x=1.2' will return error as no data type has been assigned to the variable. In strict mode, using a variable without declaring it throws an error.

Example:

'use strict';
x=2.5;
console.log(x);

This will return undefined error as the data type of the variable is not specified.

Output:

Uncaught ReferenceError: x is not defined
    at <anonymous>:2:2

Note: You need to declare strict mode at the beginning of the program. If you declare strict mode below some code, it won't work.

You can also use strict mode inside a function. If 'use strict' is used inside a function then all the variables inside that function will be in strict mode.

Example:

a = 5.6;
console.log(a); // Prints 5.6

function first(){
	'use strict';
	x = 2.5;
}

first(); // Throws error as type is not defined

Output:

Uncaught ReferenceError: x is not defined
    at first (:6:4)
    at <anonymous>:9:1

Why should we apply "use strict"?

This makes it easier to write good and secure JavaScript code. Strict mode removes certain JavaScript silent errors. It makes your code more robust, readable, and accurate.

JavaScript Examples »


ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.