JS Drip#63 Safely Referencing Undeclared Global Variables

12 views
Skip to first unread message

Ahmad El-Alfy

unread,
Jun 11, 2014, 8:18:05 AM6/11/14
to js-drip-d...@googlegroups.com
I never looked as global variables as properties of the window object.

Also understanding how the engine work and deal with undefined variables vs undefined properties totally blown my mind!

At the beginning I thought maybe it is a scope thing but then I realized, it if wasn't in the function's scope it will move to the higher scope. I felt so dumb. It''s how the engine treat things differently. I think getting more into details like these makes the one a better developer.

Thanks a lot Josh

Ahmad El-Alfy

unread,
Jun 11, 2014, 8:18:40 AM6/11/14
to js-drip-d...@googlegroups.com
*at

damnit

Franklin Javier

unread,
Jun 11, 2014, 10:13:27 AM6/11/14
to js-drip-d...@googlegroups.com
You can also use typeof, for this purpose

if ( typeof wishList !== 'undefined' ) { }

Joe Grossberg

unread,
Jun 11, 2014, 4:23:54 PM6/11/14
to js-drip-d...@googlegroups.com
Yeah, that's the convention I'm used to.

And with JS now widely used outside the browser, it seems like a legacy quirk that we can use an object named "window".

Franklin Javier

unread,
Jun 11, 2014, 4:39:02 PM6/11/14
to Joe Grossberg, js-drip-d...@googlegroups.com
Exactly Joe \o
--
--
Franklin Javier

Joshua Clanton

unread,
Jun 12, 2014, 10:46:54 AM6/12/14
to js-drip-d...@googlegroups.com
In the case that you are using Node, the global object is named (more appropriately!) `global`, so the pattern would become...

if (global.varname) {}

Thanks!

Josh Clanton
Reply all
Reply to author
Forward
0 new messages