Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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.jsconstpaymentMethods=[{key:'STRIPE',value:1,title:'Stripe Payment',},{key:'PAYPAL',value:2,title:'Paypal Payment',},{key:'AMAZON_PAYMENT',value:3,title:'Amazon Payment',}]constshippingMethods=['SKYNET','GDEX','DHL','UPS',]
Enter fullscreen modeExit 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 modeExit fullscreen mode

Actually, there is a another way...

Store in key value object instead of array

// constants.jsconstpaymentMethods={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',}}constshippingMethods={SKYNET:'SKYNET',GDEX:'GDEX',DHL:'DHL',UPS:'UPS',}
Enter fullscreen modeExit 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 modeExit fullscreen mode

For loop through the object

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

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

Thanks you!

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Coffee addict · Thinker · Software Engineer
  • Location
    Kuala Lumpur, Malaysia
  • Joined

More fromEdwin Wong

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp