Why this code outputs 3, not 2?
var i = 1;
i = ++i + --i;
console.log(i);
I expected:
++i // i == 2
--i // i == 1
i = 1 + 1 // i == 2
Where I made mistake?
The changes occur in this order:
Increment i (to 2)
Take i for the left hand side of the addition (2)
Decrement i (to 1)
Take i for the right hand side of the addition (1)
Perform the addition and assign to i (3)
… and seeing you attempt to do this gives me some insight in to why JSLint doesn't like ++ and --.
Look at it this way
x = (something)
x = (++i) + (something)
x = (2) + (something)
x = (2) + (--i)
x = (2) + (1)
The terms are evaluated from left to right, once the first ++i is evaluated it won't be re-evaluated when you change its value with --i.
Your second line is adding 2 + 1.
In order, the interpreter would execute:
++i // i == 2
+
--i // i == 1
i = 2 + 1
++i equals 2, `--i' equals 1. 2 + 1 = 3.
You're a little off on your order of operations. Here's how it goes:
i is incremented by 1 (++i) resulting in a value of 2. This is
stored in i.
That value of two is then added to the value of (--i)
which is 1. 2 + 1 = 3
Because when you use ++i the value of i is incremented and then returned. However, if you use i++, the value of i is returned and then incremented. Reference
++$a Increments $a by one, then returns $a.
$a++ Returns $a, then increments $a by one.
--$a Decrements $a by one, then returns $a.
$a-- Returns $a, then decrements $a by one.
Because you're expecting this code to work as if this is a reference object and the values aren't collected until the unary operations are complete. But in most languages an expression is evaluated first, so i returns the value of i, not i itself.
If you had ++(--i) then you'd be right.
In short, don't do this.
The result of that operation isn't defined the same in every language/compiler/interpreter. So while it results in 3 in JavaScript, it may result in 2 elsewhere.
Related
how does below code give result as 10
var myVar = 2;
myVar = ++myVar + myVar++ + myVar--;
console.log(myVar);
and when directly given as below without assigning to myVar give result as 3 in javascript?
var myVar = 2;
++myVar + myVar++ + myVar--;
console.log(myVar);
There are two main factors we need to analyze:
Pre-Increment - The variable is first incremented, and then its value is used:
++x
Post-Increment - The variable value is first used, and then the value is incremented:
x++
With the first example:
var myVar = 2;
myVar = ++myVar + myVar++ + myVar--;
console.log(myVar);
The ++myVar increments the value from 2 to 3 first, so the value 3 is used. Then, for myVar++, the value 3 is used first, and then it is incremented to 4. For myVar--, the 4 is used, and then the value decrements from 4 to 3.
In the end, the expression will be: 3 + 3 + 4 = 10
For the second example:
var myVar = 2;
++myVar + myVar++ + myVar--;
console.log(myVar);
The individual +'s between the myVar are doing nothing. They are adding them together, but there is no variable storing that value. So the only thing that line does is apply the changes of ++myVar, myVar++, and myVar-- to myVar, giving it a value of 3 (from 2 to 3 to 4 to 3).
I hope this helped! Please let me know if you need any further clarification or details :)
As #Teemu said. Reading the documentation is really helpful.
Documentation
Maybe this helps also to understand this.
var myVar = 2;
myVar += myVar++;
console.log(myVar);
This question already has answers here:
Postfix and prefix increments in JavaScript
(9 answers)
Closed 1 year ago.
Today I see a weird result with the postfix and assignment operator which I was not expecting at all.
let say
let a = 10;
when we increment with postfix, it will result with the addition of 1 as follows
console.log( a++ ); // 10
console.log( a ); // 11
AFAIK a++ is a postfix operation which means
First, it will use the value(that's why a++ returns 10) and then
update the value
When we print the value, the value has been updated. That's why a returns 11.
So far so good,
But when I assigned the postfix operation to a variable, it won't update the value.
a = a++;
console.log( a ); // 11
Though I was expecting the result to be 12. Why this result? Thanks in advance.
let a = 10;
console.log(a++);
console.log(a);
a = a++;
console.log(a);
It does increment but if you breakdown the process,
Since the precedence of the postfix is greater than assignment
b = b++
Step 1 => Execute b++ which returns b
Step 2 => Assign returned value to the b, i.e assign b to b
Now console.log show the same old value.
b = 10;
Step 1 => return 10 and increment to 11.
Step 2 => Since the returned value is 10, re assign the 10 to a which cause console.log(a) to show 10 as the value.
function f(num) {
if (num<1) {
return 1;
}
return f(num-1) + f(num-2);
}
f(5); // 13
I investigated this code in the debugger but it's still unclear to me how it works. I see it as some kind of recursion, but don't get it at all.
Any kind of help will be appreciated.
There are essentially two forms of recursion direct and indirect. However, in either case any proper form of recursion must abide by three rules which makes it recursive.
1.) A recursive algorithm must have a base case.
2.) A recursive algorithm must change its state and move toward the base case.
3.) A recursive algorithm must call itself, recursively.
The intention for using a recursion algorithms focuses on taking a relatively mid to large problems and breaking them into smaller problems which can be solved iteratively or until the "base case" condition has been proven true.
function f(num) {
if (num<=1) { // (1) Base case condition
return 1; // (2.b) moving forward once the base case is true
}
// (3) the function calling itself
// also (2.a) changed state - (i.e., the param value is being decremented or "unwound" with each pass of recursion (i.e., method call)
return f(num-1) + f(num-2);
}
f(5); // Fn = Fn-1 + Fn-2 (Fibonacci Number Series)
Resources:
https://www.geeksforgeeks.org/recursion/
https://medium.com/launch-school/recursive-fibonnaci-method-explained-d82215c5498e
https://www.khanacademy.org/computing/computer-science/algorithms/recursive-algorithms/a/the-factorial-function
https://www.khanacademy.org/computing/computer-science/algorithms/recursive-algorithms/a/recursive-factorial
https://runestone.academy/runestone/books/published/pythonds/Recursion/TheThreeLawsofRecursion.html
https://www.natashatherobot.com/recursion-factorials-fibonacci-ruby/
It is a simple recursion implementation of calculating the num-th Fibonacci number(1 1 2 3 5 8....). And it has a small bug. It should be:
function f(num) {
if (num<=1) { // should be <= 1 instead of <, to handle when num = 1, otherwise it'll end up with f(0)+f(-1)
return 1;
}
return f(num-1) + f(num-2);
}
You can try to write down by hand and simulate some simple cases, which I think is really helpful when you study algorithms.
For example:
f(0) -> 0 is less than 1, return 1, thus f(0) = 1
f(1) -> 1 is less than or equal to 1, return 1, thus f(1) = 1
f(2) -> 2 is greater than 1, return f(1) + f(0), which we know from above, is 1 + 1, thus f(2) = 2
f(3) -> 3 is greater than 1, return f(2) + f(1), 2 + 1, thus f(3) = 3
f(4) -> 4 is greater than 1, return f(3) + f(2), 3 + 2, thus f(4) = 5
I bet you see the patterns now. Hope it helps.
It is recursion. It's a fibonacci series. Step through it slowly.
Start with a simple example:
f(0) = 1 (as num <1)
Increase to 1
f(1) = f(0) + f(-1) = 2
(as num = 1, but f(num-1) and f(num-2) are both less than 1 (and so each return 1)
increase to 2:
f(2) = f(2-1) + f(0) = f(1) + f(-1) = 3
we've solved f(1) and f(-1) already so we know the total returned is 2
increase to 3:
f(3) = f(3-1) + f(3-2) = f(2) + f(1) = 3 + 2 = 5
Remembering that the algorithm is expanding out each step fully (not relying on previous solutions so to speak). so this last example would look more like:
f(3) = f(2) + f(1) = (f(1) +f(0)) + (f(0)+f(-1)) = (f(0) + f(-1)) + 1 + 1 + 1 = 1 + 1 + 1 + 1 + 1 = 5
Given a statement such as let boolVal = 1 < 2, is there a way to console log the actual expression, i.e. 1 < 2 not the true result?
let boolVal = 1 < 2;
console.log(boolVal) // logs out the boolean result
console.log(boolVal.toString()) // logs out the boolean result as a string
/* is there a way to get just
'1 < 2'
itself to be logged out? */
From your response in the comment section, I see you need a generic solution with different operands.
The simplest solution I can think of is by using eval.
1- Create an array of strings array[]. You could creare a string. "" +expression.
2- console.log(array[index]+ eval(array[index]) )
Although i would not recommend. Eval is bad for both performance and security.
Another workaround is to make a connection for the results and for string you create from the first step. Like 2 arrays or create objects with 2 attributes. {value:, expression}.
You can print them accourdingly when you print the variable.
You can achieve this by making a custom function:
function printExpression(x,y){
console.log( (x<y?x:y) + " < " + (x<y?y:x));
}
printExpression(1,2);
printExpression(4,3);
let boolVal = 1 < 2;
You cant log 1 < 2 directly because they are compared and stored in boolVal. What you can do is a workaround.
Store 1 and 2 in variables var1 and var2.
let boolVal = var1 < var2
if boolVal:
console.log(var1 + "<" + var2)
else:
console.log(var1 + ">" + var2)
You could make a function that makes the comparison, and log both the result of that function and the function itself.
function boolValComparer(val1, val2) {
console.log(val1, '<', val2); // logs the boolean comparison as string with parameters
return val1 < val2;
}
let boolVal = boolValComparer(1, 2);
console.log(boolVal) // logs out the boolean result
console.log(boolValComparer) // logs out the comparer function as a string
I have a variable declared here:
var quizScore = 0;
And I want to add a number to it each time the correctAnswer() function runs:
function correctAnswer(){
quizScore+1;
console.log ( 'correct answer selected: quizscore = ' + quizScore );
}
I added a console log for debugging. It works, so the function is being called, but it is not adding the score. Do I need to parse this to an integer? I can't work out what the +1 needs to be to work correctly.
You can go here and you will see that clicking "Lightning Bolt" for question 1 shows "correct answer" in the console, but doesn't add to the score variable.
Do it like this:
function correctAnswer(){
console.log ( 'correct answer selected: quizscore = ' + (++quizScore) );
}
You just need to assign the +1 to quizScore variable. This may be the fastest way to add 1 and display it in one line
You're adding one to whatever value is in quizScore, and doing nothing with the result.
You need quizScore = quizScore + 1.
Keep quizscore as global variable.
And secondly change the line no.1 of your correctAnswer() function to
quizScore = quizScore + 1;
You can use self-memorizing function not to pollute global environment with variables like so:
function correctAnswer() {
correctAnswer.quizScore = (correctAnswer.quizScore || 0) + 1;
console.log("QuizScore : " + correctAnswer.quizScore);
}
for (var i = 0; i < 10; i++) {
correctAnswer(); // output 1 2 3 4 5 6 7 8 9 10
}
Right now, when you do this:
quizscore+1;
You add one to it but it doesn't assign the change to the variable. One reason for this is that sometimes you may want to add a number to the variable long enough to perform an operation but you don't want it to change.
// quiz score is left alone
var nextscore = quizscore + 1
Here are the different ways to actually assign it:
// temporarily adds 1 to quizscore, then saves it to quizscore
quizscore = quizscore + 1
// adds one to quizscore after it's used in an expression
quizscore++
// adds one to quizscore before it's used in an expression
++quizscore
So if you did something like this:
var nextscore = ++quizscore + 1;
You would both increment the current score and predict the next score.
Read more: Expressions and Operators