I currently am learning Javascript and C.S fundamentals, I am completing an assignment which was to create a function that takes a value(num) and outputs the index value within fibonacci numbers.
Example: function(6) outputs 8; because 8 is the 6th number in the fibonacci sequence.
fibonacci numbers: 1,1,2,3,5,8
index position: 1,2,3,4,5,6
below is the solution to the problem.
const fibonacci = function(count) {
let a = 0;
let b = 1;
for (let i = 1; i < count; i++) {
const temp = b;
b = a + b;
a = temp;
}
return b;
};
The part I am having trouble understanding lies within the for-loop, from what I've gathered it seems this is how it's being executed within the call-stack:
execute b + a
store the previousValue of b in temp
a is now equal to temp/previousValue
execute b + a
update value of a...
but what I struggle to understand is why a stores the previousValue of B and NOT the currentValue.
When I envision the call-stack running I expected the output to look something like this;
0,1
1,1
2,2
instead of..
0,1
1,1
1,2
The value of a remains at 1 even though b is now equal to 2, after
temp = b;
b = 1;
a = 1;
b = a + b // 2;
a = temp;
a should be equal to 2 now, but instead it remains at 1; Why?
If I understand you correctly, your misunderstanding is here:
a is now equal to temp/previousValue
The value stored in a does not change until the last operation in the loop body. With the initial values of a=0; b=1;, when the loop body runs,
temp is set to the value of b, so temp=1;
b is set to a+b, so b=1
a is updated with the value in temp, so a=1
At the end of each loop, b holds the next Fibonacci value. The value in a is updated to the previous value only so that it can be used in the next iteration of the loop to calculate the new value of 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
In JavaScript you can use ++ operator before (pre-increment) or after the variable name (post-increment). What, if any, are the differences between these ways of incrementing a variable?
Same as in other languages:
++x (pre-increment) means "increment the variable; the value of the expression is the final value"
x++ (post-increment) means "remember the original value, then increment the variable; the value of the expression is the original value"
Now when used as a standalone statement, they mean the same thing:
x++;
++x;
The difference comes when you use the value of the expression elsewhere. For example:
x = 0;
y = array[x++]; // This will get array[0]
x = 0;
y = array[++x]; // This will get array[1]
++x increments the value, then evaluates and stores it.
x++ evaluates the value, then increments and stores it.
var n = 0, m = 0;
alert(n++); /* Shows 0, then stores n = 1 */
alert(++m); /* Shows 1, then stores m = 1 */
Note that there are slight performance benefits to using ++x where possible, because you read the variable, modify it, then evaluate and store it. Versus the x++ operator where you read the value, evaluate it, modify it, then store it.
As I understand them if you use them standalone they do the same thing. If you try to output the result of them as an expression then they may differ. Try alert(i++) as compared to alert(++i) to see the difference. i++ evaluates to i before the addition and ++i does the addition before evaluating.
See http://jsfiddle.net/xaDC4/ for an example.
I've an explanation of understanding post-increment and pre-increment. So I'm putting it here.
Lets assign 0 to x
let x = 0;
Lets start with post-increment
console.log(x++); // Outputs 0
Why?
Lets break the x++ expression down
x = x;
x = x + 1;
First statement returns the value of x which is 0
And later when you use x variable anywhere, then the second statement is executed
Second statement returns the value of this x + 1 expression which is (0 + 1) = 1
Keep in mind the value of x at this state which is 1
Now lets start with pre-increment
console.log(++x); // Outputs 2
Why?
Lets break the ++x expression down
x = x + 1;
x = x;
First statement returns the value of this x + 1 expression which is (1 + 1) = 2
Second statement returns the value of x which is 2 so x = 2 thus it returns 2
Hope this would help you understand what post-increment and pre-increment are!
var a = 1;
var b = ++a;
alert('a:' + a + ';b:' + b); //a:2;b:2
var c = 1;
var d = c++;
alert('c:' + c + ';d:' + d); //c:2;d:1
jsfiddle
var x = 0, y = 0;
//post-increment: i++ returns value then adds one to it
console.log('x++ will log: ', x++); //0
console.log('x after x++ : ', x); //1
//pre-increment: adds one to the value, then returns it
console.log('++y will log: ', ++y); //1
console.log('y after ++y : ', y); //1
It is clearer and faster to use ++i if possible :
++i guarantees that you are using a value of i that will remains the same unless you change i
i++ allows to use a value of i which will change in the "near future", it is not desirable if possible
Of course, it's not really much faster, only a little.
It is possible to initialize multiple variables to the same value a=b=5. Also, it is possible to add to a variable with a+=2. But is there any way to add the same value to both at the same time? Something like this a+=b+=2 without the a getting incremented by the value of 2 and b. So in this case both a and b would end up being 7.
Also, I'm not looking for an answer that repeats the added value such as a+=2,b+=2.
I realize this is not the greatest coding practice I just wondered if it was possible. Somewhat similar in nature to Swapping two variable value without using 3rd variable
You can do it! Here's how to:
var a = 10;
var b = 15;
b += -a + (a += 10); // In this case, adding 10 to both
console.log(a, b); //=> 20 25
BOOM (yes it blew my own mind too)
Sometimes it doesn't matter why you do it, it just matters that you can do it!
So, how / why does it work?
The -a gets parsed and becomes the negative value of a, which is 10 (so -10). Then, a += 10 runs and sets a to 20 (10 + 10). Finally, it sums up both values (-10 + 20) and gives you the difference between old a and new a.
Gorgeous.
EDIT:
For completion's sake, as of ES6's destructuring assignments, you could do:
let a = 10;
let b = 15;
[ a, b ] = [ a+10, b+10 ]
console.log(a, b); //=> 20 25
Which is also one statement, as well as being tidier and simpler to understand.
So in this case both a and b would end up being 7.
You can add the two defined variables and the specified incremented value multiplied by the number of variables then divide by the number of variables
a = b = 5;
console.log(a, b);
n = 2;
a = b = ((a + b + n * 2) / 2);
console.log(a, b);
something like var a=5,b=7; Then you want to add the result of
foo?2:3. So if false the result would be 8 and 10.
You can use destructuring assignment, Array.prototype.map()
var a = 5, b = 7;
console.log(a, b);
var foo = false;
[a, b] = [a, b].map(v => v += foo ? 2 : 3);
console.log(a, b);
I was having a conversation about the prefix increment operator, and we seem to have run into a disagreement.
When running this code:
var x = 0;
x = ++x;
is the second line equivalent to:
x = (x = x + 1) OR
x = (x + 1)
It is hard to tell the difference because the results are identical (both result in x having a value of 1)
I believe that the value is not saved to the original variable when the left hand side of the assignment is the variable itself.
My counterpart disagrees and thinks the value is saved to the original variable whenever the ++ operator is used.
Which one of us is right?
It is saved, so it is similar to the first example.
Take for example this code:
var v = 0;
v = ++v + ++v + ++v;
// Returns 6
That is because this will translate to:
v = (0+1) + ((0+1)+1) + (((0+1)+1)+1);
Or, to be more accurate:
v = 0+1 +
v = 1+1 + //Previous value of v + 1
v = 2+1 //Previous value of v + 1
Why?
++v will first save the incremented value of v, then it will return this incremented value.
To simplify things, try this in your console:
x = 0;
++x;
If ++x would resolve to x + 1, the value of x would now still be 0, right?
Nope, your x will be 1. This means that ++x must have a assignment operator in there.
Just try writing both ++x and x++ out in full English sentences:
++x: increment x by one and return the value
x++: return the value of x, and increment it.
Your second line (x = ++x;) is equivalent to x = (x += 1), yes.Just look at any loop you've ever written:
for (var i = 0;i<100;i++)//<-- no need for another assign here
So you could've written ++x; all the same, but since that expression is the entire statement, it makes no difference if you write x++; or ++x...
As you probably know xxsomeVar increments the variable by 1, assigns the resulting value to that variable and then returns it, someVar++ returns the current value of the variable, and then increments it by 1 (the new value is assigned to the variable, too, of course).
So ++x; is the equivalent of x = (x + 1);
From the Language specs:
++prefix increment operator
Postfix++ increment operator
Doing:
var x = 0;
console.log(++x); // will make print 1
Doing :
var x = 0;
console.log(x++); // will make print 0
console.log(x); // will print 1
After reading the ECMAScript Language Specification in answer to the question it appears that ++x is equivalent to x = ( x = x + 1 ).
Translation of the steps outlined by the specification is:
The result of the operation will be assigned to x
Throw error if certain conditions are true
oldValue = x
newValue = oldValue + 1
assign newValue to x
return newValue
For the post-increment operator the above will return the oldValue instead of the newValue.
var x = 0;
// x is assigned 1 during the post-increment operation but because
// the oldValue is returned it is immediately replaced by 0.
x = x++;
console.log( x ) // prints 0
In JavaScript you can use ++ operator before (pre-increment) or after the variable name (post-increment). What, if any, are the differences between these ways of incrementing a variable?
Same as in other languages:
++x (pre-increment) means "increment the variable; the value of the expression is the final value"
x++ (post-increment) means "remember the original value, then increment the variable; the value of the expression is the original value"
Now when used as a standalone statement, they mean the same thing:
x++;
++x;
The difference comes when you use the value of the expression elsewhere. For example:
x = 0;
y = array[x++]; // This will get array[0]
x = 0;
y = array[++x]; // This will get array[1]
++x increments the value, then evaluates and stores it.
x++ evaluates the value, then increments and stores it.
var n = 0, m = 0;
alert(n++); /* Shows 0, then stores n = 1 */
alert(++m); /* Shows 1, then stores m = 1 */
Note that there are slight performance benefits to using ++x where possible, because you read the variable, modify it, then evaluate and store it. Versus the x++ operator where you read the value, evaluate it, modify it, then store it.
As I understand them if you use them standalone they do the same thing. If you try to output the result of them as an expression then they may differ. Try alert(i++) as compared to alert(++i) to see the difference. i++ evaluates to i before the addition and ++i does the addition before evaluating.
See http://jsfiddle.net/xaDC4/ for an example.
I've an explanation of understanding post-increment and pre-increment. So I'm putting it here.
Lets assign 0 to x
let x = 0;
Lets start with post-increment
console.log(x++); // Outputs 0
Why?
Lets break the x++ expression down
x = x;
x = x + 1;
First statement returns the value of x which is 0
And later when you use x variable anywhere, then the second statement is executed
Second statement returns the value of this x + 1 expression which is (0 + 1) = 1
Keep in mind the value of x at this state which is 1
Now lets start with pre-increment
console.log(++x); // Outputs 2
Why?
Lets break the ++x expression down
x = x + 1;
x = x;
First statement returns the value of this x + 1 expression which is (1 + 1) = 2
Second statement returns the value of x which is 2 so x = 2 thus it returns 2
Hope this would help you understand what post-increment and pre-increment are!
var a = 1;
var b = ++a;
alert('a:' + a + ';b:' + b); //a:2;b:2
var c = 1;
var d = c++;
alert('c:' + c + ';d:' + d); //c:2;d:1
jsfiddle
var x = 0, y = 0;
//post-increment: i++ returns value then adds one to it
console.log('x++ will log: ', x++); //0
console.log('x after x++ : ', x); //1
//pre-increment: adds one to the value, then returns it
console.log('++y will log: ', ++y); //1
console.log('y after ++y : ', y); //1
It is clearer and faster to use ++i if possible :
++i guarantees that you are using a value of i that will remains the same unless you change i
i++ allows to use a value of i which will change in the "near future", it is not desirable if possible
Of course, it's not really much faster, only a little.