Sam Williams Sam Williams - 22 days ago 9
Javascript Question

If/else statement goes straight to else

My if/else statement goes straight to else and I cant seem to figure out why. Here is my code:

var sentiment = require ('sentiment');
var twitterSentiment;
var geoColor;
var results;
var twit = new twitter({
consumer_key: credentials.consumer_key,
consumer_secret: credentials.consumer_secret,
access_token_key: credentials.access_token_key,
access_token_secret: credentials.access_token_secret
});

twit.stream(
'statuses/filter',
{ 'locations': location },
function(stream) {
stream.on('data', function(tweet) {
console.log(tweet.text);
results = sentiment (tweet.text);
twitterSentiment = results;


//Comparison of Sentiment Scores
if (twitterSentiment == 0) {
geoColor = '#B5B5B5';
}

else if (twitterSentiment < 0) {
geoColor = '#FC0828';
}
else {
geoColor = '#00DE1E';
}

console.log (geoColor);
});
});


This is an example output:

omg yes!!
#00DE1E
Do you think will actually understand? I want to ask mine the same question. Just not sure I'm ready to have that conversation.
#00DE1E
A thing of beauty by:
@youtube
#00DE1E
do you still do this??
#00DE1E


As you can see all the tweets are being identified by only one color; almost as if my
if/else
statement is not implemented correctly?

When I change
console.log (geoColor);
to
console.log (results);
This is my output:

omg yes!!
{ score: 1,
comparative: 0.25,
tokens: [ 'omg', 'yes' ],
words: [ 'yes' ],
positive: [ 'yes' ],
negative: [] }

Do you think will actually understand? I want to ask mine the same question. Just not sure I'm ready to have that conversation.
{ score: 1,
comparative: 0.041666666666666664,
tokens:
[
'do',
'you',
'think',
'will',
'actually',
'understand',
'i',
'want',
'to',
'ask',
'mine',
'the',
'same',
'question',
'just',
'not',
'sure',
'i\'m',
'ready',
'to',
'have',
'that',
'conversation' ],
words: [ 'want' ],
positive: [ 'want' ],
negative: [] }

A thing of beauty by:
@youtube
{ score: 3,
comparative: 0.25,
tokens:
[ 'a',
'thing',
'of',
'beauty',
'by',
'youtube', ],
words: [ 'beauty' ],
positive: [ 'beauty' ],
negative: [] }

do you still do this??
{ score: 0,
comparative: 0,
tokens:
[
'do',
'you',
'still',
'do',
'this' ],
words: [],
positive: [],
negative: [] }


As you can see each tweet has their individual sentiment score of respectively
1,1,3,0
So why is my if/else statement disregarding those numbers?

What can I change in my code so that my if/else statement correctly implements and considers the sentiment score of the tweets? My goal is to output the appropriate color for each tweet.

Answer

You are setting twitterSentiment to the result object and comparing the whole object instead of just the score. Change your code to:

if (twitterSentiment.score == 0) {
    geoColor = '#B5B5B5';
} 

else if (twitterSentiment.score < 0) {
    geoColor = '#FC0828';
} 
else {
   geoColor = '#00DE1E';
}
Comments