TIL 1: Labeled Statements in Javascript
Today I learned about the labeled statement construct in Javascript.
While working through The Modern JavaScript Tutorial, I came across this language feature as a way of controlling the flow of an outer loop from within an inner loop (labels for break/continue).
Here’s an example of how you can use a labeled statement to break out of an outer loop from within an inner loop:
function someCondition(i, j) {
return i === 2 && j === 2;
}
// Using break with a label
outerBreakLoop:
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
if (someCondition(i, j)) {
break outerBreakLoop; // Breaks out of both loops
}
console.log(`break example: i = ${i}, j = ${j}`);
// Output:
// break example: i = 1, j = 1
// break example: i = 1, j = 2
// break example: i = 1, j = 3
// break example: i = 2, j = 1
}
}
Having been coding mainly Ruby for the past few years, I found this feature interesting as Ruby doesn’t have a direct equivalent to labeled statements. I wasn’t sure if Ruby did or didn’t at first, so I went ahead and asked ChatGPT if it did, and it hallucinated some code that is not valid Ruby.
outer_loop:
(1..3).each do |i|
(1..3).each do |j|
if some_condition(i, j)
next outer_loop
end
puts "#{i}, #{j}"
end
end
So I guess today I learned not to trust ChatGPT for Ruby syntax as well 😅 (though it’s usually pretty good).