Why Can I Use the Same Variable Name in a Function Without Conflicts?

0
5
Asked By CodeJuggler22 On

I'm confused about a piece of JavaScript code I've been working on. Here's what I have:

```javascript
const booking = [];

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

My main question is how can I have two variables called 'booking' without causing any conflict? What's going on with the scopes here? Any insights would be appreciated!

4 Answers

Answered By ScriptNinja88 On

Since both variables are named `booking`, the one inside the function takes precedence when you're inside that function. This is known as variable shadowing. Check out this [Wikipedia article](https://en.wikipedia.org/wiki/Variable_shadowing) for more info. Just be aware that `booking.push(booking)` won't work, because `booking` in that context refers to the object, not the array you declared globally, and objects don't have a `push` method!

Answered By TechyMickey On

You’re on the right track! Scope dictates what's visible where in your code. In your case, the `booking` inside the function is a separate variable that only exists in that function's context. Just remember, using the same name outside and inside can sometimes cause confusion! Just be cautious with it—especially if you omit `const` or `let` in variable declarations, where it might refer back to the global one inadvertently. Also, your current code will error out because you're trying to use `push()` on an object, which doesn’t have that method.

Answered By JS_CodingWhiz On

It's cool to have a local variable named the same as a global variable—just remember that the local one is what gets used inside the function. If you call `booking.push(booking)`, you're trying to push an object into an array, but that won't work since objects don’t have a `push()` method. If you want to access the global `booking` array, you can rename the local one or directly refer to the global variable.

Answered By DevGuru99 On

The reason you can use the same variable name is that you have a global variable called `booking` and a local one inside the `createBooking` function. They exist in different scopes, so they don't interfere with each other. You can learn more about this concept by checking out scope definitions, like in this article: [w3schools on scope](https://www.w3schools.com/js/js_scope.asp).

JavaWhiz77 -

Thanks for the clarification!

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.