I couldnt call a value from other function - javascript

The js code has 3 functions. I want to call values from the 2 functions and execute them in the 3rd function.
function first() {
var x = 2
var y = 3
var z = x * y
}
first()
function second() {
first();
var z;
var a = z - 1
}
second()
function third() {
first();
second();
var a
var z
var ans = a * z
console.log(ans);
document.getElementById("ans_html").innerHTML = precision(ans);
}
third()
<div id="ans_html"></div>
The expected outcome was 30.
But the output was "NaN".

In most languages, including JS, variables have "scope" (mdn). If you want to share data between function's, you can either
1) return values (mdn),
function first() {
var x = 2
var y = 3
return x * y;
}
function second() {
let z = first();
return z - 1
}
function third() {
let z = first();
let a = second();
var ans = a * z
console.log(ans);
}
third();
2), less conventionally, modify a param obj since they're are passed by ref.
let func = param => {
param.x = 3;
param.y = 4;
};
let a = {};
func(a);
console.log(a);

You will need to either create global variables which is considered a bad practice, or pass values around as parameters.
Global variables:
var a
var x
var y
var z
function first() {
x = 2
y = 3
z = x * y
}
function second() {
a = z - 1
}
function third() {
first()
second()
let ans = a * z
console.log(ans);
}
Passing Parameters:
function first(x, y) {
return x * y
}
function second(z) {
return z - 1
}
function third() {
let x = 2
let y = 3
let z = first(x, y)
let a = second(z)
let ans = a * z
console.log(ans);
}
Judging based on your code, you likely should take a look into how JavaScript scopes variables based on using the keyword var vs let. I hope this helps!

You have two major issues:
Your variables a and z are not global variables. They are defined within the function itself so you cannot access those variables outside of that scope (see this)
I would not fix your code to adhere to the first issue. You don't need global variables here, you just need to return the result so you can call your functions later. In the long run, I would assume you want to add arguments to your functions, but the below is an example of how to do what you're trying to accomplish by simply returning the result in your functions.
NOTE I don't know if you have a custom precision function or what. So, I added an empty function that just returns the input. You can probably remove this.
function precision(num) {
// Insert whatever is in your precision function here...
return num;
}
function first() {
var x = 2
var y = 3
var z = x * y
return z;
}
function second() {
var z = first();
var a = z - 1
return a;
}
function third() {
var a = second();
var z = first();
var ans = a * z
console.log(ans);
document.getElementById("ans_html").innerHTML = precision(ans);
}
third()
<div id="ans_html"></div>

This is not the best design pattern, but if you want to achieve this in this way, the code is going to look like the one below. You need to return the result of the function in order to get it in another function and use it.
function first() {
var x = 2
var y = 3
return x * y
}
function second() {
var z = first()
return z - 1
}
function third() {
var a = first()
var z = second()
var ans = a * z
console.log(ans);
// document.getElementById("ans_html").innerHTML = precision(ans);
}
third()
<div id="ans_html"></div>

Related

How do you add multiple arguments from different functions into one function containing all the parameters?

Is this possible in JavaScript
I am curious, if I set up three parameters in one function, can I pass the arguments independently in three different functions?
For example, if I created a function that calculates three parameters like the one below, can I then just pass an argument for each of these parameters x, y and z in three different functions.
I understand the example code is not a very good example but its the only way I could think up a explanation.
Main function
function mathsCal(x, y, z) {
return (x * y) - z;
}
The three independent functions
function one(x) {
return x = 23;
}
function two(y) {
return x = 19;
}
function three(z) {
return x = 45;
}
You can do something like this for example you have your 3 functions, each of them receive 1 parameter
function num1(param) {
//your code for num1, return a value
return param
}
function num2(param) {
//your code for num2, return a value
return param
}
function num3(param) {
//your code for num3, return a value
return param
}
Then you can call them all inside single function that will receive all 3 parameters needed for num1, num2 and num3
function sumNum(x, y, z) {
var value1 = num1(x);
var value2 = num1(y);
var value3 = num1(z);
return (value1 * value2) + value3;
}
Then call your function with the needed parameters
var result = sumNum(1,2,3)
console.log(result);//your output = 5
Without using JQuery and using the code I got from user "Chris G", I believe this is the best answer to my question. Please leave comments if I have written this wrong so I can correct it.
<button id= "btn">Get Answer</button>
var numVal1 = 2;
var numVal2 = 6;
var numVal3 = 9;
document.getElementById("btn").addEventListener("click", function() {
funcPara(numVal1, numVal2, numVal3);
})
function funcPara(x, y, z) {
num1(x);
num2(y);
num3(z);
}
function num1(para) {
console.log(`num1 = ${para}`);
}
function num2(para) {
console.log(`num2 = ${para}`);
}
function num3(para) {
console.log(`num3 = ${para}`);
}

How to use a specific variable out of three returned variables?

I have got three variables (x,y,z) and I have returned them all. I want to use a specific variable out of the three instead of just using the newest one.
This is to test what I can do for my loading screen which I mentioned in a previous question. I have tried to put the variable in the void to no avail. I have researched this and I haven't found anything.
function inputs(){
var x = 19;
var y = 20;
var z = 21;
return x, y, z;
}
function output(){
console.log(inputs(x));
}
output();
My expected result is that I can log x to my console. My actual result is that it says undefined.
Your input(x) here x is undefined so.
And x,y,z will also always return z. Read more about comma operator
So what you're trying to achieve can be done like this with object.
You can do it like this
function inputs(input){
let obj =
{ x : 19,
y : 20,
z : 21 }
return obj[input]
}
function output(){
console.log(inputs('x'));
}
output();
In ES6 you can do this:
function inputs() {
var x = 19;
var y = 20;
var z = 21;
return {x, y, z};
}
function output() {
console.log(inputs().x);
}
output();
Hope that helps.
Returning x, y, z actually only returns z. What you want is an Object, like let a = {x, y, z}, which you can then access z from using a.z.
You cannot return comma separated values like this:
return x, y, z;
Instead what you can do is return an object:
function inputs(){
var x = 19;
var y = 20;
var z = 21;
return {x: x, y: y, z: z};
}
function output(){
console.log(inputs().x)
}
output()
Hope you understand.

Replace a variable in a function with the value in javascript

I am looking for a way to replace a variable in a function with its actual value. I am going to convert this function into a string and send via a HTTP request and thus need to convert the variables inside the function with their values.
let x = Math.random();
let funcString = function () {
let y = x + 10;
return y;
}.toString();
// Send funcString as a parameter
For eg. in the above code if I send funcString as it is, whoever receiving it will have no idea what is the value of x.
Since I am ultimately sending a string I would like to send
"function () {let y = 0.53 + 10; return y;}" (assuming
Math.random() produced 0.53 at runtime).
Is there any way to do this?
I am doing this in a nodejs project so a npm module would be fine by me too.
Well if you are returning this function as a string, just use String#replace() method to replace x occurrence with its value.
This is how you should use it:
funcString.replace('x', x)
Demo:
let x = Math.random();
let funcString = function () {
let y = x + 10;
return y;
}.toString();
console.log(funcString.replace('x', x));
Edit:
If your variable has many occurrences and can be part of other variables just use a regex with replace method.
funcString.replace(/\bx\b/g, x)
Demo:
let x = Math.random();
let funcString = function () {
let y = x + 10;
let fix ='true';
let z = x * 2;
return y;
}.toString();
console.log(funcString.replace(/\bx\b/g, x));
use replace with regex, g will search all x-es
let x = Math.random();
let funcString = function () {
let y = x + 10;
let a = x + 10;
let b = x + 10;
return y;
}.toString().replace(/x/g, x);
console.log(funcString);

Variable hoisting examples [duplicate]

This question already has answers here:
Surprised that global variable has undefined value in JavaScript
(6 answers)
Closed 7 years ago.
Hi I have a snippet of code. I am confused about change of value x1 when I remove non-related part of same code. I searched about it and I came to know that it has to do with hoisting. But the value x1 is still unclear even with hoisting concept for me. Can someone please make me clear on this?
var x = 10;
function main() {
document.write("<br>x1 is " + x);
x = 20;
if (x > 0) {
var x = 30;
document.write("<br>x2 is " + x);
}
var x = 40;
var f = function(x) {
document.write("<br>x3 is " + x);
}
f(50);
}
main();
The output of this code is:
x1 is undefined
x2 is 30
x3 is 50
If I change this code to:
var x = 10;
function main() {
document.write("<br>x1 is " + x);
}
main();
The output is:
x1 is 10
So what is happening here is a common pitfall.
The simplest way to put this is. When you set var x = 30 inside your main function, you are actually redefining the scope that var x = 10 had for use inside this function. This has to do with how Javascript executes and scope.
By defining x inside the function, your scope for x has changed. Below is an example of what I mean and a version of your code that works
Example:
var test = 'test';
function run(){
console.log(test);
var test=1;
}
Your Code Updated:
var x = 10;
function main() {
console.log("<br>x1 is " + x);
x = 20;
if (x > 0) {
x = 30;
console.log("<br>x2 is " + x);
}
x = 40;
var f = function(x) { console.log("<br>x3 is " + x); }
f(50);
}
main();
Good question btw.
Since this is somewhat of a very interesting scope of how Javascript executes, consider the following code and its outputs to get the full idea
var test = 'test';
function run(){
console.log(test);
test=1;
console.log(test);
var test=2;
console.log(test);
}
console.log(test);
run();
console.log(test);
Very interesting to see how this reacts.
All variable and function declarations get "hoisted" or moved to the top of their scope. The undefined value for x is caused because the var x statement gets moved up to the top of main however the assignment = 30 does not.
So, your code will read more like this:
var x = 10; // x is 10
function main() {
var x; // x declaration is "hoisted"
document.write("<br>x1 is" + x); // x1 is undefined
x = 20; // x is 20
if (x > 0) {
x = 30; // x is 30
document.write("<br>x2 is" + x);// x2 is 30
}
x = 40; // x is 40
var f = function(x) { // x is 50
document.write("<br>x3 is" + x);// x3 is 50
}
f(50);
}
main();
You can read more about Hoisting here: JavaScript Scoping and Hoisting

Passing arguments down to nested functions Google Maps v3

Sorry for the newb question here, but Im new to javascript. Ideally I would like to call for myLoop(latLong); but unless I make the variables outside of the function, I can't seem to have .setPosition() recognize the variable.
var x = 0;
var y = 0;
var z = 0;
var v = 0;
function xy(a,b,c,d) {
var longDistance = Math.abs(a-d);
var longTime = longDistance/0.1*0.5;
var latDistance = b-c;
var latRate = latDistance/longTime*0.5;
x = a; //origin long
y = b; //oringin lat
z = latRate;
w = d; //destination long
v = c; //destination lat
}
function myLoop () {
setTimeout(function () {
var latLong = new google.maps.LatLng(y,x);
marker.setPosition(latLong);
x = x + 0.1;
y = y - z;
if (x < w && y < v) {
myLoop();
} else {
alert('finished');
}
}, 0.5)
}
xy(-118,33,40,-73);
myLoop();
You simply need to pass the latLong variable into the myLoop() function recursively.
To do this, you can create your first latLong variable outside of the function, then call the function (passing in the first latLong variable), then within the latLong function, check for your conditions, and if you need to call the myLoop function again, update the latLong variable and then call the myLoop function again.
Here is what your recursive code would look like:
var x = 0;
var y = 0;
var z = 0;
var v = 0;
// Your first latLong
var latLong = new google.maps.LatLng(y,x);
function xy(a,b,c,d) {
// ...
}
// Pass in the latLong variable
function myLoop (latLong) {
setTimeout(function () {
marker.setPosition(latLong);
x = x + 0.1;
y = y - z;
if (x < w && y < v) {
// now create a new latLong, and pass it
// back into this function recursively
latLong = new google.maps.LatLng(y,x);
myLoop(latLong);
} else {
alert('finished');
}
}, 0.5)
}
xy(-118,33,40,-73);
// Now call the myLoop function to get the recursion started
myLoop(latLong);
Alternatively, you can wrap all the code up into one function
Using the revealing module pattern, you can wrap up all your loop functionality in one place (within a function object called latLongGenerator), allowing for a nice separation in your code logic, but still giving you a clean interface to use. The restructured "revealing module" code would look like this:
var latLongGenerator = (function () {
var x = 0;
var y = 0;
var z = 0;
var v = 0;
var latLong;
function setXY(a,b,c,d) {
var longDistance = Math.abs(a-d);
var longTime = longDistance/0.1*0.5;
var latDistance = b-c;
var latRate = latDistance/longTime*0.5;
x = a; //origin long
y = b; //oringin lat
z = latRate;
w = d; //destination long
v = c; //destination lat
// pass in the initial latLong to myLoop(latLong) from here
latLong = new google.maps.LatLng(y,x);
myLoop(latLong);
}
// This is the only function that will
// be exposed publicly on this function
// Example usage: latLongGenerator.startLoopWith(0,0,0,0);
function startLoopWith(a,b,c,d){
setXY(a,b,c,d);
}
function myLoop (latLong) {
setTimeout(function () {
marker.setPosition(latLong);
x = x + 0.1;
y = y - z;
if (x < w && y < v) {
// recursively call the loop from here
latLong = new google.maps.LatLng(y,x);
myLoop(latLong);
} else {
alert('finished');
}
}, 0.5);
}
return {
startLoopWith:startLoopWith
};
})();
// Finally, you can start your loop by passing in
// your initial values to latLongGenerator.startLoopWith(...)
latLongGenerator.startLoopWith(-118,33,40,-73);
This structure gives you a clean way of encapsulating all your calculation logic, while also giving you a nice, clean entry point. Using this new refactor, you can get your loop started with one line:
latLongGenerator.startLoopWith(-118,33,40,-73);
I haven't tested this code, but it should help you get on the right track.
Hope this helps!

Categories