Hey there @kusha.kpr! Totally understand that frustrating scenario with undefined objects in JavaScript,been there myself!
What @joe-elmoufak suggested would also work but always having something up your sleeve doesn’t hurt right?
You’re spot on: when you do just typeof me.onChange === 'function' and me is undefined, JavaScript will indeed “freak out” and throw an error. The safest and most modern pattern to handle this involves optional chaining (?.):
if (me?.onChange instanceof Function) {
me.onChange(str);
}
That optional chaining (?.) is super handy here. It’ll gracefully return undefined if me doesn’t exist (or is null), and then the instanceof Function check determines if the method is actually a function. It’s wonderfully clean, truly modern, and prevents those unexpected crashes.
Hope the solution provides you the help you needed!