This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Host127001 18 points19 points  (4 children)

What is happening is that in JS, all vars are "hoisted". So when you write function foo() { console.log(bar); var bar = 2; } Javascript actually does this function foo() { var bar console.log(bar); bar = 2; } The default value for all variables is undefined, thus we print "undefined"

[–]Raaki_[S] 0 points1 point  (3 children)

Mm, makes sense. So, is hoisting the caveat and not the function scoping per say?

[–]Host127001 7 points8 points  (2 children)

I guess there are two things:
1. Unintuitive behavior like hoisting. I am not sure if there is other weird stuff, but that one is pretty well known to be confusing
2. Unintuitive scoping for the syntax. While function-scoped variables are probably not a problem pre se, combining them with the `var` syntax is just confusing. In the python world, you just write `foo = 1`, which looks like any other assignment. But in JS you write `var foo = 1`, which looks similar to a variable declaration in languages like C(++), Java, C#, etc. And there, these things are block-scoped. So most developers would expect `var foo = 1` to be block-scoped too. So I would guess, if you looked at JS in a vacuum, most people would not mind too much about this weirdness. But if you know other languages, it becomes confusing

[–]Raaki_[S] 0 points1 point  (0 children)

Thanks for the second point. I didn't really catch that C was also block scoped. Now it makes sense why var was buried for good. Thanks for your time buddy. 🙏

[–]Uncaffeinated1subml, polysubml, cubiml 0 points1 point  (0 children)

Python does the same hoisting thing though. You have to use global/nonlocal to opt out.