function test(a, b){
a = a + 2;
b = b + 5;
}
var a = 1;
var b = 2;
test(a, b);
console.log(a);
console.log(b);
This return 1 and 2, but i would like 3 and 7.
Is possible to make two operation in one function? This working if i use return, but how to use return to two operation?
live: http://jsfiddle.net/anCq6/
The reason you are getting 1 and 2 instead of 3 and 7 is because there are two different a and b variables. There's the a and b you declared outside the function, and there is the a and b which represent the values you passed into the function. (Basically, the parameters declared in the function's parentheses are newly declared variables.)
If you want to change the external a and b, change your test function to the following:
function test(x, y) {
a = x + 2;
b = y + 5;
}
Or, alternatively, don't pass a reference into the function, so that the a and b in the inner scope refer to the same a and b as the outer scope:
function test() {
a = a + 2;
b = b + 5;
}
Just send it back as an object...
function test(a, b){
a = a + 2;
b = b + 5;
return {a:a,b:b};
}
var a = 1;
var b = 2;
var test = test(a, b);
alert(test.a);
alert(test.b);
DEMO HERE
This doesn't work because since numbers are passed by value and not by reference, you're modifying the local copies of those variables, however the ones in the outer scope remain unmodified.
If you remove the a and b parameters from your function, you'll get the behavior that you want since the a and b parameters that are being modified will be the ones in the outer scope.
What are references?
Here's a pretty decent answer - Javascript by reference vs. by value
In short, only objects and arrays are passed by reference. Although in reality it's more complex than this depending on how functions are defined and syntax, at this point you can assume that anything that's defined by calling new or the syntactic shorthands [] ( array ) and {} ( object ) are passed by reference. Other types like numbers and strings are passed by value.
Another solution: because of how variable scope works in JavaScript, you can just remove the parameters of "test" function and it will work.
function test(){
a = a + 2;
b = b + 5;
}
function test(){
a = a + 2;
b = b + 5;
}
var a = 1;
var b = 2;
test();
console.log(a);
console.log(b);
Related
The function reverseArrayInPlace(array) is as per solution in eloquentJS. The reverseArrayInPlace function works, by altering the arrayValue as expected. A similar function written for a single variable does not work as expected. In the code, x should come out as 25, but comes out as 20.
//function from eloquentJS solutions, working as expected
`` function reverseArrayInPlace(array) {
for (let i = 0; i < Math.floor(array.length / 2); i++) {
let old = array[i];
array[i] = array[array.length - 1 - i];
array[array.length - 1 - i] = old;
}
return array;
}
let arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
// working as expected, returns → [5, 4, 3, 2, 1]
// Writing similar function for a single variable
function changeInPlace(a) {
a += 5;
return a;
}
let x = 20;
changeInPlace(x);
console.log(x);
// Not working as expected returns, 20 instead of 25
`
Snippet of the code
Assign changeInPlace to a variable at second last line, and then print that variable in console. It should work.
The problem is that you are returning your calculated variable and not logging it. The one you are logging remains 20.
You must use your function as below :
let variable = changeInPlace(x)
Full code must be like :
function changeInPlace(a) {
a += 5;
return a;
}
let x = 20;
x = changeInPlace(x);
console.log(x);
// x should come out as 25
If for any reason you want to edit a variable value directly, you must access it globally like this:
function changeInPlace() {
x += 5;
return x;
}
let x = 20;
changeInPlace(x);
console.log(x);
For each time you want to change the value in a variable, it needs to be called out again in the form of a declaration. Therefore, output of your function needs to be declared as new value for variable x. Like below:
Your function
// Writing similar function for a single variable
function changeInPlace(a) {
a += 5;
return a;
}
let x = 20;
changeInPlace(x);
console.log(x);
// x should come out as 25
Mine
// Writing similar function for a single variable
function changeInPlace(a) {
return a += 5; // Made a small tweak to your function,
}
let x = 20;
x = changeInPlace(x); // this stores the output of the function in the same variable
console.log(x);
This should give you the desired output, assume this is what you've been asking for if otherwise let me know
Answered by Marijn (author of eloquentJS):
You can't change numbers in JavaScript, only create new ones, so there's no way for a function to change the value of a binding whose value is passes as argument to that function. See for example this section in the book: https://eloquentjavascript.net/04_data.html#h_C3n45IkMhg
For example:
let a = 5;
let b = 6;
function sum1() {
console.log(a + b);
}
function sum2(a, b) {
console.log(a + b);
}
Are there any cases where one of the examples won't work?
In sum1 as you can’t pass arguments, it will do 5 + 6.
But in sum2 you can do something like this:
sum2(7,8) >> 15
sum2(1,5) >> 6
It’s better sum2, because use call it from anywhere and passing it arguments, you want.
Main questions:
1. How does f refer to r and t within the formula but no declaration for them anywhere in the code. Also the references appear to be cyclical.
2. Why is f2 set to f(x) what does that accomplish?
let x = 3;
let y = 7;
const f = function(r) {
return function(t) {
return x + y + Math.abs(r) + t;
}
};
const f2 = f(x);
x = 2;
alert(f2(17));
This code works but I do not understand what it is doing.
Thank you for your help.
How does f refer to r and t within the formula but no declaration for them anywhere in the code.
You can declare variables using function arguments. This is what they are doing here.
A simplified example:
function example(f) {
console.log("f is " + f);
}
example("one");
example(2);
Why is f2 set to f(x) what does that accomplish?
It calls f(x) and assigns its return value.
That return value is the function after the return keyword.
Now f2 is a function.
See also How do closures work
I want to get the values a, b, c from these functions and use them in my total. I have tried to return the values but it doesn't work. When I create global variables, total always takes the original global variable instead of the one from the function.
function d1() {
var a = document.getElementById("s1").value;
document.getElementById("d1").innerHTML = (2 * a).toFixed(2);
return a;
}
function d2() {
var b = document.getElementById("s2").value;
document.getElementById("d2").innerHTML = (3 * b).toFixed(2);
return b;
}
function d3() {
var c = document.getElementById("s3").value;
document.getElementById("d3").innerHTML = (4 * c).toFixed(2);
return c;
}
var total = a + b + c;
document.getElementById("total").innerHTML = total.toFixed(2);
I think it should be
var total = d1() + d2() + d3();
Since variables a, b and c are local to the functions and they fall into those functions scope. However, the biggest problem is that you do not call the functions at all, so even with using global variables your a,b,c would be undefined.
a, b and c are local variables within d1, d2 and d3 respectively. So, you can't use them directly outside of their scope like you have tried to.
There are multiple ways of achieving your desired outcome. The easiest
function d1() {
var a = document.getElementById("s1").value;
document.getElementById("d1").innerHTML = (2*a).toFixed(2);
return a;
}
function d2() {
var b = document.getElementById("s2").value;
document.getElementById("d2").innerHTML = (3*b).toFixed(2);
return b;
}
function d3() {
var c = document.getElementById("s3").value;
document.getElementById("d3").innerHTML = (4*c).toFixed(2);
return c;
}
**var total = d1() + d2() + d3();**
document.getElementById("total").innerHTML = total.toFixed(2);
That's a code fragment task - you should enter "var" (as many as want) in it in order to get 17 in the first, and 21 in the second alert. I thing that I have met this before, but still was not able to solve the issue.
a = 3;
b = 2;
function line(x) {
a = 5;
b = 4;
return a*x + b
}
//b should be 17
b = line( a ) - b;
alert( b );
//c should be 21
c = line ( a ) + b;
alert(c);
If you put "var" in the function in front of b, it will alert "17". The next alert gives us 46 because of the new value of b, return by the function.
function line(x) {
a = 5;
var b = 4;
return a*x + b
}
That's the source of the task:
http://www.codecademy.com/courses/javascript-for-jquery/1?curriculum_id=4fc3018f74258b0003001f0f/#!/exercises/3
Using exactly what's given, in exactly the way it's given is impossible.
What I mean by that is if the call:
c = line(a) + b;
is dependent upon the value of b which is the assignment at:
b = line(a) - b;
Then it's 100% impossible to either have made a a significantly-small number, or made b a significantly-large negative number to make the math work.
Therefore it's my belief that they're intended to be two separate checks.
Best-case scenario, if we're trying to have b=17 included:
a = 3;
3 * 5 = 15 + 4 = 19 + 4 = 23;
That's the smallest you're going to get, assuming you run the two back-to-back.
Even if you did it that way, you wouldn't get b = line(a) - b = 17 on the first run...
If it was written:
c = line(a) - b;
d = line(a) + b;
Then you could run both in succession and get the expected result.
Or you can run:
var a = 3,
b = 2;
function line (x) {
var a = 5,
b = 4;
return a*x + b;
}
b = line(a) - b;
and get 17.
Then you can run:
var a = 3,
b = 2;
function line (x) {
var a = 5,
b = 4;
return a*x + b;
}
c = line(a) + b;
(ie: the exact same setup with a different instigator, and without the saved b value from the return of the previous call), and get the desired result.
But it's not possible to run both of them one after the other, and expect to have them both work, without doing anything to the code but add a var or four.
Keep your function like this, if you want to maintain consisitency. Using "var" before a and b will make them local to the function block and that call. Otherwise they will refer to the global variable.
function line(x) {
var a = 5;
var b = 4;
return a*x + b
}