DEV Community

loading...
Cover image for Tips to create a constants file in Javascript

Tips to create a constants file in Javascript

Edwin Wong
Write code for human.
・1 min read

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',
]

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')

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',
}

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',    
// }

For loop through the object

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

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

Thanks you!

Discussion (0)