Skip to main content

Command Palette

Search for a command to run...

Mastering the 'in' Operator in JavaScript

Published
โ€ข2 min readโ€ขView as Markdown
Mastering the 'in' Operator in JavaScript
D

Hi ๐Ÿ‘‹, I am Dipankar Paul, aspiring Full Stack Developer with a passion for learning new technologies. Currently, I am learning my front-end development and full-stack development through Apna College Delta. With a passion for creating innovative and user-friendly applications, I am excited to continue my journey in the tech industry.

Introduction

In the world of JavaScript, there's a hidden detective known as the in operator. Its role? To determine whether a specific property exists within an object or if an elusive element is concealed within an array. This operator returns a simple verdict: true if the target is found, and false if it remains elusive.

Syntax

Let's start by unveiling the operator's syntax:

// For objects: 
property_name in object_name;
// For arrays: 
element_value in array_name;

Now, let's dive into some examples to grasp its functionality.

Example 1: Property Pursuit

const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

console.log('name' in person); // Output: true
console.log('address' in person); // Output: false

In this example, name in person returns true because the person object contains a property named name. However, address in person returns false as the address property doesn't exist in the object.

Example 2: Array Adventure

const fruits = ['apple', 'banana', 'orange'];

console.log('apple' in fruits); // Output: true
console.log(0 in fruits); // Output: false

In the second scenario, apple in fruits returns true because the fruits array does indeed contain an element with the value apple. However, 0 in fruits returns false because there is no element in the array with the value 0.

Key Takeaways

  • The in operator is used to check if a property exists in an object or an element exists in an array.
  • It returns true if the property/element exists and false otherwise.
  • The syntax of the in operator is property_name in object_name or element_value in array_name.
  • When checking an object, the property name must be enclosed in quotes.
  • When checking an array, the element value can be a value or an index.

Javascript

Part 20 of 24

In this series I will be sharing my journey in learning Javascript and posting my own notes from the process. These notes can be helpful for beginners in learning this amazing language. Good luck.

Up next

Mastering the JavaScript delete Operator

Introduction In the world of JavaScript, think of the delete operator as your tool for making changes to objects and arrays. It allows you to remove specific things like properties in objects and elements in arrays. Let's explore how it works and wha...

More from this blog

Dipankar Paul's blog

51 posts