Just a basic J.S question

Hi. Thanks for clicking on my post. :slightly_smiling_face:
My question is do you ALWAYS have to declare a variable and then assign a value?
like:
var someRandomName;
someRandomNane = “I hope this is not a silly question.”;

or can you just do this:
someRandomName = “knowledge is power”

1 Like

To declare a value is to create it. This is done with the keyword var (there are other keywords, but don’t worry about that yet). This is done once and only once. Assigning a value to a variable is done with the assignment operator (=). The first time we assign a value to a variable, we call it “initializing” it. This can be done at the same time as declaration or later.

var something;
something = 'Hello Glitches777';
// is functionally identical to
var something = 'Hello Glitches777';
1 Like

Hey, so as far I know if you are in global scope then you don’t need to use var keyword but if you are declaring a variable inside a function then it’ll be important because var keyword enable to create a local variable inside that function, otherwise it’ll be of global scope

1 Like

You may have done this and seen it work, but you should be very aware that (unless you are in strict mode) this will create a global variable. Which is not something you want to have happened unintentionally (sometimes you do need globals).

In the browser:

makeMeGlobal = 'Are you sure?'
window.makeMeGlobal
// Are you sure?
2 Likes

Thank you for your responses. This is actually my second time starting JS. You know, life gets busy and things get put on hold. I totally forgot about the global scope! I think previously I didn’t really understand that part which is probably why my stuff wasn’t working and it just ended in frustration. Again, thanks a bunch! :sunglasses:

You can also write like this
var someRandomName = “knowledge is power” .

so , it means you are declaring a variable and assign a value in that variable using = operator .

But i suggest you to have a look at let and const keyword for variable declaration.

1 Like

Notice that not all codes uses var to declare a variable.

var is used to declare a global variable. let is the same as var but instead of a global variable, it declares a local variable instead. const creates a variable for which it’s value cannot be changed but a new data (such as an array item or an object property) can be added but cannot be changed.

Here’s an example:

var number = 32;
console.log(number); //This outputs 32.

Hope this helps.