Skip to content

Semantics

Amila Welihinda edited this page Apr 16, 2017 · 10 revisions

Here is a list of the semantics of JavaScript that babel-plugin-fail-explicit changes:

1. Array access array out of bounds:

If an array index that is out of bounds is accessed, fail-explicit will throw a TypeError.

Example:

const foo = []
foo[100]
// ^ TypeError: "Array[100]" is out of bounds

2. Access of non-existent property

If a non-existent property is accessed on an object array index that is out of bounds is accessed, fail-explicit will throw a TypeError.

Example:

const foo = {}
foo.bar
// ^ TypeError: Property "bar" does not exist in "Object"

3. Restriction of operators to numbers and strings and types

Operators can only be used with numbers and strings

Example:

// Coercion of types that are not strings or numbers:
new Array() + new Object()
// ^ Unexpected coercion of type "Array" and type "Object" using "+" operator

// Usage with different operators:
'foo' * 12
// ^ TypeError: Unexpected coercion of type "string" and type "number" using "*" operator
null - undefined
// ^ TypeError: Unexpected coercion of type "null" and type "undefined" using "-" operator

// Comparison of different types:
const str = '12'
const num = 12
str > num
// ^ TypeError: Unexpected comparison of type "string" and type "number" using ">" operator

// Comparison of same types:
new String('aa') < 'bb' // true
'aa' < 'bb' // true

const foo = {}
const bar = []
foo >= bar
// ^ Unexpected comparison of type "Object" and type "Array" using ">=" operator

4. Allow propagation of default values

If a property access is followed by a LogicExpression (||), . This semantic was added because propagating default values using the || operator is a very common practice. By default, this is enabled but it can be turned off by enforceLogicExpressionCheck to false in the plugin's config.

Example:

const some = {}
some.foo || 'bar' // bar

5. 💡 Idea: Allow access of non-existent properties in test of conditional statement and expressions

A common practice in JavaScript projects is to check the existence of a property by simply accessing the property. While this isn't as safe as properly checking the existence of a property, adding this semantic may make it easier for projects to integrate fail-explicit. By default, this feature should be disabled.

Example:

const foo = {}

if (foo.bar) {
  // do stuff
}

const baz = foo.bar ? 'foo' : 'bar' // bar