Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
96
rated 0 times [  102] [ 6]  / answers: 1 / hits: 25065  / 14 Years ago, fri, october 8, 2010, 12:00:00

Possible Duplicate:

Javascript: is using 'var' to declare variables optional?






When creating variables in javascript is adding var before the variable name a must?



For example instead of



var message = Hello World!


can I use



message = Hello World!


?



I notice that scripts like Google Adsense don't use var



Example:



google_ad_width = 160;
google_ad_height = 600;
google_color_border = 000000;
google_color_bg = ffffff;

More From » variables

 Answers
301

If you don't declare a variable (explicitly creating it in the current scope) using var, let or const then (in non-strict mode) you create an implicit global.



Globals are a fantastic way to have different functions overwriting each other's variables (i.e. they make code a pain to maintain).



If you use var, the scope of the variable is limited to the current function (and anything inside it — it is possible to nest functions).



(const and let scope constants and variables to the current block instead of the function, this usually makes variables even easier to manage than var does.)



Google Adsense uses globals because it splits scripts into two distinct parts (one local and one remote). A cleaner approach would be to call a function defined in the remote script and pass the parameters as arguments instead of having it pick them up from the global scope.






Modern JS should be written in strict mode which bans implicit globals (preferring to explicitly declare them at the top level instead, thus prevent accidental globals when a variable name is typoed).


[#95379] Wednesday, October 6, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kieraelsies

Total Points: 718
Total Questions: 103
Total Answers: 104

Location: England
Member since Sun, May 21, 2023
1 Year ago
kieraelsies questions
Tue, Aug 3, 21, 00:00, 3 Years ago
Tue, Feb 23, 21, 00:00, 3 Years ago
Thu, Nov 12, 20, 00:00, 4 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Mon, Sep 16, 19, 00:00, 5 Years ago
;