Local variables are saved within a function using var for use exclusively within that function's scope, whereas global variables are declared outside of a function for accessible across the programme.
In JavaScript, global variables should be avoided or used sparingly. This is because other scripts can easily overwrite global variables. Global variables aren't necessarily bad or even dangerous, but they shouldn't overwrite the values of other variables.
One advantage is that they are simple to overwrite in various locations because they are widely available. Because global variables are window object properties, they can also overwrite anything in the window object. These are actual challenges that make our code difficult to understand.
var window. iAmGlobal = "some val" ; //Global variable declaration with window.
/In any other part of the code.
doSomething function ()
alert(window. iAmGlobal); /I am also available here!! /OR.
Share a personalized message with your friends.