“use strict” in Javascript

Daniel Park
2 min readMay 12, 2017

--

We all know that JavaScript can be weird sometimes. There are certain things that we all know that we shouldn’t do but CAN do and get away with it. We can do things like establish a global variable and not cause any errors.

x = "happy";//Everyone knows that you CAN but SHOULDN’T do this.

You probably meant to write…

var x = "happy";

Below are a couple of more examples of things that you can do in JavaScript that you really shouldn’t do.

Setting a function with the same parameter names

function funny(a, a) {
console.log("happy")
}

Establishing an object with the same keys.

var x = {a: "happy", a: "cat"};x; //==> What would "x" look like?

Silent failing assignments

NaN = 5;//orundefined = 5;

Deleting plain names or undeletable properties

var x = "happy";
delete x; //==> What happens to "x"?
//ordelete Object.prototype

Setting an integer that starts with a zero to a variable

var x = 0123;  //<<== what is this?

Implementing Strict Mode

Strict Mode is a feature in JavaScript that was introduced in ECMAScript 5. It eliminates some JavaScript silent errors by changing them to throw errors. Strict mode applies to entire scripts or to individual functions. It doesn’t apply to block statements enclosed in {} braces. You can implement strict mode by adding “use strict”; to the beginning of a script or a function.

Strict Mode for scripts

'use strict';  //You're in Strict Mode!var x = "Hello World!";

Strict Mode for functions

function cool() {
"use strict";
// ... your code ...
// this function is executed in strict mode
}
//anything outside of the function will be in non-strict mode.

I‘m not sure how often I’ll use strict mode but I think it’ll come in handy if I were to teach a beginner and to reinforce what I know about JavaScript or if I myself wasn’t sure of committing bad syntax. It’s great to get another level of error messages since we as developers depend on them so much.

--

--