rock3rd
rock3rd

Reputation: 9

How do you add numerical values of variables rather than the numbers in JS?

VERY new, barely understand functions.

Here is an example of my issue:

        function getx() {
            x = 3;
        }

        function gety() {
            y = 2;
        }

        getx();
        gety();

        document.write("The sum of x and y is " + x + y); 

OUTPUT: The sum of x and y is 32

I would like to know how I can make it so x + y = 5 instead of 32. Obviously 3 + 2 isn't 32, can someone explain to me how I might output the right answer?

Upvotes: 0

Views: 35

Answers (2)

A Franklin
A Franklin

Reputation: 121

Your functions getx() and gety() aren’t returning any values because you don’t have a return statement.

By calling the functions the way you do, you are creating two global variables: x and y, and initializing the to 3 and 2, respectively.

You should avoid using global variables in this capacity. Your global variables (or functions) can overwrite window variables (or functions). Any function, including the window object, can overwrite your global variables and functions. Your variables should be declared with var instead.

Unless specificied, js variables are not strongly typed, And since you are using the concatenation operator before adding the variables together, it sees them as a string and this is why your concatenation is putting 3 and 2 together.

If you change your code to something like this, it should accomplish what you’re trying to achieve.

function getx() {
    var x = 3; 
    return x;
}

function gety() {
    var y = 2; 
    return y;
}

document.write("The sum of x and y is " + (gety() + getx()));

Upvotes: 0

Ele
Ele

Reputation: 33736

You're concatenating the string with x before the add operation. So, you need to wrap your Math operation with parentheses in order to avoid string concatenation.

function getx() {
  x = 3;
}

function gety() {
  y = 2;
}

getx();
gety();

document.write("The sum of x and y is " + (x + y));

Upvotes: 2

Related Questions