Does C have a “foreach” loop construct?

C doesn’t have a foreach, but macros are frequently used to emulate that: And can be used like Iteration over an array is also possible: And can be used like Edit: In case you are also interested in C++ solutions, C++ has a native for-each syntax called “range based for”

Short circuit Array.forEach like calling break

There’s no built-in ability to break in forEach. To interrupt execution you would have to throw an exception of some sort. eg.  Run code snippetExpand snippet JavaScript exceptions aren’t terribly pretty. A traditional for loop might be more appropriate if you really need to break inside it. Use Array#some Instead, use Array#some:  Run code snippetExpand snippet This works because some returns true as soon as any of the … Read more

Short circuit Array.forEach like calling break

There’s no built-in ability to break in forEach. To interrupt execution you would have to throw an exception of some sort. eg.  Run code snippetExpand snippet JavaScript exceptions aren’t terribly pretty. A traditional for loop might be more appropriate if you really need to break inside it. Use Array#some Instead, use Array#some:  Run code snippetExpand snippet This works because some returns true as soon as any of the … Read more

break out of if and foreach

if is not a loop structure, so you cannot “break out of it”. You can, however, break out of the foreach by simply calling break. In your example it has the desired effect: Just for completeness for others that stumble upon this question looking for an answer.. break takes an optional argument, which defines how many loop structures it should break. Example: … Read more

Why is “forEach not a function” for this object?

bject does not have forEach, it belongs to Array prototype. If you want to iterate through each key-value pair in the object and take the values. You can do this: Usage note: For an object v = {“cat”:”large”, “dog”: “small”, “bird”: “tiny”};, Object.keys(v) gives you an array of the keys so you get [“cat”,”dog”,”bird”]

How do I apply the for-each loop to every character in a String?

The easiest way to for-each every char in a String is to use toCharArray(): This gives you the conciseness of for-each construct, but unfortunately String (which is immutable) must perform a defensive copy to generate the char[] (which is mutable), so there is some cost penalty. From the documentation: [toCharArray() returns] a newly allocated character array whose length is the length of this string and whose contents are … Read more