Learn

Now that you have learned about some dangerous functions and regular expressions to avoid, let’s learn about some defensive tools. One of them is JavaScript’s strict mode. Using strict mode throws errors that would otherwise be silent, which can help reveal vulnerabilities. To invoke strict mode, simply put "use strict"; in single or double quotes on top of your JavaScript file.

For example, strict mode catches assignments to undefined variables:

// Runs fine without strict mode x = "codecademy";
// Throws “ReferenceError” with strict mode "use strict"; x = "codecademy";
// Runs fine with strict mode if the variable is declared with let, var, or const "use strict"; var x = "codecademy";

We are going to use strict mode to find the errors in the workspace code!

Instructions

1.

In the workspace, we have some code in a file named main.js. Without strict mode, there should be no errors.

Run node main.js on the terminal and take a note of the output. Click Check Work to move to the next checkpoint.

2.

Add strict mode at the top of this file and click Check Work.

3.

Use node main.js to try run the program with strict mode on! Note that strict mode will stop execution on the first error, so we’ll see one error at a time as we’re fixing.

Strict mode caught a SyntaxError! It looks like it’s unhappy that the function printNames() has duplicate parameters. There are two parameters both called names. Let’s remove one of them in the function definition. Don’t forget to change the calls to this function as well.

Click Check Work when you’re ready to move on.

4.

Run main.js again with node main.js. Strict mode caught another SyntaxError! This one should state that variables cannot be named arguments or eval. Change the name of the variable violating this rule to ourNames. Remember to change any references to this variable as well.

Click Check Work when you’re ready to move on.

5.

Run node main.js again. This SyntaxError warns that variables or functions cannot be deleted. Let’s remove the line delete printNames; from the code.

Click Check Work when you’re ready to move on.

6.

Running node main.js one last time gives you a ReferenceError stating that companyName is not defined. Variables cannot be assigned without being declared first. Make sure each variable is first declared with either let, var, or const.

Great job! Hopefully, you understand how we can read the errors to figure out what needs to be changed. The output when running node main.js should not throw any more errors, meaning the code has passed JavaScript’s strict mode!

Click “Check Work” to move on to the next exercise.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?