Using strict mode
We can change the understanding and forgiving behavior of JavaScript to some extent using strict mode. You can switch on strict mode with the following command in your code. This needs to be the first command of your code:
"use strict";
Here is something that works when we don't use strict mode:
function sayHi() {
greeting = "Hello!";
console.log(greeting);
}
sayHi();
We forgot to declare greeting
, so JavaScript did it for us by adding a greeting
variable to the top level and it will log Hello!
. If we enable strict mode, however, this will give an error:
"use strict";
function sayHi() {
greeting = "Hello!";
console.log(greeting);
}
sayHi();
The error:
ReferenceError: greeting is not defined
You can also use strict mode only in a particular function: simply add it to the top of the function and it gets enabled for that function only. Strict mode alters a few other things...