AI Takeover
AI Takeover

Reputation: 33

Node js if condition is not working properly

I want to initialize global variable with body of json object. But in my code if is not being executed instead of if, else part of code executes, if console.log(typeof ticker) I get undefined. What appears to be the problem.

var ticker;
request({
    method: 'POST',
    url: 'xyz'
}, (err, res, body) => {

    if (typeof ticker === undefined) {
        ticker = body;
    } else {

        console.log(ticker)
    }
})

Upvotes: 2

Views: 999

Answers (2)

vapurrmaid
vapurrmaid

Reputation: 2307

Marco's answer above is the correct answer. What I'm addressing is the following statement and how you can verify it for yourself:

if condition is not working properly

You can use the debugger to understand your program. Since you're using node, you can verify this right from the command line.

  1. Place a debugger statement above the line of code you're interested in. This sets a breakpoint.
  2. run node inspect <filename>
  3. A REPL opens up in the command shell, starting from line 1 of your file. To arrive at your breakpoint, simply type c or cont into the command line

You're now here:

> 3 debugger
  4 if (typeof ticker === undefined) {
  5 ticker = body
debug> _
  1. You can now run expressions right in the REPL to see how node will evaluate them at runtime:

    debug> typeof ticker
    'undefined'               // aha, there's our programming error
     debug> typeof ticker === undefined
     false
     debug> typeof ticker === 'undefined'  // it works
     true
    
  2. To further verify the flow of your program, enternext in the REPL to see line-by-line where the program flows.

Optionally, you can utilize chrome's interface to debug:

  • run node --inspect-brk <filename>
  • open chrome to chrome://inspect
  • click Open dedicated devTools for node

Chrome's interface allows you to highlight or hover over variables and expressions to see their value.

Upvotes: 0

Marcos Casagrande
Marcos Casagrande

Reputation: 40404

Your condition will always evaluate to false. typeof operator returns a string. So your if condition should be:

typeof ticker === 'undefined'

or

 ticker === undefined

Upvotes: 4

Related Questions