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

javascript - Or operator not working in IF statement Node.js - Stack Overflow

programmeradmin3浏览0评论

I originally had a route in node.js that stated this:

If the req.url === something or something or something or something, do this, else, do that.

The problem is that the else statement never got executed even though the if condition was not met. Only the if statement executes no matter what

I have broken down my route to bare minimum trying to figure out the problem. I simplified it to this:

app.get('/test', function(req,res) {

        var category = 'stupid3';

        if(category === 'stupid' || 'stupid2') {

            res.end('yup');

        } else {

            res.end('nope');

        }

});

What am I doing wrong?

Why wont the else statement execute?

I originally had a route in node.js that stated this:

If the req.url === something or something or something or something, do this, else, do that.

The problem is that the else statement never got executed even though the if condition was not met. Only the if statement executes no matter what

I have broken down my route to bare minimum trying to figure out the problem. I simplified it to this:

app.get('/test', function(req,res) {

        var category = 'stupid3';

        if(category === 'stupid' || 'stupid2') {

            res.end('yup');

        } else {

            res.end('nope');

        }

});

What am I doing wrong?

Why wont the else statement execute?

Share Improve this question asked Oct 12, 2015 at 20:26 Wee WeeWee Wee 1971 gold badge4 silver badges12 bronze badges 2
  • 1 javascript - Check variable equality against a list of values - Stack Overflow – user202729 Commented Jul 30, 2018 at 6:58
  • You could get rid of the problem entirely by using ["stupid", "stupid2"].includes(category) as the condition (see this answer). – bb216b3acfd8f72cbc8f899d4d6963 Commented Jul 5, 2019 at 19:19
Add a ment  | 

2 Answers 2

Reset to default 11

You're using it incorrectly.

category === 'stupid' || category === 'stupid2'

Your version is effectively...

 (category === 'stupid') || 'stupid2'

...so because a non-empty string is "truthy", the RHS will always cause the || to pass.

the else statement is never executed because your if condition always returns true..

if (category === 'stupid' || 'stupid2') {

the second part of the condition i.e. after the || operator is 'stupid2 which is a truthy value

发布评论

评论列表(0)

  1. 暂无评论