nopr
nopr

Reputation: 88

Implications of private variables from function arguments?

I'm not entirely certain that I'm asking this correctly because my technical understanding of advanced Javascript is lacking a little. But let's say I have a function. Inside this function (foo), an argument is passed (bar), which is created as a private variable.

function foo(bar){
    console.log(bar);
}
foo("wassup");

Am I correct in thinking that even if unassigned, bar retains private scope without being declared? It also remains an object? So instead of doing this:

function foo(){
    var bar = {
        message: "wassup"
    };
    console.log(bar.message);
}
foo();

I could do this:

function foo(bar){
    bar = {
        message: "wassup"
    };
    console.log(bar.message);
}
foo();

What are the implications of using an argument as an object in this way? Everything seems to check out and the code works just fine, but I was wondering if there are consequences I'm not aware of.

Thanks

Upvotes: 0

Views: 39

Answers (1)

ilan berci
ilan berci

Reputation: 3881

This is an example of a closure, your second function foo is forming a closure over bar. There are consequences to coding with closures but thankfully, they are mainly addressed by the engine and they are not usually a concern of the coder. Actually, forming closures is considered a good form of data encapsulation and many patterns rely heavily on this technique.

in your last foo decleration, you are 'masking' the passed in argument. (assuming you put var in front of it as you should) please note that since you didn't put a 'var' in front of bar, your second decleration of foo is assigning the variable bar to the global namespace which is something your probably didn't intend..

Upvotes: 1

Related Questions