-1

I'm new at learning javascript. I am trying to create a function that calculates something, and then stores the end result of the calculation in a global variable.

I am clearly doing something wrong because it is writing the entire code of the function to the document, instead of just writing the result.

 var myNumbers = function myCalculation () {
        var myCalc1 = 4 + 6;
        var myCalc2 = myCalc1 + 100;
        var myCalc3 = myCalc2 + 20;
        return myCalc3
}

document.write(myNumbers);
Shtarley
  • 313
  • 9
  • 22

3 Answers3

3

myNumbers is a reference to a function, not the result of the call to that function.

I think you mean:

function myCalculation () {
        var myCalc1 = 4 + 6;
        var myCalc2 = myCalc1 + 100;
        var myCalc3 = myCalc2 + 20;
        return myCalc3
}

var myNumbers = myCalculation();

document.write(myNumbers);

What is the difference between a function call and function reference?

kmoser
  • 8,780
  • 3
  • 24
  • 40
1

You can do this various ways. But, first you must understand the ways of defining functions in javascript. I am providing two ways here. For more read this and this.

  1. The regular way:
function add(a, b) {
  let c = a + b;
  return c;
}
  1. The function expression way:
let add = function(a, b) {
  let c = a + b;
  return c;
}

You can use any of them declare a function, though there's some difference in them. But, for your usecase, it won't be problem.

So, you can declare myCalculation as follows:

function myCalculation () {
    var myCalc1 = 4 + 6;
    var myCalc2 = myCalc1 + 100;
    var myCalc3 = myCalc2 + 20;
    return myCalc3;
}

or

let myCalculation = function() {
    var myCalc1 = 4 + 6;
    var myCalc2 = myCalc1 + 100;
    var myCalc3 = myCalc2 + 20;
    return myCalc3;
}

Then, you can do:

let myNumbers = myCalculation();
document.write(myNumbers);

And again there's another way, you can do this without creating myCalculation function, by using immediate call to anonymous function(note: this is created using function expression, read the links I've provided):

let myNumbers = (function myCalculation() {
    var myCalc1 = 4 + 6;
    var myCalc2 = myCalc1 + 100;
    var myCalc3 = myCalc2 + 20;
    return myCalc3;
})();

// and then
document.write(myNumbers);

You should whatever fits your situation...

reyad
  • 1,392
  • 2
  • 7
  • 12
0

End result store by calling the myCalculation() and result automatically store in the global variable.

var myNumbers = myCalculation();

function myCalculation () {
    var myCalc1 = 4 + 6;
    var myCalc2 = myCalc1 + 100;
    var myCalc3 = myCalc2 + 20;
    return myCalc3
}

document.write(myNumbers);
Safyan Yaqoob
  • 444
  • 3
  • 11