Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's advantage to use var in the variable declaration? [duplicate]

Tags:

javascript

Possible Duplicate:
Difference between using var and not using var in JavaScript

For the code, I found it is no need to declare variable using var. the following are both working

// with var
var object = new Object();

// without var
object = new Object();

what's the difference between those two?

like image 334
Adam Lee Avatar asked Jan 15 '12 10:01

Adam Lee


People also ask

What is the advantage of using VAR in Java?

In Java 10, the var keyword allows local variable type inference, which means the type for the local variable will be inferred by the compiler, so you don't need to declare that.

What is the benefit of using var in C#?

By using “var”, you are giving full control of how a variable will be defined to someone else. You are depending on the C# compiler to determine the datatype of your local variable – not you. You are depending on the code inside the compiler – someone else's code outside of your code to determine your data type.

What is the primary advantage of using the let keyword over using the var keyword in Ecmascript?

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.


1 Answers

the key difference is if you don't use var keyword, your variable will be global, even if you defined it in some nested function.

var defines a scope for that variable. Using a global or not depends if you want to use your object across multiple scopes or not, but globals are strongly discouraged in favour of namespaces that reduce the global scope pollution.

like image 106
Fabrizio Calderan Avatar answered Nov 14 '22 22:11

Fabrizio Calderan