DEV Community

Cover image for Well explained: Javascript in operator
Yanze Dai
Yanze Dai

Posted on • Originally published at pitayan.com

1

Well explained: Javascript in operator

This article is going to uncover the usage of Javascript in operator. in operator is one of the keywords in Javascript. We use it very often in loops or if conditions.

in operator can check if something exists in the Object. It returns true when the first operand is in the Object as a property or exists in the prototype chain.

1. Simple basic usage

Object property check

The follow example returns true because variable obj has all of them.

let obj = {
  javascript: 1,
  html: 2,
  css: 3
}

'javascript' in obj // true
'html' in obj // true
'css' in obj // true

Prorotype chain

It is false because python does not exist in obj but if we could add it to the prototype chain the result will turn to true

'python' in obj // false

obj.prototype.python = 4

'python' in obj // true

Deleted/Undefined Property

When a property is deleted from obj, it returns false because we remove the property completely.

delete obj.javascript

'javascript' in obj // false

But if we sett the property undefined, the in operator returns true because the property exists it just doesn't have any value.

obj.javascript = undefined

'javascript' in obj // true

2. Other usages

Other than using in operator in an hashmap Object, we could also apply it to other situations like String Array and some other supported behaviors in Javascript.

If String is in another String

let str = 'string'

'string' in str // true

'str' in str // true

'ing' in str // true

'something else' in str // false

If an index is in an Array

There are only 3 elements in arr, so the fourth element witn index 3 is out of range.

let arr = ['javascript', 'in', 'operator']

0 in arr // true
1 in arr // true
2 in arr // true

3 in arr // false

Non-inherited property is in Object

obj is inheriting Object. But the native function of toString is an inherited property. To Check if non-inherited property is in Object we need to use Object.property.hasOwnProperty() method.

let obj = {}

'toString' in obj // true

obj.hasOwnProperty('toString') // false

References:


Originally on pitayan.com
https://pitayan.com/posts/javascript-in-operator/

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay