Explain Codes LogoExplain Codes Logo

Javascript isset() equivalent

javascript
prompt-engineering
existence-checks
javascript-operators
Nikita BarsukovbyNikita BarsukovΒ·Nov 14, 2024
⚑TLDR

There isn't a direct isset() function in JavaScript, but fear not, you can still check if a variable or property exists:

// Quick existence check for myVar if (typeof myVar !== 'undefined') { // myVar exists, no existential crisis here! }

You want to check if an object property is playing hide and seek? Use either:

// Looking for 'prop' in myObj? if ('prop' in myObj) { // Found 'prop'! πŸ•΅οΈβ€β™€οΈ }

Or

// Need to be sure if 'prop' is really a part of myObj? if (myObj.hasOwnProperty('prop')) { // 'prop' is indeed myObj's own property! 🏑 }

Comprehending existence checks

Existential dilemma for a Variable?: typeof operator

The typeof operator is your friend when dealing with uncertain existence of a variable.

// This is safe - just like asking: "Who are you?" instead of "Are you John Doe?" if (typeof whoKnows !== 'undefined') { // We found someone who's not undefined! }

Can't trust the inheritance: hasOwnProperty method

If you prefer direct ownership over inherited properties, hasOwnProperty will serve you well:

// More picky than 'in', only trusts direct ownership if (myObj.hasOwnProperty('prop')) { // 'prop' is literally myObj's legit kid πŸ§’πŸ‘Œ }

Generous heritage inspector: in operator

To check for a property existent anywhere, whether in direct ownership or inheritance, go for the in operator:

// Doesn't care about direct ownership, loves all properties alike if ('prop' in myObj) { // 'prop' spotted in myObj's vicinity πŸš€ }

Coding like hipsters: Optional Chaining (?.) & Nullish Coalescing (??)

Embrace the modern JavaScript syntax of Optional Chaining and Nullish Coalescing to handle uncertainties:

// Oh please dear existence, give me some value or undefined, no error am I seeking! let value = myObj?.prop; // Dear null or undefined, should you dare to exist, become 'default' you will! let secureValue = myObj?.prop ?? 'default';

Need a sturdy isset(): Libraries & NPM packages

For deeply nested property checks, consider using utilities from libraries such as Lodash or Underscore:

// Going deep with Lodash _.has(myObj, 'deeply.nested.prop');

The isset-php package is a robust PHP-style isset() function port for JavaScript, handling checks on multiple arguments altogether:

// This is like buying PHP's isset() a JavaScript ticket const isset = require('isset-php'); if (isset(() => myObj.prop1, () => myObj.prop2)) { // All properties exist and we're good to go! }

The global search: Checking global variables

Global variables are accessible via the window object, hence their existence is verifiable through it:

// Caught the global variable yet? Sherlock 'window' Holmes to the rescue! if ('myGlobalVar' in window) { // Global variables can't hide from me πŸ•΅οΈ }

Custom built isset(): Arrow function

No one said you couldn't craft your own isset() function using an arrow function:

// All you need: a portable isset() because JavaScript won't complain const isset = (prop) => typeof prop !== 'undefined'; if (isset(myObj?.prop)) { // Live long and prosper with myObj.prop }

Daredevil check: Negation of the in operator

Remember, the in operator can be negated, much like a double-edged sword:

// 'prop': Not in myObj? Let's find out! if (!('prop' in myObj)) { // 'prop' isn't partying in this myObj club πŸ•ΊπŸš« }

Do remember it doesn't confirm prop is null or undefined. It merely signifies the absence of recognition as a property.

Decoding these methods

Checking associative arrays

Ensure you're looking in the right place when it comes to associative arrays:

// For hunting a specific key in myArray if (myArray.hasOwnProperty('key')) { // Found the 'key' to our problem! πŸ”‘πŸ’‘ }

Distrust in falsy friends

Watch your back when dealing with falsy values. They might make you fall in the trap of non-existent existence:

if (myObj.prop) { // Falsy values lurk around, making this unreliable 😨❌ }

Consistency: The ace in the hole

Maintaining a consistent way of checking property presence fends off errors and pain in general:

if (typeof someArray['key'] !== 'undefined') { // Because 'key' might like playing the game of hide and seek! }

In-depth knowledge is power

The more, the merrier! Deep dive into provided references for an oceanic understanding of typeof, hasOwnProperty, in, and the nuances of JavaScript existence checks.