beginner

Tricky JS part 1


Javascript is pretty famous for its tricky and sometimes unexpected behaviour. I am going to show some examples starting with expected behaviour that is maybe not straightforward right away and then examples of some tricky situations.

Changing const value

As we know, a const variable can’t be changed after its been assigned a value. To be more specific it can’t be changed through re-assignment or re-declaration. This means that we can change property of a const object or an array because we are not actually changing the reference to a value but value itself.

const a = { name: "Alice" };
const colors = ["red", "green", "blue"];
console.log(a.name); // Alice
a.name = "Bob";
a.age = 30;
console.log(a.name); // Bob
console.log(a.age); // 30
colors.push("yellow");
console.log(colors); // ["red", "green", "blue", "yellow"]
colors = ["red", "green", "blue"]; // this WON'T WORK because we are re-assigning

Floating-Point Arithmetic Precision

JavaScript uses the IEEE 754 standard for representing floating-point numbers, which can lead to precision issues.

0.1 + 0.2; // Returns 0.30000000000000004

To avoid precision errors, you can use libraries like bignumber.js or round results when needed.

Type Coercion

JavaScript is known for its type coercion meaning values of different types are automatically converted in certain situations.

const a = { name: "Alice" };
const colors = ["red", "green", "blue"];
console.log("5" - 3); //  2
console.log("5" + 3); // // "53"
console.log("5" + 5 + 5); // "555"
console.log(5 + 5 + "5"); // "105"
console.log(5 + a); // "5[object Object]"
console.log(5 + colors); // "5red,green,blue"

Non-Numeric Strings and NaN

When you attempt to perform arithmetic operations with non-numeric strings, you’ll often get NaN (Not a Number).

const colors = ["red", "green", "blue"];
console.log("Hello" - "World"); // NaN
console.log(5 - colors); // NaN

JavaScript tries to convert the strings to numbers for subtraction, but since the conversion fails, it results in NaN.

Leading Zeroes and Octal Interpretation

Leading zeroes can result in unexpected octal (base 8) interpretation in JavaScript.

console.log(010); // Outputs 8, not 10

What now?

Now you know some tricky JS situations to be careful of. There will be more posts like this later on. Now go practice a bit.

If you’re interested in a lot more examples check wtfjs, a very interesting github repo.

Previous Working with variables 2
Next Conditional statements