Possible Duplicate:
Difference between using var and not using var in JavaScript
What is the difference between using var keyword in java script & without using it for a variable?
For example:
var x = 14;
And x = 14;
Are these same or when we declare var x, its a local variable & when it doesn't have var keyword, then its global?
Thanks!
var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped. Variable declared by let cannot be redeclared and must be declared before use whereas variables declared with var keyword are hoisted.
If you declare a variable, without using "var", the variable always becomes GLOBAL.
var is a keyword, it is used to declare an implicit type variable, that specifies the type of a variable based on initial value.
This means that if a variable is defined in a loop or in an if statement it can be accessed outside the block and accidentally redefined leading to a buggy program. As a general rule, you should avoid using the var keyword.
If var
keyword is used within a function or other non-global scope then that variable's scope is not global .
If var
keyword is not used before a variable name, then that variable's scope is global .
Variables declared outside a function become GLOBAL, and all scripts and functions on the web page can access it.
Global variables are destroyed when you close the page.
If you declare a variable, without using "var", the variable always becomes GLOBAL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With