DEV Community

vrezhhakobyan
vrezhhakobyan

Posted on

JavaScript variables

In general, variables play an essential role in programming and solve many questions. As every programming language, JavaScript or JS contains variables. It means that we can create them and give them some value. The values can be different such as numbers, strings, or boolean. But before giving value, we must make the variable. To do that, first, we write the type of variable(var, let, const), which I will explore later. So, for example, we first write:

var

Then we have to create a name for that variable. It can be anything but let's call it n. So we have the variable n or:

var n

Now we can give some value to our variable. To do that, we put = and then put the value. Let's assume that the value is 5. So we have

var n = 5

If we want to give a string value, we must use "" or we will get an error. Additionally, if we write numbers in "", it will no longer be a number. For example:

var m = "Hello"

In the same way we can give boolean values:

var x = true
var y = false

Now let's talk about the difference between var let and const.
The var and let are approximately the same, and we can change their values during the process. But we can't change the value of const.

What about scopes.
In JavaScript, scopes are the areas where the variable is visible. In JavaScript, there are 3 types of scopes.

Block scope
Function scope
Global scope

Variables in the Block Scopes {} and are accessible only inside that block. For example

{
let x = "Hello"
}

If there is a function scope, the situation is the same, we can access to variable only in function. For example:

function(){

const n = 10

}

Variables in the global scope are visible in everywhere.It means that we can put the variable everywhere and it will work without errors
For example:

let a = true
function SayHello()
{
if(a==true){

   console.log("Hello")

 }
Enter fullscreen mode Exit fullscreen mode

}

Top comments (0)