Variable declaration reset
A decidely non-challenging task to highlight a potential difference between programming languages.
Using a straightforward longhand loop as in the JavaScript and Phix examples below, show the locations of elements which are identical to the immediately preceding element in {1,2,2,3,4,4,5}. The (non-blank) results may be 2,5 for zero-based or 3,6 if one-based.
The purpose is to determine whether variable declaration (in block scope) resets the contents on every iteration.
If your programming language does not support block scope (eg assembly) it should be omitted from this task.
JavaScript
<lang javascript><!DOCTYPE html> <html lang="en" >
<head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>variable declaration reset</title> </head> <body> <script>
"use strict"; let s = [1, 2, 2, 3, 4, 4, 5]; for (let i=0; i<7; i+=1) {
let curr = s[i], prev; if (i>1 && (curr===prev)) { console.log(i); } prev = curr;
}
</script> </body>
</html></lang>
No output
Changing the third "let" to "var" (causes legacy hoisting and) gives:
- Output:
2 5
Phix
with javascript_semantics sequence s = {1,2,2,3,4,4,5} for i=1 to length(s) do integer curr = s[i], prev if i>1 and curr=prev then ?i end if prev = curr end for
- Output:
3 6
Like the first JavaScript example, under pwa/p2js there is no output (at least as things currently stand)