What is a statment prefix in Javascript? [duplicate] - javascript

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++;
}

Related

How javascript function body can be an object instead of a series of lines of code?

I've been reviewing how an old AngularJS solution works and in one of the controllers I've found the following code:
Array.prototype.update = function (newArray) {
loop: for (var newIndex1 = 0; newIndex1 < newArray.length; newIndex1++) {
var newItem = newArray[newIndex1];
for (var oldIndex1 = 0; oldIndex1 < this.length; oldIndex1++)
if (this[oldIndex1].Id === newItem.Id)
continue loop;
this.push(newItem);
}
loop1: for (var oldIndex2 = 0; oldIndex2 < this.length; oldIndex2++) {
var oldItem = this[oldIndex2];
for (var newIndex2 = 0; newIndex2 < newArray.length; newIndex2++) {
if (newArray[newIndex2].Id === oldItem.Id)
continue loop1;
}
this.splice(oldIndex2, 1);
}
};
Basically, an "update" function is added to standard Javascript Array that does some adding and removal of the items.
But how come the function body that is defined in curly braces is not a series of lines of javascript code (expressions), but is a javascript object with two properties loop and loop1.
As this seems to be valid javascript, where can I read about this style of definition to learn what is the logic of execution of this?
In the function code above, loop and loop1 are labeled block statements, as kindly noted by James in the comments to the original question.

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);
}

Trying to rewrite for loop, get jslint error

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.

HTML JAVASCRIPT goto label? [duplicate]

This question already has answers here:
How can I use goto in Javascript?
(16 answers)
Closed 6 years ago.
I need your help, I wish to do a "goto" like "goto" in batch :
:loop1
goto loop1
but in javascript for html page, all my research are useless...
it can be so usefull to know that !
in my case i need this code because i change a the same 'block of code' many times in different function, and there are to much variable to parse ...
so it can help my a lot
here a simple exemple of what i want to do :
for (var i=0; i < 999; i++) {
//some code here
goto go_to_1;
go_to_2:
//some code here
};
for (var i=0; i < 5; i++) {
//some different code here
goto go_to_1;
go_to_2:
//some different code here
};
function mytest () {
for (var i=0; i < 100; i++) {
//again some different code here
goto go_to_1;
go_to_2:
//again some different code here
};
};
go_to_1:
//code here
//always the same code here ,i change it many times
temp = "library"+i+"";
//code here
goto go_to_2;
is that possible ?
how use the "goto" function in javascript ?
Thank for you time
Thank for your help !
JavaScript has NO goto statement, you can only use labels with the break or continue.
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.
var i, j;
loop1:
for (i = 0; i < 3; i++) { //The first for statement is labeled "loop1"
loop2:
for (j = 0; j < 3; j++) { //The second for statement is labeled "loop2"
if (i === 1 && j === 1) {
continue loop1;
}
log.innerHTML += ('i = ' + i + ', j = ' + j + "<br/>");
}
}
<div id="log"> </div>
Please Take a look at these:
mozilla developers - js label
stackoverflow - js label

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.

Categories

Resources