Understanding Variable Declaration in JavaScript

0
10
Asked By CuriousCoder92 On

I'm having trouble grasping how variable declarations work in JavaScript, particularly when two variables share the same name. Here's a snippet of my code:

```javascript
const booking = [];

const createBooking = function(flightNum, numPassengers, price) {
const booking = {
flightNum,
numPassengers,
price
}
console.log(booking);
booking.push(booking);
}
```

In this code, I declare `booking` as both an array and an object. My confusion lies in how these two variables coexist without any conflicts. Can someone explain how this is possible?

5 Answers

Answered By TechWhiz19 On

A quick note on scope: If you use `var`, it behaves differently by being function-scoped, which can lead to unexpected behaviors when not using block scope like `let` or `const`. So keep an eye out for that!

Answered By DevGuru88 On

You've stumbled upon variable shadowing! The local `booking` inside `createBooking` overshadows the global one, meaning any reference to `booking` in that function will point to the local variable. It's important to note, though, that since you're trying to use `push` on what is an object, it won't work because objects don't have that method. That's likely why your code fails when it hits that line!

Answered By JSExpert06 On

Essentially, when you have two variables named `booking`, JavaScript resolves the reference based on scoping rules. The local variable inside the function takes precedence as long as it's defined in that context. And remember, since `booking` refers to an object in this case, the `push` method won’t work because it’s meant for arrays!

Answered By CodeNinja77 On

The reason you don't run into conflicts here is due to variable scope. The `booking` array is declared globally, while the `booking` object inside your `createBooking` function is locally scoped to that function. Essentially, they're different variables in different scopes! You can learn more about this concept of scope in JavaScript. Here's a handy link for you: [Scope in JavaScript](https://www.w3schools.com/js/js_scope.asp)

CuriousCoder92 -

Thanks for clarifying that! So, it's like the function has its own private `booking` that doesn't mess with the global one.

Answered By CodeWizard11 On

In summary, local and global variables can have the same name, but the local one is what you interact with inside its function. Just a heads up, `booking.push(booking)` will throw an error here since you're trying to push an object into an array, which doesn't work. Keep practicing these concepts, and it'll get clearer!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.