JSFiddle - React, Tailwind, and code Playground

by Andrew Gerst

HTML

JavaScript Pitfalls

Table of Contents:

Decimal fractions
Bitwise OR
NaN
Multiline String Literals
parseInt function
for in with arrays
Array number sort
Deleting Elements
Comments
Addition and concatenation
Unary operator
Percent Operator
Evils of type coercion
With statement
Style isn't subjective
WATMAN!
Constructor

JavaScript

/**
 * Javascript Pitfalls
 */

// Decimal fractions are approximate because of binary floating point.
// Solution (Integers): (Money) Multiply by 100 and use cents.

console.log('SECTION: Decimal Fractions');

a = 0.1;
b = 0.2;
c = 0.3;

console.log((a+b)+c === a+(b+c)); // false
console.log((a*100+b*100)+c*100 === a*100+(b*100+c*100)); // true

// Another solution is to compare doubles using a threshold.

ERROR_ALLOW_WHEN_COMPARE_DOUBLES = 0.01;

function equals(x, y) {
    return Math.abs(x - y) < ERROR_ALLOW_WHEN_COMPARE_DOUBLES;
}

console.log(equals((a+b)+c, a+(b+c))); // true


// Bitwise OR
console.log('SECTION: Bitwise OR');

console.log(13.6 | 0); // 13

// This method can't be applied for money calculations (especially in cases where you multiply by 100 to avoid decimal numbers). This is truncation as opposed to flooring.

console.log(3000000000.1 | 0); // -1294967296, not 3000000000


// Math.floor
console.log('SECTION: Math.floor');

// Math.floor does exactly what it is supposed to with respect to negative numbers. Mathematically, that is what a floor is.

console.log(Math.floor(-13.1) === -14); // true


// NaN
console.log('SECTION: NaN');

// Any arithmetic operation with an NaN as an input will have NaN as a result.
// NaN is not equal to anything, including NaN

console.log(NaN === NaN); // false
console.log(NaN !== NaN); // true


// Multiline String Literals
console.log('SECTION: Multiline String Literals');

long_line_1 = "This is a \
very very very \
long line"; // ok
console.log(long_line_1);

/* You can't have space after backslash
long_line_2 = "This is a \ 
long line"; // Syntax Error
*/


// parseInt function
console.log('SECTION: parseInt function');

// It stops at the first non-digit character.
// The radix(10) should always be used. If it starts with zero it will assume base 8 instead.
// JavaScript thinks that the leading zero indicates an octal integer, and since there is no "8" or "9" in base-8, the function returns zero. Like it...