passing variables across functions on javascript - javascript

I'm trying to pass variables across functions,
something like
function one() {
var x = 1
}
function two() {
var y = x + 1;
}
alert(y);
Is there a way to do it?
edit:Thanks everyone for being so helpful, but maybe I should have been more specific with my question.

You current way has x and y in the scope of the function, which means the other function doesnt know it exists. Also, its good practice to name functions according to what they do. 3 straightforward ways to do this.
Global
Params
Inline
Set two variables outside of the functions scope that any function can reach.
var x, y;
function assignOne() {
x = 1;
}
function addOne() {
y = x + 1;
}
assignOne();
addOne();
console.log(y);
Pass in a parameter to to the function and return values.
function one() {
return 1;
}
function addOneTo(x) {
return x + 1;
}
const y = addOneTo(one());
console.log(y);
Perform functions inline
var x = null;
function one() {
x = 1;
}
function two() {
return x + 1;
}
one();
const y = two();
console.log(y);

You will need to hoist the scope, by extracting the variable declaration to outside of the functions. That is to say, define x and y outside of the functions. Note that you can still update their values from within the functions. However, don't forget that you'll actually need to invoke both functions as well!
This can be seen in the following:
var x, y;
function one() {
x = 1;
}
function two() {
y = x + 1;
}
one();
two();
console.log(y);

If you really want to get variable declared in one method, return it
function one(){
var x = 1;
return x;
}
function two() {
var x = one();
var y = x + 1;
return y;
}
alert(two());

Seems like you want to have shared state between both functions instead of passing arguments. So, an object oriented pattern seems to be appropriate.
class Thing {
constructor() {
this.x = 1;
}
one() {
return this.x;
}
two() {
return this.x + 1;
}
}
const t = new Thing();
console.log(t.one());
console.log(t.two());

If you want to share variables between functions but don't want to declare them in global scope, you can use a closure like this:
(function() {
var x, y;
function one() {
var x = 1
}
function two() {
var y = x + 1;
}
one();
two();
alert(y);
})();

Related

Why does this JavaScript code return an error?

I know in JavaScript only function declarations are hoisted, which means it should print 30 after running the function sum.
However it says diff is not defined, shouldn't it be hoisted?
sum(10, 20);
diff(10, 20);
function sum(x, y) {
return x + y;
}
let diff = function(x, y) {
return x - y;
}
It's because as you said, only function declarations are hoisted, not function expressions (assigning a nameless function to a variable). Following code works:
sum(10, 20);
diff(10, 20);
function sum(x, y) {
return x + y;
}
function diff(x, y) {
return x - y;
}
To declare diff the way you did, you must lift it to the top of your code:
let diff = function(x, y) {
return x - y;
}
sum(10, 20);
diff(10, 20);
function sum(x, y) {
return x + y;
}
Yes, let and const are hoisted but you cannot access them before the actual declaration is evaluated at runtime.
You are accessing the function before you initialize it.
So this should work,
let diff = function(x, y) {
return x - y;
}
function sum(x, y) {
return x + y;
}
console.log(sum(10, 20));
console.log(diff(10, 20));
let diff will hoist but at the moment when function diff(10, 20); will be called variable diff will not jet be defined with the function.
Google this topic function declaration vs function expression
Because Function Expressions are not hoisted like Function Declarations
Function expressions in JavaScript are
not hoisted, unlike function declarations. You can't use function
expressions before you create them:
console.log(notHoisted) // undefined
// even though the variable name is hoisted, the definition isn't. so it's undefined.
notHoisted(); // TypeError: notHoisted is not a function
var notHoisted = function() {
console.log('bar');
};
https://developer.mozilla.org/en-US/docs/web/JavaScript/Reference/Operators/function#function_expression_hoisting
You will need to use a Function Declaration if you want it to be hoisted.

In JavaScript, is there a way to get closure parameters

I have two file:
//------------a.js--------------
function a(){
return '1'
}
var testCase = {
func(){
return a()
}
}
module.exports = testCase
//------------b.js--------------
var testCase = require('./a.js')
//Can I get closure parameters(function a) that not modify a.js?
Is there a way to get closure parameters In JavaScript? Thank You!
If you mean to return the list of parameters from a closure like get x and y from closure run(x, y) {} which is inside function walk() {} then the below code might help.
function walk() {
function run(x, y) {
return x + y;
}
return run;
}
var fun = walk();
fun.getParameters = function () {
var functionText = this.prototype.constructor.toString();
return functionText
.substring(functionText.indexOf('(') + 1, functionText.indexOf(')'))
.split(',')
.map(x => x.trim());
};
console.log(fun.getParameters());

Why is a global variable (inside function) not identified?

So, I was trying to initialize variables and put a few global variables in my Unity script, but when I run the code, it says that x, y, and z are unknown identifiers. I've been trying to find the answer to this:
function Awake () {
x = 0; //Unity doesn't work with commas
y = 0;
z = 0;
}
function Update () {
if (Input.GetTouch) {
x = x-1;
}
Transform.position = Vector3(x,y,z);
}
The thing with putting the variables outside the function is that they will repeat and act as update.
I'm also new to Unity, and JavaScript.
It looks to me (granted with my limited exposure to unity) like you need to declare your variables at a global level. Try doing something like this:
// declare these variables in the global scope.
var x;
var y;
var z;
function Awake () {
x = 0;
y = 0;
z = 0;
}
function Update () {
if (Input.GetTouch) {
x = x-1;
}
Transform.position = Vector3(x,y,z);
}

How can I pass a variable from function x to function y and a varible from function y to functio x without run the whole function

How can I pass a variable from function x to function y and a varible from function y to function x without run the whole function. For Example below I want to sent the z variable from function two to function one and the y variable from function one to function two but without run the function two, just send the variable value.
function one(x) {
var y;
y = x+1;
}
function two(z) {
z = 9;
var k = y +9;
one(z)
}
Is a way to do that? Or it is not achievable with this way?
This is what you have:
function one(x) {
var y;
y = x+1;
}
function two(z) {
z = 9;
var k = y +9;
one(z)
}
From what I can understand you need to do this:
var z = 9;
function one(x) {
var y;
y = x+1;
}
function two() {
z = 9;
var k = y +9;
one()
}
However, it is extremely difficult to understand what you want to achieve. Can you give a scenario as to where you will use this kind of code?

Assigning arguments to local variables in closure

Here is a currying snippet from javascript patterns:
function add(x, y) {
var oldx = x, oldy = y;
if (typeof oldy === "undefined") { // partial
return function (newy) {
return oldx + newy;
}
}
// full application
return x + y;
}
ref: https://github.com/shichuan/javascript-patterns/blob/master/function-patterns/currying.html
What is the point of local vars oldx and oldy?
The variables oldx and oldy are completely unnecessary here; the code behaves identically without them:
function add(x, y) {
if (typeof y === "undefined") { // partial
return function (y) {
return x + y;
}
}
// full application
return x + y;
}
The function being returned here has access to outer-scope variables regardless of whether those variables are declared with var or declared as formal arguments to an outer function.
Generally speaking, if x is a primitive, it might sometimes make sense to assign it to a new variable if you needed a copy of that value to alter independently of the original:
function foo(x) {
var newX = x;
newX += 7;
// now newX and x are different
// ...
}
However, that need does not exist in this code, so it's totally unnecessary.

Categories

Resources