Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment in while loop - Javascript

I have strange situation - here is Javascript code - and in NetBeans IDE 8.0 I see an alert "Expected a conditional expression and instead saw an assignment":

var elem;
var a = 0;
while ((elem = document.getElementById('id-' + a)) !== null) {
    //Some code
    a++;
}

But code works fine. Maybe this is some bug in Netbeans IDE 8.0?

like image 533
Ernestas Gruodis Avatar asked Jan 23 '15 10:01

Ernestas Gruodis


People also ask

Do while loops assignment?

A do while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given boolean condition at the end of the block. Some languages may use a different naming convention for this type of loop.

How does a while loop work in JavaScript?

The while loop starts by evaluating condition . If condition evaluates to true , the code in the code block gets executed. If condition evaluates to false , the code in the code block is not executed and the loop ends.

What is the purpose of the while () method?

A "While" Loop is used to repeat a specific block of code an unknown number of times, until a condition is met. For example, if we want to ask a user for a number between 1 and 10, we don't know how many times the user may enter a larger number, so we keep asking "while the number is not between 1 and 10".

Do While loop in JavaScript execute?

The do... while statement creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.


1 Answers

The code is fine. The IDE's warning is because usually a comparison (==) is made, but sometimes an assignment (=) is what is actually wanted. It's to catch mistakes made by missing an equals sign.

Here, you set the elem variable, and at the same time, compare it to null.

like image 112
Scimonster Avatar answered Sep 28 '22 06:09

Scimonster