https://mirankavinda.medium.com/weirdness-in-javascript-043767bca370

Weirdness in JavaScript

Miran Kavinda
2 min readApr 20, 2024

Have you ever felt confused while coding in JavaScript? You might have encountered a tricky little character called the "in" operator. In this article, we'll break down what the "in" operator does and why it might seem confusing at first glance.

What Does the “In” Operator Do?

Think of the “in” operator like checking a toolbox to see if a certain tool exists. But here’s the twist it doesn’t actually look at the tool itself. Instead it checks if there’s a specific spot for that tool in the toolbox.

Examples to Clear Things Up

Let’s say you have a list of names, like

["Elon", "David", "Sam", "Greg"].

If you use the “in” operator to check for “Elon” you might expect it to say “true” since Elon is in the list. But surprisingly it says “false”

// Checking for "Elon" in the list of names
console.log('Elon' in [“Elon”, “David”, “Sam”, “Greg”]);

// Output: false

Why? Because it’s not checking for the name “Elon” it’s checking if there’s a spot specifically labeled “Elon” in the list. Since there isn’t it says “false”.

Now consider an array of numbers like

[1, 2, 3]

If you check for “0” using the “in” operator, it says “true” Even though there’s no actual “0” in the array, there’s a spot labeled “0”, so the “in” operator gives a thumbs up.

// Checking for "0" in the array of numbers
console.log(0 in [1, 2, 3]);

// Output: true

Confusion with Objects

Objects in JavaScript are like collections of labeled things. If you delete a label or set its value to “undefined”, the “in” operator behaves differently.

For example, imagine a car object with properties like “make” and “model”. If you delete the “make” property, then checking for “make” using “in” returns “false” as expected. But if you set “make” to “undefined” the “in” operator still returns “true” Weird, right?

// Creating a car object
const car = {
make: 'Vega',
model: 'VegaEVX',
};

// Deleting the "make" property
delete car.make;
console.log('make' in car);
// Output: false

// Setting "make" to "undefined"
car.make = undefined;
console.log('make' in car);
// Output: true

Why the Confusion?

The “in” operator works with something called the prototype chain which defines all the things you can do with an object. It simply checks if a specific operation is allowed on that object, not the actual values inside it.

The Takeaway

The “in” operator might seem a bit weird at first. Just remember, it’s checking for allowed operations, not the actual contents of an array or object. Keep this in mind and you’ll master this JavaScript quirk in no time.

Happy coding, and may your JavaScript journey be free of unnecessary weirdness :)

--

--

Miran Kavinda
Miran Kavinda

No responses yet