In programming languages such as JavaScript or Python, if you declare a variable in a block scope (if statement, for statement, ...) the variable is hoisted to the outer function scope. E.g.
JavaScript - var
for(var i = 0; i < 10; i++) {
console.log(i); //outputs 1-9
}
console.log(i); //outputs 10
Python
for i in range(1,10):
print(i) //outputs 1-9
print(i) //outputs 9
I other languages such as C# and JS(using let or const), if a variables is declared in a block scope, then the variable is not hoisted to the outer scope. E.g.
C#
using System;
class MainClass {
public static void Main (string[] args) {
for(int i = 0; i < 10; i++) {
Console.WriteLine(i);
}
Console.WriteLine(i); //error i does not exist here
}
}
JavaScript - let
for(let i = 0; i < 10; i++) {
console.log(i); //outputs 1-9
}
console.log(i); //error i not defined
What other programming languages implement this type of variable scope hoisting?
Mensah Oliver
Student
JavaScript - var