Javascript for loop new condition - javascript

plz check the code below:
for(i=0; i-DIL; i++)//see the condition here i-DIL .Is this correct?
{
}
is the second condition above in for loop correct?if so ,what does that mean?
actual code is:
javascript:R=0;
x1=.1; y1=.05;
x2=.25; y2=.24;
x3=1.6; y3=.24;
x4=300; y4=200;
x5=300; y5=200;
DI=document.getElementsByTagName("img");
DIL=DI.length;
function A(){for(i=0; i-DIL; i++)//see the condition here i-DIL .Is this correct?
{
DIS=DI[ i ].style;
DIS.position='absolute';
DIS.left=(Math.sin(R*x1+i*x2+x3)*x4+x5)+"px";
DIS.top=(Math.cos(R*y1+i*y2+y3)*y4+y5)+"px"}
R++
}
setInterval('A()',5); void(0);
Also can anyone help me describing the reason for placing void(0) at the end of the script?
And U can see that repeatedly image position is set over and over .How can i overcome that

Whether or not it's "correct" depends on what exactly you want the for loop to do. However, it is valid code, and hinges on the fact that 0 in JavaScript is "falsey", while other numbers are "truthy".
Essentially, when i and DIL are equal, i - DIL equals 0, which for the purposes of the for loop condition is evaluated as false, and it stops iterating. Given that DIL is the length of a collection, it's an interesting (but technically valid) method of iterating over the entire collection.
It's equivalent to (though I'd say less readable than):
for(i=0; i < DIL; i++)

it means execute code below till i-DIL != 0. ie here in your code it will work till i reaches DIL.

A for loops usually takes:
for(variable definition; condition; increment) {}
So, you need a condition. However, because Javascripts has loose content types, you don't have to use a comparison for it to be true or false.
10 - 1 // = 9 equals true
10 - 9 // = 1 equals true
10 - 10 // = 0 equals false
"legit string" // equals true
NULL // equals false
However, I do suggest to make an actual comparison just to avoid nasty browsers to break your condition.
for(var i = 0; i - DIL > 0; i++) {}

Related

basic Javascript While loop and boolean value questions

I would ask my instructor, but whenever I do, he gives me an even more vague answer to my questions, so I'm asking yall for help. We "learned" (i.e. watched videos) about for and while loops and I get it, I feel like I do, but whenever it comes to doing the assignments given, I feel like they don't make sense. Like back in math class in high school, they'd teach you about the problems, but then when it came time to do your homework, the problems were completely different from what you just learned about. For instance, it says the basic while loop structure is:
while(condition is true) {
//do something
}
But then in this assignment, it gives me:
// Another way to write a while loop is to have a boolean variable
// where the condition goes and then test every time if you need to
// change the boolean to false.
// Below we have a variable lessThan5 and it is set to true.
// Create a loop that tests if our variable 'j' is less than 5.
// If it is less than 5 then Increment it by 1. If it is not
// less than 5 then set our lessThan5 variable to be false.
let lessThan5 = true;
let j = 0;
while(lessThan5) {
}
We didn't learn anything about using boolean values in while loops and I feel like I'm meant to infer what to do, and what structure to use and I just have no idea. Aside from the fact I feel like the instructions to many of these questions are poorly worded, which only confuses me more!
So then there's this third one:
// Example of what the number game would look like:
// Couple things to note:
// Math is a built in object in javascript.
// Math.round() will round a decimal number to a whole number.
// Math.random() returns a decimal number between 0 to 1.
// (But not including 1)
function guessNumberGame(guess) {
let guessing = true;
let number = Math.round(Math.random() * 100);
while(guessing) {
if(guess === number) {
guessing = false;
} else {
guess = Number(prompt("That number didn't work. Try again: "));
}
}
}
// Problem 3
// We will give you a number through the 'num' parameter
// Create a while loop that will loop 'num' amount of times.
// For example if num is 3 then your while loop should loop 3 times
// If num is 20 then the loop should loop 20 times.
// Increment k every loop.
let k = 0;
function keepLooping(num) {
}
If this Problem 3 is meant to be related somehow to the number game example, I can't see it. I don't even know what it is I need to be asking. Does this make any sense to anyone? And nobody else is publicly asking questions about any of this, and it's making me feel stupid and like I am the only one too dumb to get what's going on. I was doing really well and ahead of schedule with all this until this point, but just none of this is making any sense to me.
Welcome to programming, JavaScript (JS), and StackOverflow (SO)!
Let's dive into this a little deeper. First, a quick JavaScript primer: in JavaScript, everything can be classified as either an expression or a statement. At a super high and not-technical level:
expression: something that produces a value
statement: an instruction to the computer
(For a much longer explanation, see here)
Often, statements have slots that can take expressions. Loops are a great example of that.
For example, 1 + 1 is an expression, since it produces the value 2. Even more simply, 1 on its own is also an expression, since it produces the value 1. while(/*some expression here*/) is a statement that has a slot for an expression. for(s1, e2, e3) is also a statement that has slots for statements and slots.
So, the while loop acts on an expression, and will continue to loop as long as the value returned by that expression is truthy. truthy and falsey is an interesting concept in JavaScript and can be a whole essay on it's own, but the tl;dr of it is that anything that == true is truthy, and anything that == false is falsey
So for your first question, 0 < 5 == true, while 5 < 5 == false. Thus, if you make the value of j be greater than or equal to 5, the loop will break.
let lessThan5 = true;
let j = 0;
while(lessThan5) {
// For each cycle of the loop, check if `j` is less than 5
if (j < 5) {
// If `j` is less than 5, increment it
j++; // This is equivalent to saying j = j + 1, or j += 1
} else {
// If `j` is not less than 5, set `lessThan5` to `false`
// Not when the loop goes to iterate again, `false == false`, and it stops
lessThan5 = false;
}
}
I think given the above you should be able to solve the third problem. Please let us know if you have trouble with it, show us what you try, and we'll be happy to help some more :)
Let's take a deep breath and relax. I'm a very senior developer and can't tell -- from your examples -- what's going on here. Maybe that's because your instructor is terrible, maybe it's because you've missed some context in your class, and so it's omitted from the question.
I can answer the two questions you've been given. Hopefully it'll be helpful.
First:
I do not know why your materials claim that a while loop might be written this way. I've completed the assignment, but it seems very odd. But if they want you to complete it, here's a solution.
// Another way to write a while loop is to have a boolean variable
// where the condition goes and then test every time if you need to
// change the boolean to false.
// Below we have a variable lessThan5 and it is set to true.
// Create a loop that tests if our variable 'j' is less than 5.
// If it is less than 5 then Increment it by 1. If it is not
// less than 5 then set our lessThan5 variable to be false.
let lessThan5 = true;
let j = 0;
while(lessThan5) {
if (j >= 5) {
lessThan5 = false;
} else {
j++;
}
}
Moving on to the second snippet, the second snippet does not, to me, appear to be related to guessNumberGame in any way.
And the solution to "Problem 3" seems useless to me. A loop that doesn't do anything is not useful in real life.
That said, the solution to "Problem 3" is as follows:
// Problem 3
// We will give you a number through the 'num' parameter
// Create a while loop that will loop 'num' amount of times.
// For example if num is 3 then your while loop should loop 3 times
// If num is 20 then the loop should loop 20 times.
// Increment k every loop.
let k = 0;
function keepLooping(num) {
while(k < num) {
k++;
}
}

What does an if (number) return?

I seem to be having a hard time understanding what this does to my code?
const $counters = $('.js-item-counter')
if($counters.length)
{
}
What would this if statement return?
I can tell that the value is 1, but does this make sense?
I am trying to fix some frontend issues, and ran into something like this..
In Javascript, 0 is a falsey value. Anything other than 0 is considered true.
So what your code is doing is, it is making sure that the $counters is present in the DOM because if it were, it would give the length of > 0.
.length property tells you how many elements of the given selector are present in the DOM. If it is 0, then the element isn't present. If it is more than 0, then the element is present and you can act upon it as you wish.
The if statement will return true or false based on the condition.
If $counters.length > 0, it will return true and if block will be executed. Otherwise, it will return false and block won't be executed.
It returns true if the number inside the if statement is greater than or equal to 1 and false if it is 0.
It's a simple test to see if any elements of that class exist. Using length of a jQuery object is the most common jQuery approach to count matches in the collection
If it is anything other than zero it is truthy and zero is falsy
There used to be a size() method but that was deprecated and if you read in it's docs it tells you to use length instead
if the target element is stand for integer that having initial value of 1, then you should do this way
if($counters > 1)
{
//note length is only for checking of element existance
}
length coerced to true for any length other than 0 and false for 0:
console.log(
!!0,
!!1,
!!10
);

Javascript loops

Im confused about JavaScript loop types.
for loop
I learned that this loop looping until condition isn't false. If it false on first try it will never run.
for (var i = 0; i < 9; i++) {
console.log(i);
}
while
It runs loop until condition isn't false. If it is false on first try, loop never starts.
var n = 8;
while (n < 9) {
n++;
console.log(n)
}
But i is 8 and n resulting into 9
questions:
In for loop is condition true even if i = 8 - 8 is less than 9 so loop should increase i at number 9.
Descricption of this two loops are pretty much the same whats the diference between them?
You see a difference because the last expression of a for loop runs after each iteration.
That means the following codes are equivalent:
for (var /* VariableDeclarationList */; /* Expression 1 */; /* Expression 2 */) {
/* StatementList */
}
var /* VariableDeclarationList */;
while (/* Expression 1 */) {
/* StatementList */
/* Expression 2 */
}
But when transforming to a while loop, you placed the expression n++ before the statements.
https://www.codecademy.com/en/forum_questions/510e3c1a3011b8fa25005255:
For Loops allow you to run through the loop when you know how many
times you'd like it to run through the problem such as for (var i; i
< 10; i++); this will continually increase i untill that condition
returns false, any number can replace the 10 even a variable. but it
will quit once the condition is no longer being met. This is best used
again for loops that you know how when they should stop.
While Loops allow you a little more flexability in what you put in it,
and when it will stop such as while ( i < 10) you can also substitue
in a boolean(true/false) for 10 as well as many other types of
varibles.
The key difference between the two is organization between them, if
you were going to increase to 10 it'd be a lot cleaner and more
readable to use a for statement, but on the other hand if you were to
use an existing variable in your program in your loop parameters it'd
be cleaner to just wright a while loop. In the For loop you MUST
create a new variable, thats not true for the While loop.

JavaScript: What will break, and what will break it? [closed]

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 8 years ago.
Improve this question
Potentially dangerous code below, line 2
Repeat: POTENTIALLY DANGEROUS CODE BELOW
var history = "";
for (start = 3; start = 1000; start += 1){
if(start % 5 == 0 || start % 3 == 0)
history += start + " "; }
Okay, this is the tenth time I've put JavaScript code in that's frozen my browser. It's putting my computer in shock. Are these panic attacks going to destroy her heart? Where can I learn about all the crap that might break my computer as I continue to learn and practice JavaScript? I'm looking for an exhaustive list, only.
Your loop: for (start = 3; start = 1000; start += 1){
The second part of a for( ; ; ) loop is the condition test. The loop will continue until the second part evaluates to false. To not create an infinite loop, change your code to:
for (var start = 3; start < 1000; start += 1){
Note: start+=1 is equal to start++. If you want a compact code, you can replace +=1 by ++.
An overview of the three-part for-loop, for(initialise; condition; increment):
initialise - Create variables (allowed to be empty)
condition - The loop will stop once this expression evaluates to false
increment - This expression is executed at the end of the loop
Always check against infinite loops: Make sure that the condition is able to evaluate to false.
Commonly made mistakes:
A negative incremental expression in conjunction with a is-lower-than comparison:
i-- decreases the counter, so i<100 will always be true (unless the variable i is initialized at 100)
A positive incremental expression in conjunction with a is-higher-than comparison.
A non-incrementing expression: for(var i=0,j=0; i<100; j++) (i doesn't increase)
A condition which is always true (such as in your case)
You just have to learn and read about it properly. Your loop condition start = 1000 will always evaluate to true, that's why the loop never terminates (an assignment returns the value which was assigned and any other number than 0 is evaluates to true).
The MDN JavaScript Guide is a great resource for learning JavaScript. Particular for this situation:
A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop. A for statement looks as follows:
for ([initialExpression]; [condition]; [incrementExpression])
statement
When a for loop executes, the following occurs:
The initializing expression initialExpression, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables.
The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the for loop terminates. If the condition expression is omitted entirely, the condition is assumed to be true.
The statement executes. To execute multiple statements, use a block statement ({ ... }) to group those statements.
The update expression incrementExpression, if there is one, executes, and control returns to step 2.
As the others said, it mostly comes down to try and error.... that is a good way of learning anyway.
your conditional statement start=1000 will always return true. You cant found such fool proof's list for this, you have to learn from these mistakes on your own.
Uh - what did you wanted here ?
for (start = 3; start = 1000; start += 1)
do you wanted this ? ( from 3 to 1000 )
for (start = 3; start <= 1000; start += 1)
in first case you will stuck on 1000

Simple Confusing Loops and Variable working

In this question,I'm asking how the following snippets work, as it involves weird use of variable:
while (+(+i--)!=0)
{
i-=i++;
}
console.log(i);
Interesting problem... you've tagged it Java, JavaScript and C -- note that while these languages have the same syntax, this question involves very subtle semantics that may (I'm not sure) differ across languages.
Let's break it down:
+(+i--)
The -- postfix decrement operator is most tightly bound. So this is equivalent to +(+(i--)). That is therefore equivalent to the value of +(+i) (that is, i), but it also decrements i after taking the value. It compares the value with 0 to see if the loop should continue. Thus, while (+(+i--)!=0) is equivalent to the following:
while (i-- != 0)
Note that it also performs i-- at the end of the loop.
Inside the loop, I believe you have some undefined behaviour, at least in C, because you are referencing i on the right, and also updating i on the left -- I believe that C doesn't define which order to do that in. So your results will probably vary from compiler to compiler. Java, at least, is consistent, so I'll give the Java answer. i-=i++ is equivalent i = i - i++, which is equivalent to to reading all the values out of the expression, computing the result of the expression, applying the post-increment, and then assigning the result back. That is:
int t = i - i; // Calculate the result of the expression "i - i++"
i++; // Post-increment i
i = t; // Store the result back
Clearly, this is the same as writing i = 0. So the body of the loop sets i to 0.
Thus, the loop executes just one time, setting i to 0. Then, it decrements i one more time on the next while loop, but fails the check because i (before decrementing) == 0.
Hence, the final answer is -1, no matter what the initial value for i is.
To put this all together and write an equivalent program:
while (i-- != 0)
{
int t = i - i;
i++;
i = t;
}
console.log(i);
When I tried it in Java and JavaScript, that's what I got. For GCC (C compiler), it gives -1 only when i starts out as 0. If i starts out as anything else, it goes into an infinite loop.
That's because in GCC (not necessarily all C compilers), i-=i++ has a different meaning: it does the store back to i first, then does the post-increment. Therefore, it is equivalent to this:
int t = i - i; // Calculate the result of the expression "i - i++"
i = t; // Store the result back
i++; // Post-increment i
That's equivalent to writing i = 1. Therefore, on the first iteration, it sets i to 1, and then on the loop, it checks whether i == 0, and it isn't, so it goes around again, always setting i to 1. This will never terminate, but for the special case where i starts out as 0; then it will always terminate the loop and decrement i (so you get -1).
Another C compiler may choose to act like Java instead. This shows that you should never write code which both assigns and postincrements the same variable: you never know what will happen!
Edit: I tried to be too clever using that for loop; that wasn't equivalent. Turned back into a while loop.
That's soooo wierd! (I love it)
first, you can forget about the +(+...) part, it's just like saying 1 + (+1) = 2.
i-- means i = i - 1. In your while condition, you test if i-- is different from 0. Note: the test is made on i != 0 and then i's value is changed. If you wanted to change its value before the test, you should have used --i instead.
As for the i -= i++, it's a very dumb way to say i = 0. You must read it from right to left: i = i + 1 and then i = i - i1 (whatever value of i you have, you'll end up with 0.
Simplier quivalent snippet:
while (i-- != 0) {
i = 0;
}
console.log(i);
1 a -= b means a = a - b.
i -= i++ would mean a similar thing to i = i-i; i++ (if you make the -= explicit).
In a similar fashion, you can pull the side effect of i-- out of the loop condition by
transforming while (foo(i--)) { ... } to while (foo(i)) { i--; ...} i--; (you need to put it both in the loop body and after the loop because, at the end, the condition will be false and the loop body will not be executed but execution continues after the while loop).
The while condition evaluation happens based on operator precedence. I have used explicit braces to help understand the evaluation:
(+(+(i--)) != 0) which is equivalent to using (i-- != 0) as the '+' are just unary operators.
The expression i -=i++; is equivalent to i = i - i++; where the LHS expression gets evaluated from left to right.
i = 4;
while (+(+i--)!=0) //here i would be decremented once to 3.
{
i-=i++; // here i = 3 - 3 = 0; even though i has been incremented by 1 its value is set to 0 with this assignment
}
This is very simple. And I think the only reason to code like this is a concept called "code obfucasion" or "code confusing". This way makes the code harder to read and debug, so that can prevent from reverse engineer your code :-)

Categories

Resources