Tyler Dillen
Tyler Dillen

Reputation: 3

How to increment a variable, then save said variable, then continue to add on to it?

I'm working on a small discord bot in JS that all I need it to do is when a certain command is said, it will increment a number ( 0 -> 1) then it will remember that it incremented that number so that next time the command is said, it will increase again ( 1 -> 2). Sorry that I'm pretty new to JS but I'm figuring it out bit by bit.

Due to my limited knowledge, all I've tried is just declaring "num" then adding it by one. And then I tried declaring num as 0, once the command (which is "song" for placeholders sake) is said, it increases up to one, then once we say the command again, it resets back to 0, then increases to 1.

if(command === "song") {
    var num = 0
    num = num + 1;
    return message.channel.send(num);
}

I want it to keep incrementing every time the command is said e.x (I say "song", bot says 1, I say "song" again, bot says 2, etc.)

Upvotes: 0

Views: 1579

Answers (3)

Pietro Martinelli
Pietro Martinelli

Reputation: 1906

You should move the num variable initialization away from if body and place it out of the function containing the if, as in the answer by Code Maniac.

EDITED

Merging the original code sample and the code sample provided by Code Maniac, you can try something like this:

function init() {
  var num = 0;
  return function(command) {
    console.log(command);
    if(command === "song") {
      num = num + 1;
      //return message.channel.send(num); 
      console.log(num);
    }
  }
}

var commandHandler = init();

commandHandler('song');
commandHandler('song');
commandHandler('no-song');
commandHandler('song');
commandHandler('no-song');
commandHandler('song');

Upvotes: 2

Code Maniac
Code Maniac

Reputation: 37755

You need to keep num in outer scope to avoid reset every time.

You can consider below example for understanding

let num = 0 

function command(input){
   if( input === "song") {
        num++;
      } 
  return num
}

console.log(command('song'))
console.log(command('blah'))
console.log(command('song'))

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44135

Simple. First of all, declare num at the top of your JavaScript file, so it's globally accessible:

var num = 0;

Then in your if statement, just use num++:

if (command === "song") {
    num++;
    return message.channel.send(num);
}

(The above syntax is the increment operator, specifically the post-increment operator).

Here's a simplified demonstration:

var num = 0;

function test(command) {
  if (command === "song") {
    num++;
  }
  return num;
}

console.log(test("song"));
console.log(test("not a song"));
console.log(test("song"));

Upvotes: 0

Related Questions