简体   繁体   中英

|| operator not working as expected in EJS

I have this EJS code:

<link rel="stylesheet" type="text/css" href="/public/stylesheets/<%= css || 'default' %>.css" />

I thought that, when css was undefined , this would evaluate to "/public/stylesheets/default.css" , but instead it throws the error

css is not defined

Why? Is this a quirk of EJS, or am I misunderstanding something?

As VLAZ says:

It says that css is not defined rather than undefined . Two different concepts. If it's not defined, it's never declared and/or cannot be reached from the current and enclosing scopes. undefined means it's declared but no value is assigned to it.

I was able to solve my problem using customcommander 's solution:

Rather than

css || 'default'

which throws an error, use

typeof css === 'undefined' ? 'default' : css

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM