Warm tip: This article is reproduced from stackoverflow.com, please click
console javascript lookup object

Can a JavaScript object return a value AND console log?

发布于 2020-04-19 09:42:52

I have an object that looks something like this:

const CONVERT = {
  a: 1,
  b: 2,
  c: 100,
};

and I'm using it like so:

let x = 'a';
// some logic that may change x
const value = CONVERT[x];

Say I know that when x = 'c' this is an error condition. I would like to console.error( 'value clamped at the limit of 100' ) when x = 'c'.

Is there an elegant way to do this inside the CONVERT object assignment? I was hoping I could do something like this:

const CONVERT = {
  a: 1,
  b: 2,
  c: ( ()=> { console.error( 'value clamped at the limit of 100' ); return 100; )(),
};

...but that doesn't console.error the message when CONVERT['c'] is called, Instead it does so immediately when the CONVERT object is instantiated.

The only alternative I can think of is:

let x = 'a';
// some logic that may change x
const value = CONVERT[x];
if( value === 100 ) {
  console.error( 'value clamped at the limit of 100' );
}

but that means that no matter where I use CONVERT, I now need to do this extra if-check so that I can console.error the desired message. I'd like to avoid having to do this if-check completely if I know that x is not equal to 'c'.

My other choice is to get rid of the CONVERT object and instead hard code an if-else or switch like this:

let value;
if( x === 'a' ) {
  value = 1;
} else if( x === 'b' ) {
  value = 2;
} else if( x === 'c' ) {
  value = 100;
  console.error( 'value clamped at the limit of ', value );
}

This too, I'm hoping I can bypass with the use of a lookup-object instead.

Questioner
MarekKnows.com
Viewed
31
Nick Parsons 2020-02-05 10:09

You seem like you might be after a getter, which is a function which can be executed on property access. The value you return from the getter is the value which CONVERT['c'] is evaluated to:

const CONVERT = {
  a: 1,
  b: 2,
  get c() { 
    console.error( 'value clamped at the limit of 100' ); 
    return 100; 
  }
};


let x = 'a';
x = 'c'; // some logic that may change x
const value = CONVERT[x];
console.log(value);