Can someone explain this code in JavaScript with ++ and brackets? - javascript

var m=10;
n=(m++)+(++m)+(m++)+(++m);
Output is
n=48 m=14
How does this answer occur?

Initially m=10. Now when ++ is executed, it will add 1 to the variable. In your code, there are 4 occurences of either ++m or m++, so it will be 14 at the end.
When ++ appears before the variable like ++m, it will add 1 first and use the variable in code. But when it appears after the variable like m++, the variable will be used first and then add 1.
So in n=(m++)+(++m)+(m++)+(++m);,
m++ - m will be used in code as 10 and becomes 11.
++m - m will be incremented by 1 first, so 11+1 =12 and will be used in code.
m++ - m will be used in code as 12 and becomes 13.
++m - m will be incremented by 1 first, so 13+1 =14 and will be used in code.
So, final result will look like this:
n=10+12+12+14
var m = 10;
var m1 = m++;
var m2 = ++m;
var m3 = m++;
var m4 = ++m;
var n = m1 + m2 + m3 + m4;
console.log('n: ' + n);
console.log('m: ' + m);
console.log('(m++): ' + m1 + ', (++m): ' + m2 + ', (m++): ' + m3 + ', (++m): ' + m4);
console.log('---');
var x = 10;
var y = (x++) + (++x) + (x++) + (++x);
console.log('y: ' + y);
console.log('x: ' + x);

m++ this will use previous value of m then increment.
++m this will first increment and then use the incremented value of m.
now,
n=(m++)+(++m)+(m++)+(++m);
-> m++ here the value of m will be first used then increased by 1. so expression will be 10 + (++m) + (m++) + (++m). and for further value of m will be 11.
-> for next it is ++m so it will first increment then use in expression. so previously the value of m was 11, now 11+1 is 12. so expression will look like 10+12 + (m++) + (++m).
-> similarly to first point here also it will first used then increment. so expression will be n=10+12+12+(++m). but after this the value of m is now 13.
-> so here (++m) it will first increment and then add. so previously the value was 13 so 13+1=14. so m is 14 and expression will be n=10+12+12+14.
so the value of n=48 and m=14

Related

Equation evaluation in math.js

I am new in math js library and I was trying to solve this expression:
var x_res = math.simplify('(x-'+x1+')^2 + ('+y_part+' - '+y1+')^2 - 197.5^2');
With simplify method i simplified it, but how can I do to know the "x" value ?
Thanks in advance.
I'm not sure what you mean by know the x value but you get an expression with one variable - x.
x1 = 2
y_part = 3
y1 = 4
var x_res = math.simplify('(x - '+x1 + ')^2 + (' + y_part + ' - ' + y1 + ')^2 - 197.5^2');
x_res.toString()
// "-156021 / 4 + (x - 2) ^ 2"
If you want then to evaluate the expression against a defined x, you can:
x_res.eval({ x: 1 })
// -39004.25
x_res.eval({ x: 2 })
// -39005.25
x_res.eval({ x: 1000 })
// 956998.75
Not regarding mathjs but, If you want to find what x will be equals to when the all equation equals some value you can use AlgebraJs
var expr = new Expression("x");
expr = expr.subtract(3);
expr = expr.add("x");
console.log(expr.toString());
2x - 3
var eq = new Equation(expr, 4);
console.log(eq.toString());
2x - 3 = 4
var x = eq.solveFor("x");
console.log("x = " + x.toString());
x = 7/2

Javascript for loop displaying more results than expected

When running the code below, the text inside the document.write runs 8 times and not 7 times as I was expected.
If I understand correctly, increment by 2 should display the positions:
20+2, 22+2, 24+2, 26+2, 28+2, 30+2 and 32+2.
Based on the results I get I assume it also displays the 34+2, which is 36. What I am missing? Thank you.
x = 20;
for (x = 20; x < 35; x += 2) {
document.write("How many times will this loop execute?" + "<br/>");
};
As noted in the comments above, The loop is correct in running 8 times. Since no one stated the reason, it is this: the x+=2 happens at the end of the loop, not at the beginning. So the loop will run for 20, 22, 24, 26, 28, 30, 32, and 34.
You are misunderstanding how the for loop works.
for ([initialization]; [condition]; [final-expression])
final-expression: An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.
So your counter gets incremented at the end of the loop and the observed behaviour is correct. The loop gets executed for 20, 22, 24, 26, 28, 30, 32, and 34.
When start loop add +2 to x like below:
x = 20;
for (x = 20+2; x<35; x+=2) {
document.write("How many times will this loop execute?" + "<br/>");
};
fiddle
Script:
x = 20;
count = 1;
for (x = 20; x < 35; x += 2){
document.write("Execution: "+ (count++)+ "<br/>");
};
Output
The loop executes total 8 times.
Execution: 1
Execution: 2
Execution: 3
Execution: 4
Execution: 5
Execution: 6
Execution: 7
Execution: 8
jsfiddle link to checkout.
Yes, is executing 8 times, because is from 20 to 35 in 2 x 2
x = 20;
for (x = 20; x < 35; x += 2) {
document.write("Execute for " + x + " " + "<br/>");
};
/*
OUTPUT:
Execute for 20
Execute for 22
Execute for 24
Execute for 26
Execute for 28
Execute for 30
Execute for 32
Execute for 34
*/
If you want 7 times, you can change to 34
x = 20;
for (x = 20; x < 34; x += 2) {
document.write("Execute for " + x + " " + "<br/>");
};
It will run eight times, x iterating through every even number between 20 and 34 inclusive. You can write it like this if it helps:
var x = 20;
while (x <= 34) {
// do something
x += 2;
}
However, it is important to note that after the loop has run (whether you're using the for or while version), x will equal 36, since it is incremented to that before it finally fails the test; inside the loop, x will never equal 36. In terms of best practice, you should only really use a counter variable like x within the loop; this can be enforced by using the ES6 let keyword (which is block-scoped) like so (the example just prints out a list of the x values as DOM elements):
function appendSpanCounter(i, end) {
let el = document.createElement("span"),
content = i.toString(10);
if (i < end) content += ", ";
(typeof el.textContent === "string") // ternary operator
? el.textContent = content
: el.innerText = content;
(document.body || document.querySelector("body")).appendChild(el);
}
for (let x = 20; x <= 34; x += 2) {
appendSpanCounter(x, 34);
}
// x is now undefined here

newbie in javascript closure, and the closure test's result is unexpect

newbie in javascript closure
i follow a example from internet, and try to change some of it
i think it should give me 16,17,18,19
but the result was unexpect
here is my code.
i do not know why i first call bar2(10),it alert 17, does it should give me 18?
function foo(x) {
var tmp = 3;
return function (y) {
alert(x + y + (++tmp));
}
}
var bar = foo(2);
bar(10);//alert16
bar(10);//alert17
var bar2 = foo(3);
bar2(10);//alert17
bar2(10);//alert18
Because tmp is a variable local to the function you return from foo -- that means when you call foo for the second time, it gets reset to 3. 3 + (3+1) + 10 = 17.
The result 17 is correct.
Each call to foo produces a new function with a new closed-over variable tmp.
Perhaps you thought the second call to foo uses the same tmp as in the first call? It doesn't. That is why you get 17: 3 + 10 + 4.
bar(y) = n = x + y + tmp
bar(10) = 16 = 2 + 10 + 4
bar(10) = 17 = 2 + 10 + 5
bar2(10) = 17 = 3 + 10 + 4
bar2(10) = 18 = 3 + 10 + 5

Add two values together in Mootools

My Javascript / Mootools knowledge is limited, so I am having trouble figuring out how to take the following code and make it produce a sum and assign the value to the ordertotal variable.
$('ordertotal').value = '$' + 100 * $('tickets').value + 10 * $('fiftytickets').value + '.00';
The tickets variable is either 1 or 2 depending on the user selection and the fiftytickets variable is either 0.5, 2.5 or 5.0 depending of the user selection. Both variables are supplied values using a HTML select menu and they function correctly when used individually.
For example:
$('ordertotal').value = '$' + 100 * $('tickets').value + '.00';
Works correctly and
$('ordertotal').value = '$' + 10 * $('fiftytickets').value + '.00';
Works correctly, but I can figure out how to add them together and assign them to the ordertotal variable.
Any assistance with this issue would be greatly appreciated.
Thank you.
Mike
Seems like you are trying to get sum of string + int + int + string
Your two examples worked, because there was only concatenation (string + int(converted to string) + string)
And when you add a nubmer to a "$" - your number get converted to a string. What you can do is to either put numbers sum in () or get the value separately:
sumValue = 100 * $('tickets').value + 10 * $('fiftytickets').value
$('ordertotal').value = '$' + sumValue + '.00';
Example:
> "1" + 1
"11"
> "$" + 1 + ".00"
"$1.00"
> "$" + 1 + 1 + ".00"
"$11.00"
> "$" + (1 + 1) + ".00"
"$2.00"

Why I got NaN in this javaScript code?

First I test that every variable got a number value:
09-11 18:15:00.420:
d_drop: -1.178791867393647
drop_at_zero: 0.0731037475605623
sightHeight: 4.5
d_distance: 40
zeroRange: 10
09-11 18:15:00.420:
d_drop: true
drop_at_zero: true
sightHeight: true
d_distance: true
zeroRange: true
function isNumber (o) {
return ! isNaN (o-0) && o != null;
}
var d_drop; // in calculation this gets value 1.1789
var d_path = -d_drop - sightHeight + (drop_at_zero + sightHeight) * d_distance / zeroRange;
console.log("Path: " + d_path + " cm");
and in the log:
09-11 18:15:00.430: D/CordovaLog(1533): Path: NaN cm
WHY? I have tried to figure that out couple of hours now and no success, maybe someone has an idea, I haven't!
Thanks!
Sami
-------ANSWER IS that parse every variable when using + operand-----------
var d_path = parseFloat(-d_drop) - parseFloat(sightHeight) + (parseFloat(drop_at_zero) + parseFloat(sightHeight)) * parseFloat(d_distance) / parseFloat(zeroRange);
The addition operator + will cast things as strings if either operand is a string. You need to parse ALL of your inputs (d_drop, sightHeight, etc) as numbers before working with them.
Here's a demo of how the + overload works. Notice how the subtraction operator - is not overloaded and will always cast the operands to numbers:
var numberA = 1;
var numberB = 2;
var stringA = '3';
var stringB = '4';
numberA + numberB // 3 (number)
numberA - numberB // -1 (number)
stringA + stringB // "34" (string)
stringA - stringB // -1 (number)
numberA + stringB // "14" (string)
numberA - stringB // -3 (number)
http://jsfiddle.net/jbabey/abwhd/
At least one of your numbers is a string. sightHeight is the most likely culprit, as it would concatenate with drop_at_zero to produce a "number" with two decimal points - such a "number" is not a number, hence NaN.
Solution: use parseFloat(varname) to convert to numbers.
If you're using -d_drop as a variable name, that is probably the culprit. Variables must start with a letter.
var d_drop = -1.178791867393647,
drop_at_zero = 0.0731037475605623,
sightHeight = 4.5,
d_distance = 40,
zeroRange = 10;
var d_path = d_drop - sightHeight + (drop_at_zero + sightHeight) * d_distance / zeroRange;
console.log("Path: " + d_path + " cm"); // outputs: Path: 12.613623122848603 cm

Categories

Resources