Reputation:
I am wondering if it's possible to go back to a while loop instead of having to type it all over again?
Simple example:
let sum = 0;
let value = 10;
while (sum < value) {
// do code
sum++;
};
// sum is changed for some reason outside of loop, after iteration
sum = 3
// iterate through the loop again?
Instead of..
let sum = 0;
let value = 10;
while (sum < value) {
// do code
sum++;
};
// sum is changed for some reason outside of loop, after iteration
sum = 3;
while (sum < value) {
// do same code again
sum++;
};
I suppose you can create a function with the while-loop but is it possible to handle this some other way?
Thanks in advance.
Upvotes: 0
Views: 387
Reputation: 386560
You could take the values in an array and loop the array and the while
loop inside of the for
loop.
var sums = [0, 3],
sum,
value = 10,
i;
for (i = 0; i < sums.length; i++) {
sum = sums[i];
console.log('outer', sum);
while (sum < value) {
// do code
sum++;
console.log('inner', sum);
}
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 10384
If you are in a ES6 environment you can use a setter to watch an object and execute a function when one of its property changes.
let obj = {
value: 20,
set sum(sum) {
while (sum < this.value) {
// some code
sum++;
}
}
};
obj.sum = 5; // execute the code inside the while 15 times
obj.sum = 10; // execute the code other 10 times
You can also give a glance to Proxies
Upvotes: 0
Reputation: 333
Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure—a set of statements that performs a task or calculates a value. To use a function, you must define it somewhere in the scope from which you wish to call it.
let sum = 0;
let value = 10;
valueSum(sum , value);
sum = 3;
valueSum(sum , value);
function valueSum(sum , Value){
while (sum < value) {
// do code
sum++;
};
}
Upvotes: 0
Reputation: 16576
Make loopy function. Functions help avoid duplicating code.
let sum = 0;
let value = 10;
function loopy() {
while (sum < value) {
// do code
console.log(sum++)
};
}
loopy();
// sum is changed for some reason outside of loop, after iteration
sum = 3;
loopy();
Upvotes: 1