use strict
is a special feature that javascript provides us to write code in the script file.
This helps us to write code more efficiently and smartly. All we need to do is just write use strict
at the beginning of script.js file and that's it. We are ready to use this special feature.
use strict always monitor code which is below it. Code above it will not get monitored so writing use strict at the top is the best practice. Suppose we want to use only for specific function instead of the whole file, then also we can do that by just writing use strict inside that function and this will take care of only that function.
function someFunction() {
'use strict';
// code
}
use strict helps us to write more secure code and secure code means helps to avoid accidental mistakes and also finds bugs in our code by throwing errors in the console. some times javascript does not show errors for small mistakes so while execution it tasks a lot of time to find that error. let's see an example..
let driversLicense = false;
let driverTest = true;
if(driverTest) {
driverLicense=true;
}
if(driversLicense){
console.log("yes")
}
//output=> nothing
In the above case on line number five, we have written driversLicense
spelling different than what we have initialised so in the output we get nothing. Now we need to check code again line by line and then we will get that yes on line number four spelling is wrong so after changing that we will get output "yes".
But if we use use strict
at the beginning we get an error saying that there is some mistake on line number five. So using this special feature is simple and saves our time.
'use strict';
let driversLicense = false;
let driverTest = true;
if(driverTest) {
driverLicense=true;
}
if(driversLicense){
console.log("yes")
}
//output=> Referance error, driverLicense is not defined on line number 5
use strict
gives an error if we use the reserved keyword as a variable in code.
I hope you find this helpful. you can find me on Twitter