Christoph
Christoph

Reputation: 21

How do I keep track of a variable's value when it's passed into a function?

Does JavaScript come with a way to keep track of a variable's identity when it's passed into a function? For example:

var dog = 0;

function dogStuff(animal){
  animal = animal++;
}

In this example I would like to make dog == 1 by passing dog into the function:

dogStuff(dog);

such that

console.log(dog);

would print 1. People have marked this as duplicate to a couple of other questions, but those are a bit too complex for me, a beginner, to understand. I need some responses that assume I have little to no knowledge of JS.

Upvotes: 1

Views: 1473

Answers (2)

Jonathan Lam
Jonathan Lam

Reputation: 17351

First things first: the line animal = animal++ won't do anything because it is a postfix increment. Either just do animal++ or ++animal to increment it.


Nope, dog will not be changed. JavaScript passes primitives by value (Thanks @ASDFGerte for the correction).

var dog = 0;
function dogStuff(animal) {
  animal++;
}
dogStuff(dog);
console.log(dog);  // prints 0

What you want to do (probably) is something similar to what @alfasin mentioned: return the updated value of dog.

var dog = 0;
function dogStuff(animal) {
  animal++;
  return animal;
}
dog = dogStuff(dog);
console.log(dog);  // prints 1

However, if you pass an object and reassign its properties, the original object will be modified (almost like pass by reference):

var dog = { age: 0 };
function incrementAge(animal) {
  animal.age++;
}
incrementAge(dog);
console.log(dog.age);  // prints 1

edit: If you want to assign multiple variables on return, one possible way to do it is to return an array of variables, which can then be assigned with deconstructed assignment:

var dog = 0;
var cat = 52;
function incrementTwoAnimals(animal1, animal2) {
  animal1++;
  animal2++;
  return [animal1, animal2];
}
[dog, cat] = incrementTwoAnimals(dog, cat);  // deconstructed assignment
console.log(dog, cat);  // prints 1, 53

Upvotes: 1

Victoria Ruiz
Victoria Ruiz

Reputation: 5013

The function you posted did not return any value that you can use outside of it. So you need to add: return. This means that when you run dogStuff(...) it will actually return a value. And then you save that value in a variable, which can be the same dog that you passed as a parameter.

Here's the full code:

var dog = 0;

function dogStuff(animal){
   return animal++;
}

dog = dogStuff(dog);

Upvotes: 1

Related Questions