Trying to rewrite for loop, get jslint error - javascript

I'm trying to combine various code so I want to declare the start of i ahead of time.
OLD
var i,
max_i = 4;
for (i = 2; i<= max_i; i += 1)
{
//things
}
NEW
var i = 2,
max_i = 4;
for (; i<= max_i; i += 1)
{
//things
}
The problem is that I am getting various errors in JSLint
Expected ')' and instead saw '<='.
Expected ';' and instead saw 'i'.
Expected '{' and intead saw 'max_i'.
The code executes fine in both cases.

for (i; i<= max_i; i += 1)
{
//things
}

JSLint helps you write better code, have faith in it, it's not about taste or else.
It complains because not initializing the for() is considered ugly (bad style).
You should initilize it as always. I would also go as far as to not define variables but declare them, and then initialize them as shown below. I would also use "use strict" nowadays. Not doing so is kind of unpleasant. The outer function is to avoid globals and non-function-scoped code:
/*jslint for */
(function () {
"use strict";
var i;
var max_i;
max_i = 4;
for (i = 2; i <= max_i; i += 1)
{
// things
}
}());

You can pre-declare and initialize i, but you must still set it as the loop variable in the loop configuration. And, it is clearer if you initialize it in the loop configuration, rather than above because debugging will be easier.
var i , max_i = 4;
for (i = 2; i <= max_i; i++) {
//things
}
Also, it is better to always place the opening curly-brace (}) on the same line as the statement it defines as there are certain cases in JavaScript, where placing it on the next line down can cause bugs in the code due to automatic semi-colon insertion.
Lastly, to increment a value by one, you can use the ++ unaray operator, instead of +=1.

Related

What is a statment prefix in Javascript? [duplicate]

what does the following code meaning? (it is not json - it is code which does not generate error by js interpreter)
foo: 5
The reason for the question is as follows. In the arrow function examples there is one that shows the confusion between json and code block syntax:
var func = () => { foo: 1 };
The func() returns undefined and the above code does not fail. I tried to put just the foo: 5 code as the only code in a js module - and it works... I do not know about a ':' operator neither about labels in js.
It's a JavaScript label: documentation here.
You can use a label to identify a loop, and then use the break or continue statements to indicate whether a program should interrupt the loop or continue its execution.
Note that JavaScript has NO goto statement, you can only use labels with break or continue.
Example usage (from MDN)
var itemsPassed = 0;
var i, j;
top:
for (i = 0; i < items.length; i++){
for (j = 0; j < tests.length; j++) {
if (!tests[j].pass(items[i])) {
continue top;
}
}
itemsPassed++;
}

What happens if you put an iteration count of a for loop as a variable?

I want to make a program in javascript in which a person inputted the iteration count for a for loop(they could input x++, or y--), but I don't know if I am using the right method.
Here is my code:
var x = prompt("iteration count")
// x should equal something like, i++, or x--
for(var i = 0; i < 10; x){
document.write(i)
}
But when the code ran the program kept crashing.
Why is it crashing and how do I fix this?
Please Help
you need to parse the int value of x because it's a string and use it to increment i
var x = parseInt(prompt("iteration count"))
for (var i = 0; i < 10; i += x) {
document.write(i)
}
EDIT :
based on the question edit and the comments, you can use eval(), but :
Do not ever use eval!
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller.
So before you use it, read the MDN page and check : eval isnt evil it's just misunderstood
where there's this comment from Spudley :
From a security perspective, eval() is far more dangerous in a server
environment, where code is expected to be fully trusted and hidden
from the end user.
In a browser, the user could eval any code they wanted at any time
simply by opening dev tools, so as a developer you can't get away with
having anything on your client code that could be insecure against
eval anyway.
to test the snippet below, type i++ in the prompt
var x = prompt("iteration count");
for (var i = 0; i < 10; eval(x)) {
console.log(i)
}
an alternative to eval() would be new Function or check the answers here : Programatically setting third statement of for loop
var input = 'i++';//Or whatever condition user passing in
var conditionProgramatically = () => new Function(input)() ;
for (var i = 0; i < 10; conditionProgramatically()) {
console.log(i)
}
For for-loop, third statement will be invoked/executed on every iteration, and hence we set a function call, and in that function, we execute whatever user passing in as you've mentioned i++
That is an endless loop because the variable i never incremented. Try this one.
var x = prompt("iteration count")
for(var i = 0; i < x, i++){
document.write(i)
}
You forgot to increment the index variable, it result to endless loop and maximum stack error, you can also use + for parseInt shorcut.
var x = +prompt("iteration count")
for(var i = 0; i < x;i++){
document.write(i)
}
You have to parse the input value and then make it as a condition to stop iterating after the given value.
var x = parseInt(prompt("iteration count"))
for (var i = 0; i < x; i++) {
document.write(i);
}

JavaScript: setInterval and for loop explanation

i searched around for a couple of questions related to the use of the for loop and the setInterval function in JavaScript but i couldn´t find a concrete answer on why this snippet doesn´t work. Could someone explain please what´s happening under the hood and why this code doesn´t print anything at all?
for (let i = 0; i++; i < 10) {
window.setInterval(function () {
console.log('Test');
} , 100)
}
Your for loop is not correct. The condition needs to be the second statement in the for loop.
Following code should work.
for (let i = 0; i < 10 ; i++; ) {
window.setInterval(function () {
console.log('Test');
} , 100)
}
Expected Syntax for loop. You can read more here
for ([initialization]; [condition]; [final-expression])
statement
EDIT 1:
Though all answers (including mine) mentioned that condition needs to be second statement in the for loop which is correct. There is one more additional important behavior.
The for loop for (let i = 0; i++; i < 10) is actually correct in terms of grammar and even the javascript runtime executes this code.
But, as in your case, if the condition is evaluating to falsy value then it would exit the loop.
Breaking your for loop for (let i = 0; i++; i < 10) into each seperate construct
Initialization: let i = 0; This statement initializes the value of variable i to 0.
Condition: i++; Javascript evaluates the statement to check if the statement is true or not. In case of i++ the runtime firstly checks for the current value of i which is 0 . Since 0 is considered a falsy value the condition evaluates to false and hence the statement is not executed. Also, i++ statement is a post increment which basically increments i and then result the original value of i.
So, if you would have written loop like below, using the intiliaztion of i=1, then it would have worked, though it would be running infinitely untill the browser/Server crashes as the condition i++ would always evaluate to true. I hope that makes sense.
for (let i = 1; i++; i < 10) {
// Statements would run
}
Or
for (let i = 0; ++i; i < 10) { **// Pre increment**
// Statements would run
}
Or
for (let i = 0; i=i+1; i < 10) { **// increment i by assigment
// Statements would run
}
Douglas Crockford in his book Good Parts mention about the usage of ++ & -- and how it can confuse readers.
your for loop syntax is wrong, should be
for (let i = 0; i < 10; i++)
your setInterval code will run every 100 milliseconds for each iteration of the loop (so 10 times every 100 milliseconds)
Nothing to do with setInterval, you simply malformed your for loop:
This:
for (let i = 0; i++; i < 10)
Should be this:
for (let i = 0; i < 10; i++)
First declare the initial state of the loop, then the terminating state of the loop, then the incremental change of the loop.
Observe.

Is it possble to do comparion of two variables in javascript of different types

I am having a jstree and in javascript function i am checking which node has been selected thats working fine. But when i assign that node value to a variable then do comparasion with a normal string variable thats not working.
$(document).ready(function() {
$('#bdeViewNew').on('changed.jstree', function(e, data) {
var i, j, r = [];
for (i = 0, j = data.selected.length; i < j; i++) {
var x = data.instance.get_node(data.selected[i]).text;
r.push(data.instance.get_node(data.selected[i]).text);
if(x=="Hadoop")
{alert("hi");}
else{
alert("hello");
}
}
});
});
any one know how we can do such comparasion?
thanks in advance
It is possible that your variable has some unexpected whitespace at the start or the end, that's a common problem. You should be able to get rid of it with
var x = data.instance.get_node(data.selected[i]).text.trim();
Should work on all modern browsers.
Also keep in mind that JavaScript has function scope, not block scope like you might be used to from C/C++ or Java. The x you declare there is visible throughout the function, not just in the for loop. You should probably declare it at the same time as i, j and r.

Problem with using javascript to insert <input> tags in html

I am trying to take text that is in an array (one word per value) and insert it into html. All the code is here: http://jsfiddle.net/chromedude/r6wVq/3/.
Update:
My question is what am I doing wrong? It does not do anything which is weird.
Just for everybody who was wondering what this code is supposed to help me do is memorize long passages for school.
You have an infinite loop, that's why the browser crashes:
for (i = 0; i < text.length; i++) {
var currentText = text[i];
for (i = 0; i<blanks.length; i++){}
}
The second loop always resets the counter variable i to 0. If you have nested loops you have to use different variables. And use var to declare the variables as local, e.g.
for (var i = 0; i < text.length; i++) {
var currentText = text[i];
for ( var j = 0; j<blanks.length; j++){
}
}
Same for your most outer for loop!
I don't know exactly what you want to achieve with the code, but here are some comments:
var blankNum = Math.random(Math.floor() * (text.length / 2));
Math.random takes no parameter, but Math.floor does.
for (i = 0; i < blanks.length; i++) {
blanks is still empty at this point, so the loop will never run.
if (currentText==blanks[i]){
Are you sure that blanks[i] will contain text? The previous mentioned (never running) loop seems to add numbers to the array.
textPrelim = <input type="text"></input>
You get a syntax error here, you must enclose the string into quotes.
I fixed your fiddle: http://jsfiddle.net/yEKPt/1/
What was wrong:
for iterator scope (here)
This line (27) threw a syntax error:
textPrelim = <input type="text"></input> //Needs to be quoted.
Should be:
textPrelim = '<input type="text"></input>'; //Quoted.
You reversed Math.random and Math.floor (lines 8, 14). (See: Math.Random(), Math.Floor())
var blank = Math.random(Math.floor() * (text.length / 2));
Check out my revised version. I think it accomplishes what you were looking for?
With addition to Felix's answer, try to check your code at http://www.jslint.com for syntax errors and undeclared (implicitly global) variables.

Categories

Resources