“use strict” in Javascript

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;
//or
undefined = 5;

Deleting plain names or undeletable properties

var x = "happy";
delete x; //==> What happens to "x"?
//or
delete 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.

Like what you read? Give Daniel Park a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.