This question already has answers here:
++someVariable vs. someVariable++ in JavaScript
(7 answers)
Closed 8 years ago.
Please read whole topic, before post answer. No answer found to this question in post: ++someVariable Vs. someVariable++ in Javascript
var i = 1;
i = i++ * 2; // i = 2, .. why not 4 ?
interpreter does the multiply (1*2), but where is the increment ( i++ )?
var i = 1;
i = ++1 * 2; // i = 4
I'm understand, that the i++ does the increment after the statement, ++i does it before the statement, but in this example: i = i++ * 2 // (1*2), how the interpreter works?, where is the increment of i in this case? maybe i = (1*2)+1 )), or i = (1*2) and no more i exist, and nothing to increment??
HOW ?
P.S. I think, it is a wrong question, but as Brooks Hanes said(in comment), this is a learning example.
i++ means: read the value of variable i, then increase variable i
++i means: increase variable i, then read the value of variable i
This is an interesting little problem, a simple experiment shows what is happening. jsFiddle
var i = 3; p = i++ *2; console.log(i, p);
The 2 is multiplied by i (3) the result (6) is placed in p. Then a copy of the original value of i (3) is incremented and placed back in i. This behaviour is logically consistent with the following:
var i = 3; var p = 0; function adder(x) { p = x + 2; }; adder(i++); console.log(i, p);
This makes a strange kind of sense because the post increment is supposed to happen after the statement.
Related
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.
This question already has answers here:
What is the JavaScript version of sleep()?
(91 answers)
Closed 3 years ago.
I need to run a setInterva () but when trying to do it within a while cycle the setInterval() never runs. I'm a beginner in javascript so I don't know what the reason is.
The code I try to execute is the following:
var i = 0;
while(i < 5){
var c = 0;
var t = setInterval(function(){
c++;
if(c==5){
clearInterval(t);
}
},2000);
i++;
}
What is the method to create a time.sleep() within a while cycle in javascript?
As mentioned in the comments above, setInterval() does not pause code execution. Instead everything else runs as normal, but after the set amount of time it runs the function. Also, you want to use setTimeout because it only runs once. It looks like you just want to increment c by one every five seconds. Do so like this:
let i = 0;
let c = 0;
while (i < 5) {
setTimeout(() => c += 1, 5000/*number of milliseconds you want to wait*/ * (i + 1))
}
so, i will increment after 5000 milliseconds, 10000 milliseconds, 15000, etc.
Just so you know: () => i+= 1 is the same as
function() {
i += 1
}
With some refactoring, and using for loops, your code becomes:
let c = 0
for(let k = 0; k < 5; k += 1) setTimeout(() => c += 1, 5000 * (k + 1))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I would like to sum up all the elements inside the array covertedValue. Why I am getting a Nan result? whats wrong with the recursive function I have written?
function findOutlier(integers){
var covertedValue = integers.map(x => x % 2);
var total = 0;
for (i=0 ; i<covertedValue.length ; i++){
total = total + covertedValue[0] + findOutlier(integers.splice(1));
}
console.log(total);
}
findOutlier([0, 1, 2]);
because this line create a function and a private alias to itself
var factorial =
// create a variable named factorial in global scope
// it contains the function fac
function fac(n) {
// fac is a function available only in the factorial var context
return n < 2 ? // if n < 2
1 : // return 1
n * fac(n - 1); // else return n * fac(n - 1)
};
console.log(factorial(5));
// calls factorial(5) which is 5*fac(4) which is 5*(4*fac(3)) ...
note that the fac function is not available outside of itself
var factorial = function fac(n) { return n < 2 ? 1 : n * fac(n - 1); };
console.log(fac(5));
This way of coding where a function call itself is called recursive programming it can be hard to grasp at first but can be VERY powerful in some situations
recurcive programming can easily be used when the result of func(n) depend directly on the result of func(n+x)
the cond ? then : else structure is called ternary operator, it's a way to make if in one line, can become messy very quick
as you noted in a comment : recursion can be replaced by a loop (it can be hard to do it sometime)
here's a more beginner way to write it
function factorial(n) {
if(n < 2) {
return 1
} else {
let fac = 1;
for(var i = n; i > 0; i--) {
fac = fac * i
// here fac takes the value of the precedent iteration
}
// this whole loop is the same as i*fac(i-1) in the recurcive way
return fac
}
};
console.log(factorial(5));
This question already has answers here:
What is the fastest factorial function in JavaScript? [closed]
(49 answers)
Closed 7 years ago.
I'm learning Java Script and there is an exercise about getting the factorial of number user has entered but for some reason I always get answer is = 1
here is my code :
<SCRIPT>
function factorial(num){
for (n=1; n<=num; n++){
return fact*n;
}
}
var myNum, fact;
myNum = parseFloat(window.prompt('Enter positive integer : ',''));
fact = 1;
document.write('the factorial of the number is = '+ factorial(myNum));
</SCRIPT>
The pictured code (please include actual code in the future, not screenshots of code) returns fact immediately:
for ( n = 1; n <= num; n++ ) {
return fact * n;
}
since n starts at 1.
What you want is to include fact in the function, and multiply it as the loop goes along, then return:
function factorial(n) {
var fact = 1;
for ( n = 2; n <= num; n++ ) {
fact = fact * n;
}
return fact;
}
The reason this is returning 1 is because in your loop above, you return the value on the very first iteration, so n is never greater than 1.
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.