35

I was looking for a way to check if an object is a FormData instance, similarly to Array.isArray()

4
  • what is the question here? Commented Sep 11, 2017 at 0:04
  • Possible duplicate of What is the instanceof operator in JavaScript? Commented Sep 11, 2017 at 0:05
  • @hackerrdave how to detect if a JavaScript object is an instance of FormData Commented Sep 11, 2017 at 0:05
  • 1
    @km6—then perhaps that question should be in the text of your question somewhere. Commented Sep 11, 2017 at 0:55

2 Answers 2

67

Use instanceof

For example:

let formData = new FormData()
let time = new Date()

console.log("statement: formData is a FormData instance", formData instanceof FormData) // statement is true
console.log("statement: time is a FormData instance", time instanceof FormData) // statment is false

Source

Sign up to request clarification or add additional context in comments.

2 Comments

The reason there's an isArray mehtod is that instanceof does not work across frames (or global environments) where the constructor is in one environment but the object was created in the other. You seem to have dismissed instanceof in your OP, then post an answer using it. What's the point?
@RobG The main point is that instead of implying that my question was a duplicate of another one regarding the usage of instanceof, it should have been presented as an answer explaining how instanceof could solve my problem - which is exactly what I did in my own response. At the time of posting, I wasn't aware of instanceof, and that was the message I intended to convey in my original post. I didn't dismissinstanceof.
0

Here is the best alternative to instanceof. Unlike instanceof this works even if the FormData object was instantiated in another global environment such as a different window or frame:

function isFormData(value) {
    try {
        var test = (new FormData).has,// Throws in old browsers
            isFormData = test.call(value,0) || true;// Throws if not a FormData instance
    }
    catch(e) {
        // if browser is too old, use Object.prototype.toString test
        isFormData = !test && {}.toString.call(value)=='[object FormData]'
    }
    return isFormData
}

This function works because FormData.prototype.has will throw if it's called on any value that isn't a FormData object. A Object.prototype.toString test is used as a backup if browser is too old. The Object.prototype.toString test by itself is one of the best tests that there is as well if you're looking for more brevity in your code and cross browser compatibility.

This answer is similar to Bergi's answer on the question How to reliably check an object is an EcmaScript 6 Map/Set?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.