-1

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
  • 38,402
  • 15
  • 99
  • 123
Richard Rublev
  • 6,495
  • 12
  • 58
  • 100
  • `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')` – ChrisG 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

-1

= 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
  • 7,052
  • 2
  • 27
  • 40
Mureinik
  • 277,661
  • 50
  • 283
  • 320