I'm learning JavaScript but I'm really confused about how functions and variables work, especially when it comes to their scope and how they're defined. I started programming with Python and then moved on to Java and C++, where I felt like I understood more of what was happening. However, now that I'm diving into JavaScript, I keep seeing code that seems to rely on functions and variables that haven't been declared yet, and it leaves me wondering where they come from. For example, I might see something like:
```javascript
const myCode() {
this = getSomeFunction(someVariableThatHasntEvenBeenDeclared)
}
```
In this case, I'm not sure where `getSomeFunction` is defined or how it knows what to do with `someVariableThatHasntEvenBeenDeclared`. I understand that JavaScript is supposed to be high-level, but I'm feeling overwhelmed. Any resources or tips to help clarify this for me?
5 Answers
The distinction between how dynamically typed languages like JavaScript work versus statically typed ones (like C) is crucial here. In JavaScript, a function can be defined almost anywhere and doesn't require prior declaration. Understanding the context in which things are defined is essential, so you might need to look at the entire file and its included files to get the full picture.
It sounds like you might need to look up the functions you're running into. For example, if you find `getSomeFunction`, just search for it online and see what comes up. Understanding the parameters (like `someVariableThatHasntEvenBeenDeclared`) you pass to those functions is important too. This will help you learn how these functions are supposed to behave and what to expect from them.
JavaScript has evolved, and modern practices help with scope management. You typically use ES6 imports now to manage variables and functions, avoiding clutter in the global namespace. The key isn't that JavaScript is inherently confusing due to being high-level; it's about the quality of code you’re encountering. If you're seeing poorly structured code, it can definitely lead to confusion!
You're not alone! I started with C too, and it can be a lot to unpack when jumping into high-level languages like JavaScript. It's really normal to feel overwhelmed by things that feel hidden away. The key is practice and looking things up as you go. Functions and variables need to be defined somewhere, maybe even imported from other files, just like in Python and Java.
Totally! It takes time to adapt, but you’ll get used to it with practice!
I get where you're coming from! Some people definitely vibe more with lower-level languages because you see the details more clearly. High-level languages tend to abstract away a lot of what's happening, which can feel like you're in the dark. I personally prefer working with lower-level stuff and building higher-level solutions for others to use.
Thanks for the reassurance! It helps to know others feel the same way.