Reputation: 33
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
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.
debugger
statement above the line of code you're interested in. This sets a breakpoint.node inspect <filename>
c
or cont
into the command lineYou're now here:
> 3 debugger
4 if (typeof ticker === undefined) {
5 ticker = body
debug> _
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
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:
node --inspect-brk <filename>
chrome://inspect
Open dedicated devTools for node
Chrome's interface allows you to highlight or hover over variables and expressions to see their value.
Upvotes: 0
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