0

My code

console.log('Starting app');

const fs = require('fs');
const os = require('os');
const _ = require('lodash');

const notes = require('./notes.js');

var command = process.argv[2];
console.log(command);


if (Comment = 'add') {
    console.log('adding new note');
  } else if (command = 'list') {
    console.log('listing all notes');
  } else {
    console.log('command not recognized');
  }

When I run

 node app.js list

I got

Starting app
Starting node.js
list
adding new note

What is wrong with my else if statement?

str
  • 42,689
  • 17
  • 109
  • 127
Richard Rublev
  • 7,718
  • 16
  • 77
  • 121
  • `Comment = 'add'` is not a comparison, it is an assignment. Its value is the value of `Comment` after the assignment (i.e. `'add'`) which is never false. Read about the [JavaScript operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators) – axiac Mar 22 '20 at 09:42
  • `if (Comment = 'add')` -> `if (command == 'add')` –  Mar 22 '20 at 09:43
  • Node.js is not involved in this question. – axiac Mar 22 '20 at 09:44
  • Ok,it is from Node.js book,but javascipt syntax. – Richard Rublev Mar 22 '20 at 09:45

1 Answers1

0

= is the assignment operator. You're assigning 'add' to Comment, and then checking if this value evaluates to true in a boolean context, which it of course does. You should use the === operator:

if (Comment === 'add') {
    // Here-^

Also Comment is not declared anywhere, which will result in ReferenceError and crash your process.

Tsvetan Ganev
  • 8,246
  • 4
  • 26
  • 43
Mureinik
  • 297,002
  • 52
  • 306
  • 350