Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Yoko Oh Noes confused about hoisting and loops #733

Open
lgto4 opened this issue May 22, 2020 · 4 comments
Open

Yoko Oh Noes confused about hoisting and loops #733

lgto4 opened this issue May 22, 2020 · 4 comments

Comments

@lgto4
Copy link

lgto4 commented May 22, 2020

See the demo program at https://www.khanacademy.org/computer-programming/confused/5208304615768064 . It attempts to initialize a variable declared inside the body of a loop to undefined causing the complaint "It's not necessary to initialize 't' to 'undefined'." which is certainly not the case.

@pamelafox
Copy link
Collaborator

Huh. Thanks for the report, Bob!

@Steffan153
Copy link

This is actually one of the really catchy things about JS, it can be pretty confusing. I guess Oh Noes just hasn't learned enough JS to understand 😂

If let/const was supported though, we wouldn't have to worry about this of course.

@1point7point4
Copy link

1point7point4 commented Feb 23, 2021

In Ono-chan's defense, it's usually not considered good practice to initialize a variable multiple times in the same scope; I think the more commonplace approach would be something like:

var t;
for (var i = 0; i < 10; i++) {
        t = undefined;
        if (random() < 0.2) {
            t = 1;
        }
        if (t) {
            println(i + ". bingo");
        }
    }

edit: that being said, i still think this should be considered a bug and not a feature

@vijjuu787
Copy link

vijjuu787 commented Sep 27, 2024

it's usually not considered good practice to initialize a variable multiple times in the same scope.
initialize t=0 ;
`
var t = 0; // Set t to a falsy value initially
var doit = function() {
for (var i = 0; i < 10; i++) {
if (random() < 0.2) {
t = 1;
}
if (t) {
println(i + ". bingo");
}
}
};

doit();
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants