Search code examples
javascriptnode.jsdictionaryconstants

Strange behavior with dictionary using constants


I am defining two dictionaries using two different methods and they behave in different way. Can someone explain why?

const PORTRAIT = 'PRT';
const LANDSCAPE = 'LND';
const SQUARE = 'SQ';

const good_image_ratios = {}
good_image_ratios[LANDSCAPE] = '16_9_';
good_image_ratios[PORTRAIT] = '3_4_';
good_image_ratios[SQUARE] = '1_1_';

const wrong_image_ratios = { LANDSCAPE: '16_9_', PORTRAIT: '3_4_', SQUARE : '1_1_'  }

console.log(good_image_ratios);
console.log(wrong_image_ratios);

console.log(good_image_ratios[LANDSCAPE]);
console.log(wrong_image_ratios[LANDSCAPE]);

The output is as follow:

{ LND: '16_9_', PRT: '3_4_', SQ: '1_1_' }
{ LANDSCAPE: '16_9_', PORTRAIT: '3_4_', SQUARE: '1_1_' }
16_9_
undefined

Why is this?


Solution

  • Use dynamic object property syntax with square brackets, otherwise the property names are interpreted as strings, not variable names:

    const PORTRAIT = 'PRT';
    const LANDSCAPE = 'LND';
    const SQUARE = 'SQ';
    
    const good_image_ratios = {}
    good_image_ratios[LANDSCAPE] = '16_9_';
    good_image_ratios[PORTRAIT] = '3_4_';
    good_image_ratios[SQUARE] = '1_1_';
    
    const wrong_image_ratios = { [LANDSCAPE]: '16_9_', [PORTRAIT]: '3_4_', [SQUARE] : '1_1_'  }
    
    console.log(good_image_ratios);
    console.log(wrong_image_ratios);
    
    console.log(good_image_ratios[LANDSCAPE]);
    console.log(wrong_image_ratios[LANDSCAPE]);