Property check

2 snippets across 2 stacks - JavaScript, TypeScript

JSJavaScript

Checking Property Existence

JS · Objects
Syntax
Object.hasOwn(obj, prop)
"prop" in obj
Example
const user = { name: "Lina", age: 28 };

console.log(Object.hasOwn(user, "name")); // true
console.log(Object.hasOwn(user, "email")); // false
console.log("toString" in user);           // true (inherited)
console.log(Object.hasOwn(user, "toString")); // false

Note Object.hasOwn() (ES2022) replaces obj.hasOwnProperty(). It works even if the object was created with Object.create(null).

TSTypeScript

in Operator Guard

TS · Type Guards & Narrowing
Syntax
if ("property" in value) { ... }
Example
interface EmailContact {
  email: string;
  name: string;
}

interface PhoneContact {
  phone: string;
  name: string;
}

function sendMessage(contact: EmailContact | PhoneContact) {
  if ("email" in contact) {
    console.log(`Emailing ${contact.email}`);
  } else {
    console.log(`Calling ${contact.phone}`);
  }
}
Output
// 'in' narrows based on the presence of a property

Note The 'in' operator checks if a property name exists on an object at runtime. TypeScript uses this to narrow union types. The property name must be a string literal for narrowing to work. Works well when union members have distinct unique properties.

Frequently asked questions

How does JavaScript handle property check?
This task is covered in 2 stacks on this page: JavaScript, TypeScript. The "Checking Property Existence" snippet in JavaScript uses `Object.hasOwn(obj, prop)`.
Which code does the JavaScript example use?
The "Checking Property Existence" snippet uses `Object.hasOwn(obj, prop)`, from the Objects section of the JavaScript cheat sheet.
Which stacks cover "property check" on this page?
JavaScript, TypeScript. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Checking Property Existence": Object.hasOwn() (ES2022) replaces obj.hasOwnProperty(). It works even if the object was created with Object.create(null).