JavaScript: The Why And How Of Strict Mode

By this guy:

@MichaelKropat

JavaScript: The Why And How Of Strict Mode + Linting

By this guy:

@MichaelKropat

JavaScript: Serious Business

Spot the bug

// min: return the smallest element in arr
function min(arr) {
  var result = Infinity;
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] < result) {
      reuslt = arr[i];
    }
  }
  return result;
}

Spot the bug

// min: return the smallest element in arr
function min(arr) {
  var result = Infinity;
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] < result) {
      reuslt = arr[i]; // <== RIGHT HERE
    }
  }
  return result;
}

Without Strict Mode

> min([3,1,2])
Infinity

With Strict Mode

> min([3,1,2])
Uncaught ReferenceError: reuslt is not defined

Strict Mode

Let's try one more

var isNodejs = (typeof module) !== 'undefined' &&
    (typeof module.exports) !== 'undefined';
if (isNodejs) {
  function open(filename) {
    return require('fs').readFileSync(filename);
  }
}

Without Strict Mode

(In a browser)

> typeof readFile
"function"
> readFile('somefile')
Uncaught ReferenceError: require is not defined

With Strict Mode

Uncaught SyntaxError: In strict mode code,
functions can only be declared at top level or
immediately within another function.
> typeof readFile
"undefined"

Some other things you can't do in strict mode

Strict Mode Comes In
2 Forms

Script Form Has One Big Gotcha

Let's concatentate them

'use strict';

var a = 123;

b = 456;

Let's concatentate them

'use strict';

var a = 123;

b = 456; // <== error in strict mode

Conclusion: Use Function Form

Exception: Unit Tests

To recap...