Nikhil Pai
Nikhil Pai

Reputation: 125

Is this a global variable?

Are the below variables global variables?

var a = 10, b = 20;
c = 30;

Any variable without "var" is global. so is variable "b" also a global variable?

Upvotes: 0

Views: 89

Answers (6)

manjum2050
manjum2050

Reputation: 43

var a = 10, b = 20; c = 30;

Yes off course variable c is global here. If you define a variable without "var " keyword in any scope, the variable is treated as global as it becomes part of global scope.

for var a and b:

if its declared inside a function, they are treated as local variables(as they will be part of local scope/function scope). if they are declared and not part of any functions, then they are treated as global variables(as they are added into global scope).

Upvotes: 0

SLaks
SLaks

Reputation: 887405

No; the var statement can declare multiple variables in a comma-separated list.

Note that the statement

var a = 1, b = c = 3;

will create c as a global variable (since it isn't being declared).

Upvotes: 4

user4282669
user4282669

Reputation:

"b" is not considered a global variable, you can declare more than one variable, as long as the are divided by commas. "c" is the only global variable in that statement. You cannot declare both a global and local variable in the same line separated by commas.

a = 10, b = 5;  

global declaration

var a = 10, b = 5;

local declaration

Additionally, you can declare them like this:

var a = 10, b = 5;

Outside all other functions, and it will be global.

Upvotes: 0

David Hughes
David Hughes

Reputation: 378

"Any variable without 'var' is global" is not necessarily true. var simply declares a variable in the current scope. The default scope (assuming you are running this JS in a browser and not something like node.js) is the window object.

Essentially, yes, all three of those variables are global.

Further reading on what I'm referring to regarding scope and the varkeyword: You Don't Know JS.

The above is all assuming you are not running in strict mode/"use strict"; - if you are in strict mode, c will throw a ReferenceError as you have not declared it as a variable.

Upvotes: 0

joelmdev
joelmdev

Reputation: 11773

Assuming the first statement isn't in global scope, then no- neither a nor b are global variables because you're defining a list of vars in the first statement. However, if you did the following:

c = 30, d = 90;

you would have defined both c and d as global variables, regardless of the scope in which you defined them.

Upvotes: 0

six fingered man
six fingered man

Reputation: 2500

The c is definitely global; you can test it with console.log(window.c === 30)

The other two are only global if the var declaration is not inside a function.

Keep in mind that in strict mode, the assignment to a variable that was not declared will result in a ReferenceError.

Upvotes: 1

Related Questions