d = {'hello':'abc'}
d.get('hello','default_val');
Above is python. How to do this in javascript? I want to be able to set a default value if no key found.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You have (at least) four/five options:
In modern environments, you’d probably use the nullish coalescing operator (
??):If
obj.keyresults inundefinedornull,"default"is used instead; ifobj.keyresults in for any other value, that value is used (including various falsy values like"").In obsolete environments that don’t have
??, you can use the curiously-powerful||operator:If
obj.keyresults in any falsy value (including""), that will use"default"instead; otherwise, it’ll use the value. Where you can, you’ll generally want to use??instead of||because it more accurately tests for a "missing" value.This is now obsolete,
??handles this case.For situations where||isn’t applicable, there’s theinoperator:intells us whether an object has a property with the given key. Note the key is a string (property names are strings or Symbols; if you were using a Symbol, you’d know). So ifobj.keymay be validly0, you’d want to use this rather than #1 above.in(andobj.key) will find a key if it’s in the object or the object’s prototype chain. If you just want to check the object itself and not its prototype chain, in modern environments you can useObject.hasOwn:In obsolete environments without
hasOwn, you can use a polyfill, or usehasOwnProperty(but beware the object can have its own version ofhasOwnPropertythat may not tell the truth):If you don’t want to exclude
null, you can specifically check forundefined:That will use the default if
objdoesn’t have that property or if it has the property, but the property’s value isundefined.