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.
- The regular way:
function add(a, b) {
let c = a + b;
return c;
}
- 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...