This question already has answers here:
Unknown JavaScript syntax before for...in
(3 answers)
Closed 7 years ago.
While reading code from some project, I stumbled on this KEYVAL:
KEYVAL:
for(key_name in arg_map) { // iterates over hash key|value pairs
// if this key_name belongs to this object, not proto
if(arg_map.hasOwnProperty(key_name)) {
// skip dependent keys during iteration
if(key_name.indexOf('_') === 0) { continue KEYVAL; }
// update independent key value
anchor_map_revise[key_name] = arg_map[key_name];
// update matching dependent key
key_name_dep = '_' + key_name;
if(arg_map[key_name_dep]) {
anchor_map_revise[key_name_dep] = arg_map[key_name_dep];
} else {
delete anchor_map_revise[key_name_dep];
delete anchor_map_revise['_s' + key_name_dep];
}
} // if end
} // for end
What is that? What the purpose of this? Is it part of JS syntax?
It is a label. A label is an identifier (here: KEYVAL), followed by a colon (:), that precedes a statement (in this case, for).
A continue or break statement can use a label (in your case continue KEYVAL) to specify which loop to continue with, or break from. In this case, the KEYVAL: for is the innermost loop, so the label is actually not necessary; but labels are useful if you need to break from several levels at once.
See more on MDN.
EDIT: for, not while.
Related
This question already has answers here:
Short circuit Array.forEach like calling break
(30 answers)
Closed 3 years ago.
I'm working on a homework problem using JavaScript. I have a solution that currently works, but I am sure that it is not the most efficient way to do it. I am iterating over an array to check if any element meets a certain condition. But there doesn't seem to be a way to exit the forEach() function early. In other languages, I have used break to quit a forEach loop early. Does something similar exist in JavaScript?
My code (simplified for this question):
let conditionMet = false;
numbers.forEach((number) => {
if (number % 3 === 0) {
conditionMet = true;
// break; <-- does not work!
}
});
Rather than using Array.forEach, you can use Array.some (see docs). This function iterates over the elements of the array, checking to see if any element meets a certain condition. If an element is found that meets the condition, the function stops iteration, and returns true. If not, the function returns false. This means that you can also skip the step of initializing conditionMet to false.
Your code can therefore be simplified as:
let conditionMet = numbers.some(number => (number % 3 === 0));
You can’t break .foreach() loop unless through an exception
So you can choose another tool like a simple for loop.
This question already has answers here:
JavaScript Possible Iteration Over Unexpected
(5 answers)
Why is using "for...in" for array iteration a bad idea?
(28 answers)
Closed 5 years ago.
I use phpstorm and over the past half a year or so it started warning me about code like this:
for( let key in attachmentPaths ){
requestObject.formData.attachments.push( fs.createReadStream(attachmentPaths[key]) )
}
Warning on [key]
Possible iteration over unexpected (custom/inherited) members,
probably missing hasOwnProperty check
I understand the warning message, but i don't understand how a for() like this is bad?
Surely additional checks to ensure the key exists with the object is silly as we are looping over the objects found keys..?
Surely additional checks to ensure the key exists with the object
That isn't what the error message says.
The important part is "unexpected (custom/inherited) members".
You could find yourself dealing with extra properties that you weren't expecting which are inherited on the prototype chain.
Consider:
Object.prototype.surprise = "surprise!";
var foo = {
a: 1,
b: 2
};
for (var bar in foo) {
console.log(bar, foo[bar]);
}
You have to check if the object has key if you want to use for in loop.
In javascript, everything is an object. You can assign functions to variables as well. With for ... in loop you are iterating all keys the object has. So if the object has a function that is assigned to a key in the object, you might try to iterate that as well (like the built in functions in strings/arrays etc.)
for( let key in attachmentPaths ){
if(attachmentPaths.hasOwnProperty(key){
requestObject.formData.attachments.push( fs.createReadStream(attachmentPaths[key]) )
}
}
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I'm trying to create "dynamic" cascading dropboxes, and I almost have it done. However, I'm running into an issue dealing with adding a .change() listener onto every variable inside of an array that contains the <select> field ids.
So if I use:
fields[0].change(function() {populateFields(1, 0, xml);});
fields[1].change(function() {populateFields(2, 1, xml);});
The code works perfectly. However, I would prefer to use something like this:
for (i=1; i<numberOfFields; i++){
p = i-1; current = i;
fields[p].change(function() {populateFields(current, p, xml);});
}
So that I can have a variable number of fields, because the current code is limited to three fields. The for loop currently works, but doesn't work after the second field is entered.
Any help would be appreciated.
NOTE: This is not a question about variables or passing variables into functions, but rather adding a event listener to an array. The marked answer was the correct answer.
You can use Array.prototype.forEach(), and in the function that you pass in you can put a guard for the case where you are processing the first element:
fields.forEach(attachChangeHandler);
function attachChangeHandler(field, i) {
if (i === 0) { return; }
field.change(function() {
populateFields(i + 1, i, xml);
});
}
This question already has answers here:
Best way to find if an item is in a JavaScript array? [duplicate]
(8 answers)
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 6 years ago.
Python programmer here.
I don't know how to write this. I tried using 'if !in' and '!if in', but I don't know how. Tried to Google it but got no results.
The correct syntax is
if(!condition){
expression();
}
Note that you need parenthesis around the condition.
#plalx wants a formal definition, and here you go:
IfStatement:
if(Expression) Statement else Statement
if(Expression) Statement
In case of any ambiguity the else would be matched with the nearest if.
If you have some value:
var excludeMe = "something unwanted";
Then you can use the following if statement:
if(myTestCase !== excludeMe) { //do something...}
Keep in mind that != does not check type and !== does check type. So, 1 != "1" is false and 1 !== "1" is true.
This question already has answers here:
Why does javascript accept commas in if statements?
(5 answers)
Closed 8 years ago.
I've searched in SO but I didn't find something similar. Maybe I am using wrong search keys.
I was editing a javascript library when I found this if statment
var a = location.hash.replace(/^#/, "");
if (container = $("#content"), a) {
..content
} else {
...other code
}
the first part container = $("#content") is assigning the value of $("#content") to container but I don't understand why there is a comma inside the If. Is it like an AND operator?
Something like if (container = $("#content") && a) ?
What is it evaluating?
The comma operator in JavaScript is pretty similar to the concept in other C-like languages. It's a way of stringing multiple expressions together into one (syntactic) expression. The value of the whole thing is the value of the last expression in the list.
Thus in this case, container = $("#content") is evaluated, and then a is evaluated. The value of the whole thing is the value of a.
A good question is why that code was written that way. There are times when the comma operator is useful, but usually it's just a way to save some typing and make code a little more concise.
It is comma operator.
Basically its doing two things. First there is assignment and then the , just evaluates a and validates against it in the if condition.