You can turn the values of an Object into an array and test that a string is present. It assumes that the Object is not nested and the string is an exact match:

var obj = { a: 'test1', b: 'test2' };
if (Object.values(obj).indexOf('test1') > -1) {
   console.log('has test1');
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values

Answer from Matt Pileggi on Stack Overflow
Top answer
1 of 16
704

You can safely use the typeof operator on undefined variables.

If it has been assigned any value, including null, typeof will return something other than undefined. typeof always returns a string.

Therefore

if (typeof maybeObject != "undefined") {
   alert("GOT THERE");
}
2 of 16
50

There are a lot of half-truths here, so I thought I make some things clearer.

Actually you can't accurately tell if a variable exists (unless you want to wrap every second line into a try-catch block).

The reason is Javascript has this notorious value of undefined which strikingly doesn't mean that the variable is not defined, or that it doesn't exist undefined !== not defined

var a;
alert(typeof a); // undefined (declared without a value)
alert(typeof b); // undefined (not declared)

So both a variable that exists and another one that doesn't can report you the undefined type.

As for @Kevin's misconception, null == undefined. It is due to type coercion, and it's the main reason why Crockford keeps telling everyone who is unsure of this kind of thing to always use strict equality operator === to test for possibly falsy values. null !== undefined gives you what you might expect. Please also note, that foo != null can be an effective way to check if a variable is neither undefined nor null. Of course you can be explicit, because it may help readability.

If you restrict the question to check if an object exists, typeof o == "object" may be a good idea, except if you don't consider arrays objects, as this will also reported to be the type of object which may leave you a bit confused. Not to mention that typeof null will also give you object which is simply wrong.

The primal area where you really should be careful about typeof, undefined, null, unknown and other misteries are host objects. They can't be trusted. They are free to do almost any dirty thing they want. So be careful with them, check for functionality if you can, because it's the only secure way to use a feature that may not even exist.

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Object › hasOwn
Object.hasOwn() - JavaScript | MDN
const object = { prop: "exists", }; console.log(Object.hasOwn(object, "prop")); // Expected output: true console.log(Object.hasOwn(object, "toString")); // Expected output: false console.log(Object.hasOwn(object, "undeclaredPropertyValue")); // Expected output: false ... The JavaScript object instance to test. ... The String name or Symbol of the property to test. true if the specified object has directly defined the specified property.
🌐
Sabe
sabe.io › blog › javascript-check-if-value-exists-in-object
How to Check if a Value Exists in an Object in JavaScript
September 10, 2022 - We can check if a value exists in an object by first getting all of the values with Object.values() and then using the includes() method. JAVASCRIPTconst object = { name: "John", age: 30 }; if (Object.values(object).includes("John")) { ...
🌐
freeCodeCamp
freecodecamp.org › news › how-to-check-if-a-property-exists-in-a-javascript-object
How to Check if a Property Exists in a JavaScript Object
April 25, 2022 - We can check if a property exists in the object by checking if property !== undefined. In this example, it would return true because the name property does exist in the developer object.
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › object › object has value or key
Check if a JavaScript object has a given value or key - 30 seconds of code
February 10, 2024 - While the JavaScript API for objects ... task. In order to check if an object has a given value, you can use Object.values() to get all the values of the object....
🌐
TutorialsPoint
tutorialspoint.com › how-to-check-whether-an-object-exists-in-javascript
How to check whether an object exists in JavaScript?
In the example below, we have created the phone object, which contains some properties and values as a key-value pair. After that, we used the if-else statement to check if the phone object exists in the code. Users can observe the output that control goes to the if block as a phone object exists.
Find elsewhere
Top answer
1 of 5
15

Let's say we start with

const obj = {foo : "bar"};

Check for a value:

const hasValue = Object.values(obj).includes("bar");

Check for a property:

// NOTE: Requires obj.toString() if key is a number
const hasProperty = Object.keys(obj).includes("foo");

Multi-level value:

function hasValueDeep(json, findValue) {
    const values = Object.values(json);
    let hasValue = values.includes(findValue);
    values.forEach(function(value) {
        if (typeof value === "object") {
            hasValue = hasValue || hasValueDeep(value, findValue);
        }
    })
    return hasValue;
}

Multi-level property:

function hasPropertyDeep(json, findProperty) {
    const keys = Object.keys(json);
    let hasProperty = keys.includes((findProperty).toString());
    keys.forEach(function(key) {
        const value = json[key];
        if (typeof value === "object") {
            hasProperty = hasProperty || hasPropertyDeep(value, findProperty);
        }
    })
    return hasProperty;
}
2 of 5
4

No, there is no built in method to search for a value on an object.

The only way to do so is to iterate over all the keys of the object and check each value. Using techniques that would work even in old browsers, you can do this:

function findValue(o, value) {
    for (var prop in o) {
        if (o.hasOwnProperty(prop) && o[prop] === value) {
            return prop;
        }
    }
    return null;
}

findValue(car, "2011");    // will return "year"
findValue(car, "2012");    // will return null

Note: This will return the first property that contains the search value even though there could be more than one property that matched. At the cost of efficiency, you could return an array of all properties that contain the desired value.

Note: This uses the extra .hasOwnProperty() check as a safeguard against any code that adds enumerable properties to Object.prototype. If there is no such code and you're sure there never will be, then the .hasOwnProperty() check can be eliminated.

🌐
CodeParrot
codeparrot.ai › blogs › check-if-a-key-exists-in-a-javascript-object
Ways to Check If a Key Exists in a JavaScript Object
One of the simplest ways to check if a key exists in a JavaScript object is by using the in operator.
🌐
JavaScript Tutorial
javascripttutorial.net › home › 3 ways to check if a property exists in an object
3 Ways to Check If a Property Exists in an Object in JavaScript
June 21, 2020 - How to check if a property exists in an object in JavaScript by using the hasOwnProperty() method, the in operator, and comparing with undefined.
🌐
MyTutor
mytutor.co.uk › answers › 10947 › Mentoring › Javascript › How-to-check-if-value-exists-in-an-object-in-Java-Script
How to check if value exists in an object in JavaScript?
Let's consider an example which would answer this question var priceOfFood = { pizza: 14, burger 10 } priceOfFood.hasOwnProperty('pizza') // true priceOfFood['pizza'] // 14 priceOfFood.hasOwnProperty('chips') // false priceOfFood['chips'] // undefined in comments we have the returned value ...
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-check-whether-an-object-exists-in-javascript
How to check whether an object exists in javascript ? - GeeksforGeeks
July 12, 2025 - Checking whether an object exists in JavaScript refers to determining if a variable or property has been declared and contains a valid value.
🌐
TutorialsPoint
tutorialspoint.com › how-check-if-object-value-exists-not-add-a-new-object-to-array-using-javascript
How Check if object value exists not add a new object to array using JavaScript ?
") console.log(checkName('JavaScript')); console.log(" Does the object HTML exist in the array? ") console.log(checkName('HTML')); Step 1 ?Define an array ?inputArray' and add key value pair values to it. Step 2 ?Define a function ?checkName' that takes a string as a parameter. Step 3 ?In the function, use the function some() to check if the given value exists in the array.
🌐
Suraj Sharma
surajsharma.net › blog › check-object-in-javascript-array
How to check if a value exists in an Array of Objects in JavaScript | Suraj Sharma
You can use the some() method to check if an object is in the array. users.some(function (u) { if (u.username === user.username) return true; return false; }) // false // using an arrow function users.some(u=>u.username === user.username) // ...
🌐
EnableGeek
enablegeek.com › home › javascript check if value exists in array of objects
Javascript Check if Value Exists in Array of Objects - EnableGeek
August 7, 2023 - The some() method returns a Boolean value indicating whether at least one element in the array satisfies the provided testing function. You can use it to check if a value exists in an array of objects by defining a testing function that checks ...
🌐
Reddit
reddit.com › r/javascript › [askjs] is it bad practice to check if a value exists in the same if() statement the value is used?
r/javascript on Reddit: [AskJS] Is it bad practice to check if a value exists in the same if() statement the value is used?
December 2, 2023 -

I was making a tool for Dungeons and Dragons in which the user can click and drag character names around the screen. The characters are objects in an array, and whenever the user is dragging the name, an i() statement compares the mouse's position to the name above and the name below in the array. Problem is, the next or previous character in the array might not exist, the index might be out of bounds, and there's no guarantee that it will be in bounds.

if(mouseY < characters[i - 1].handle.position.y) {

So I did this.

if(characters[i - 1] != undefined && mouseY < characters[i - 1].handle.position.y) {

The key is checking the value is not undefined first, because that's how an if() statement is processed. If it is not undefined, the program can proceed to the next check, now that it is safe to do so. If it is undefined, it aborts the if() statement, and so the next check, which would bring everything to a screeching halt, never happens.

I'm just wondering if using if() statements in this way is something people should be doing. It feels like I shouldn't be doing it, but at the end of the day, it works.

Top answer
1 of 6
28
Nothing wrong with it, boolean evaluations in javascript short circuit so if the falsy check fails it'll drop off. You could do optional chaining which is a bit shorter but could be misinterpreted later due to misreading if (mouseY < characters[i - 1]?.handle.position.y) { ... } if characters[i-1] doesn't exist the entire chain will resolve to undefined numberis incompatible with undefined so any comparison to it will resolve to false https://en.wikipedia.org/wiki/Short-circuit_evaluation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
2 of 6
8
As many people have said, readability is your main concern. Is it "bad practice"? Well that's more a people issue than a coding issue. Logically we can write the same code multiple ways and get the same result and have similar performance. The difference you'll run into is you coming back to the project after 6 months of not paying attention to it and depending which option you chose, how fast you'll be able to pick it back up. This results in a few questions: Is this a short term personal project? Then it doesn't really Is this a long term personal project? Then it's a question to you to ask if you were to read this line of code, is it clear to you what's going on? Is this a team project? Readability is far more important for team projects because you never know if a junior engineer or a staff engineer is reading it. So let's start with your code and refactor it a bit. Your current code: if(characters[i - 1] != undefined && mouseY < characters[i - 1].handle.position.y) { Reading this, I have no idea what characters[i - 1] means (pointing to a readability concern) and it's duplicated. We can improve future readability by pulling out a variable: const someMeaningfulName = characters[i - 1]; if(someMeaningfulName != undefined && mouseY < someMeaningfulName.handle.position.y) { This way when someone reads the code, it's far easier to understand your intention when you were writing the code. That variable meant something at the time or writing, it's useful to capture that. Now incorporating @kherven's comment const someMeaningfulName = characters[i - 1]; if (mouseY < someMeaningfulName?.handle.position.y) It definitely reduces the code, and improves readability, but does it improve readability of intention? Your original code checked for undefined and not null. By using this code, if you intentionally wanted to throw an error when the value is null you have just introduced a bug. Fairly sure that's not the case but just calling it out that undefined !== null and to be careful with nullish. Anyways, if I'm reading this code and it doesn't make sense why someMeaningfulName could be nullable, we could increase the code to improve readability: const someMeaningfulName = characters[i - 1]; if (someMeaningfulName == null) { // Some meaningful reason as to why null is being thrown out here return; } if (mouseY < someMeaningfulName.handle.position.y) That said, the last one might be overkill if it's obvious and in that case you can go back to the previous option. Anyways, that's what I would put as my code review comment if I saw this.