Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between var keyword and without var [duplicate]

Tags:

javascript

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!

like image 736
Mike Avatar asked Jul 08 '11 00:07

Mike


People also ask

What is difference between declaring a variable with the keyword var and without the keyword var?

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.

What happens if we declare a variable * without * the VAR let keyword?

If you declare a variable, without using "var", the variable always becomes GLOBAL.

What does the VAR keyword do?

var is a keyword, it is used to declare an implicit type variable, that specifies the type of a variable based on initial value.

Why var keyword is not used in JavaScript?

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.


2 Answers

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 .

like image 85
mrk Avatar answered Oct 18 '22 21:10

mrk


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.

like image 43
JAiro Avatar answered Oct 18 '22 21:10

JAiro