What's the equivalent of .get in javascript?

Question:

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.

Asked By: TIMEX

||

Answers:

You have (at least) four/five options:

  1. In modern environments, you’d probably use the nullish coalescing operator (??):

    x = obj.key ?? "default";
    

    If obj.key results in undefined or null, "default" is used instead; if obj.key results 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:

    x = obj.key || "default";
    

    If obj.key results 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.

  2. This is now obsolete, ?? handles this case. For situations where || isn’t applicable, there’s the in operator:

    x = "key" in obj ? obj.key : "default";
    

    in tells 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 if obj.key may be validly 0, you’d want to use this rather than #1 above.

  3. in (and obj.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 use Object.hasOwn:

    x = Object.hasOwn(obj, "key") ? obj.key : "default";
    

    In obsolete environments without hasOwn, you can use a polyfill, or use hasOwnProperty (but beware the object can have its own version of hasOwnProperty that may not tell the truth):

    x = obj.hasOwnProperty("key") ? obj.key : "default";
    
  4. If you don’t want to exclude null, you can specifically check for undefined:

    x = typeof obj.key !== "undefined" ? obj.key : "default";
    

    That will use the default if obj doesn’t have that property or if it has the property, but the property’s value is undefined.

Answered By: T.J. Crowder

Javascript’s logical OR operator is short-circuiting. You can do:

d["hello"] || "default_val";
Answered By: Frédéric Hamidi

What about:

var d = {'hello':'abc'};
var helloVar = d.hello ? d.hello : 'default_val';
Answered By: cutsoy

Using destructuring assignment:

const { hello = 'default_val' } = d
Answered By: jsuth
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.