最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set a default value for const? - Stack Overflow

programmeradmin1浏览0评论

I got a const in meteor containing color and text variables:

const exampleTemplate = (text, color) => ('
   Hello, this is your text:
   ${text}.
   I hope you liked it. And here es your color:
   <span style="color: ${color}">Boom, here she is.</span>
');

const defaultColor = '#123456';
const firstColor = '#876543';
const secondColor = '#295736';

return exampleTemplate('I am a text example', defaultColor);

How can I define defaultColor as default if no other var is set? I have found this thread but I am not able to adopt its markup. I want to use defaultColor if the const color is null, false, 0, NaN or "".

I got a const in meteor containing color and text variables:

const exampleTemplate = (text, color) => ('
   Hello, this is your text:
   ${text}.
   I hope you liked it. And here es your color:
   <span style="color: ${color}">Boom, here she is.</span>
');

const defaultColor = '#123456';
const firstColor = '#876543';
const secondColor = '#295736';

return exampleTemplate('I am a text example', defaultColor);

How can I define defaultColor as default if no other var is set? I have found this thread but I am not able to adopt its markup. I want to use defaultColor if the const color is null, false, 0, NaN or "".

Share Improve this question edited May 23, 2017 at 12:22 CommunityBot 11 silver badge asked Jul 17, 2016 at 20:11 Marian RickMarian Rick 3,4555 gold badges34 silver badges69 bronze badges 3
  • 1 const exampleTemplate = (text, color=defaultColor) is best practice - not sure why it would be NAN, "", or false - the above case tests if not passed - you would have to check for these in the code - and also your template literal is incorrect - should be surrounded by back ticks unless Meteor uses a different templating engine - but assume this is es2015 syntax – markyph Commented Jul 17, 2016 at 20:17
  • "I am not able to adopt its markup" - just use …${ color || defaultColor }…. – Bergi Commented Jul 17, 2016 at 20:37
  • color is not a const??? It's a function parameter (of an arrow function stored in a const exampleTemplate variable) and behaves just like a var. – Bergi Commented Jul 17, 2016 at 20:38
Add a ment  | 

1 Answer 1

Reset to default 3

You're looking for Default Parameters.

const exampleTemplate = (text, color = defaultColor) => ('
');

You'll still need to do some type-checking for all of the conditions you mentioned though.

发布评论

评论列表(0)

  1. 暂无评论