On Fri, Jan 7, 2011 at 10:27 PM, Garrett Smith <dhtmlkitc...@gmail.com>wrote:
> On 1/7/11, Dmitry Soshnikov <dmitry.soshni...@gmail.com> wrote: > > On Fri, Jan 7, 2011 at 10:46 AM, Mathias Bynens <math...@qiwi.be> wrote: > > > >> > >> > >> Let’s assume you’re working in the global scope already and you want > >> to create a new global variable. What do you guys recommend? Should > >> the `var` keyword be used (first example) even though it’s not > >> necessary in this case? Are there any other implications I should be > >> aware of? What is considered to be the best practice here? > >> > >> > >> > > While answers above have already clarified the case (yes, a variable in > JS > > is declared with using a `var` keyword), I add some notes below. > > > > First, if to nit-pick to technical part, strictly speaking, a variable is > > defined only with using `var` keyword (there is a special section in my > old > > article: > > > http://dmitrysoshnikov.com/ecmascript/chapter-2-variable-object/#about-variables > > ). > > > > However, if the technical part is not so essential, you may use an > > assignment to an undeclared identifier (your case with foo = 42) for > > creating a property of the global object. The only thing you need in ES3 > for > > that is to watch attentively and manage carefully all your variables (to > > avoid collisions with other variables). > > > No, that is not the only thing. Yep, if to consider a cross-browser scripting, then of course, yes. I talked mostly about semantics of programming languages (for what this signal -- `var`, `local`, `nonlocal`, etc. is needed for the interpreter). In JS as mentioned, the best practice is to use `var`. And especially in cross-browser scripting. > Please see the discussion at the URL > Yep, thanks; there's no need, I'm aware about those cases too. > In strict mode of ES5 though, you won't be able to use `foo = 42` case, > > since such assignments are banned and cause a `ReferenceError`. Info: > > > http://dmitrysoshnikov.com/ecmascript/es5-chapter-2-strict-mode/#assignment-to-an-undeclared-identifier > > > > Not only banned in ES5, but can result in errors in most versions of > IE. Yes of course, but repeat, I was talking mostly about the semantics. > Plus it creates the confusion of "where is this identifier > declared?", as mentioned in earlier referenced thread. > > Also true; btw, from this viewpoint Python's strategy can be considered also as good (assignment either updates a local var or creates a local var and no a special keyword for local vars is needed; and for rare case of non-local vars, already `nonlocal` keyword is the case). Dmitry. -- To view archived discussions from the original JSMentors Mailman list: http://www.mail-archive.com/jsmentors@jsmentors.com/ To search via a non-Google archive, visit here: http://www.mail-archive.com/jsmentors@googlegroups.com/ To unsubscribe from this group, send email to jsmentors+unsubscr...@googlegroups.com