-3

I am new to JS. I have the following question -

Is it right to say that I can declare variables only in global scope or inside a function/method only in JS and in no other type of Object which is not function/method?

I understand that properties can be defined in any object of Javascript but variables cannot be declared everywhere.


EDIT: I might not have right terminology to explain but in simplest words I need a list of places where i can write var x = .. in JS code. Please,I am not looking for scope of a variable.

16
  • Variables using var have function-scope. Variables using const or let have block-scope. It's recommended to use the most specific scope necessary to accomplish your task to avoid name-clashes and possibility of global overrides. Commented Jan 13, 2020 at 21:00
  • 1
    Yes, by definition, JS variables are function-scoped. Meaning, they have scope within the function in which they are defined. With the introduction of the let and const keywords in ES2015, variables may be scoped within a specific block, but that block will still be inside a function or global scope. Commented Jan 13, 2020 at 21:01
  • @mhodges , So my observation is right ? Commented Jan 13, 2020 at 21:02
  • 1
    @Quentin That's still defining the variable within the global scope. Unless the OP is only asking about where the variable declaration is made? Commented Jan 13, 2020 at 21:06
  • 2
    @SunnyPatel I think the question is more about syntax than scope. Commented Jan 13, 2020 at 21:06

2 Answers 2

-1

you can the variable anywhere you want at the beggining of the program in the middle or if you need one in a function you can do it there too

Sign up to request clarification or add additional context in comments.

Comments

-2

Variables can be declared at top-level, function parameter lists, and statements in function bodies.

Object and array literals can contain nested functions, and you can declare variables inside these functions as well. But you can't declare variables directly in object/array literals; e.g. you can't write:

const foo_array = [
    let a = 1,
    let b = 2
];

4 Comments

Can u pls give an example how to do that in statements in class definitions ?
That was wrong, a statement that looks like a variable assignment in a class definition is actually a property in the class prototype, not really a variable. I've removed it.
I guess we need to use declare rather than define keyword. This was the whole fuss in the comments. stackoverflow.com/a/20822138/2844702
@BreakingBenjamin I've changed to declare, although I think for this question the distinction is not really significant. A definition is just a declaration with an initialization.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.