DEV Community

Cover image for Tips to create a constants file in Javascript
Edwin Wong
Edwin Wong

Posted on

Tips to create a constants file in Javascript

It shouldn't be difficult to just create a constants file and keep all your value in one place, so the tips how to define the const value is something I want to share about.

Let's see the example

// constants.js

const paymentMethods = [
  {
    key: 'STRIPE',
    value: 1,
    title: 'Stripe Payment', 
  },
  {
    key: 'PAYPAL',
    value: 2,
    title: 'Paypal Payment',    
  },
  {
    key: 'AMAZON_PAYMENT',
    value: 3,
    title: 'Amazon Payment',    
  }
]

const shippingMethods = [
  'SKYNET',
  'GDEX',
  'DHL',
  'UPS',
]
Enter fullscreen mode Exit fullscreen mode

Nothing is wrong with the example approach. It works fine and most of the developer will do the same like this. However, it can be a little bit hard to access particular value you want e.g access the amazon payment method object.

I believe you probably will do something like this.

paymentMethods.find(method => method.key === 'AMAZON_PAYMENT')
Enter fullscreen mode Exit fullscreen mode

Actually, there is a another way...

Store in key value object instead of array

// constants.js

const paymentMethods = {
  STRIPE: {
    key: 'STRIPE',
    value: 1,
    title: 'Stripe Payment', 
  },
  PAYPAL: {
    key: 'PAYPAL',
    value: 2,
    title: 'Paypal Payment',    
  },
  AMAZON_PAYMENT: {
    key: 'AMAZON_PAYMENT',
    value: 3,
    title: 'Amazon Payment',    
  }
}

const shippingMethods = {
  SKYNET: 'SKYNET',
  GDEX: 'GDEX',
  DHL: 'DHL',
  UPS: 'UPS',
}
Enter fullscreen mode Exit fullscreen mode

Store it as object is good for direct access particular value you need. Sometimes you just need list few options rather than all.

paymentMethods.AMAZON_PAYMENT

// {
//    key: 'AMAZON_PAYMENT',
//    value: 3,
//    title: 'Amazon Payment',    
// }

Enter fullscreen mode Exit fullscreen mode

For loop through the object

Object.keys(paymentMethods).map(key => {
  console.log(paymentMethods[key])
})
Enter fullscreen mode Exit fullscreen mode

That's it! Feel free to comment if there is better way~

Thanks you!

Top comments (0)