DEV Community

 Areg2004
Areg2004

Posted on

Javascript. Variables, Scopes

Javascript, often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, and the most used programming language in the world. As of 2022, 98 percent of websites use Javascript. Like many other programming languages, JavaScript has variables. Variables can be thought of as named containers. You can place data into these containers and then refer to the data simply by naming the container.
Before we use a variable in a JavaScript program, we must declare it. There are 3 main ways to declare the variables. The first one is var. For example,
var a = 5
var b = 20
var c = a + b
From these examples we can see that a stores value 5, b stores value 20, and c stores value 25.
The second option to declare variables is let. Let is a keyword that is used to declare a block-scoped variable. Usually, the var keyword is used to declare a variable in Javascript which is treated as a normal variable, but the variables declared using the let keyword are block scoped. Basically, let is block scoped, unlike var which is function scoped. Var also allows to redeclare variables, but let doesn’t. The last one is const. When we use the keyword const to declare variables, they cannot be changed. That name comes from the word Constant. Example,
const number1 = 6
const number2 = 50
let total = number1 + number2
Here number1, number2, and total are variables. Number1 and number2 cannot be changed, but the total can.
As I mentioned in the differences of variables, key role plays a scope. In Javascript, a variable has 2 types of scope, global and local. A variable declared at the top of a program or outside of a function is considered a global scope variable. The value of a global variable can be changed inside a function. A variable can also have a local scope that can only be accessed within a function. In the global scope, we can only access global variables, which are stored in the object. Unlike global variables, local variables are not accessible and are destroyed as soon as their scope ends. The local scope can be divided into two scopes, block scope which I already mentioned, and function scope. If we use blocks anything between {}, such as if, switch, while, can make use of block scope only if you define a variable with let and const. Function scope specifies that the variables defined inside the function are only accessible within the function. They won’t be visible outside of a function.

Top comments (0)