DEV Community

Cover image for JS Variables
Armen Ghazaryan
Armen Ghazaryan

Posted on

JS Variables

JavaScript is mostly used on:

  • Web development.
  • Web applications.
  • Web servers.
  • Mobile applications.
  • Games development.


It's the most used programming language in the world, used as a client-side programming language by 97.0% of all websites.

As in other programing languages, in JavaScript there are different data types:

  • Strings.
  • Arrays.
  • Objects.
  • Functions.

Declaring a variable is a way of storing data. It can be declared by keywords var, let and const. The var keyword is used in all JavaScript code from 1995 to 2015. The let and const keywords were added to JavaScript in 2015. If there is a need of running code in an old browser, variables should be declared with var.
There are some restrictions that we need to follow at a time of getting name to the variable. We cannot use spaces or tabs, and the name cannot start with the number. Names of variables are case sensitive: words with uppercase and lowercase letters are different.

Variables can contain different types of information: Numbers, Strings, Booleans, etc.

String is used with double or single quotes and contains a group of characters.
Boolean data type has two values: true and false.

Here is how variables are declared:

var name = "Armen";
let AUAstudent = true;
const age = 18
Enter fullscreen mode Exit fullscreen mode

When we use the const for declaring variable, then the variable cannot be changed or reassigned.

We can change the value of the variables declared with let or var. For example:
let course = “Introduction to Computer Science”;
for changing the variable course we write:
course = “Linear Algebra”;
In this way we assign a new value to the variable.

We can also do mathematical operations inside the variables, such
let a = 5+6;

The main difference between var and let is the scope. Via scopes we can know where the variable can be used.
There are two type of scopes:

  1. global
  2. local

Global variables can be redeclared outside of a block, and they are accessible from every point of the code. Its var.

Local variables are declared inside of a block. Its let. Let variables need to be declared before use.

Let allows us to declare variables which are limited to a block statement but var lets us redeclare the variables.

var x = 17
Enter fullscreen mode Exit fullscreen mode

x is global variable here.

function() {
let n = 11
Enter fullscreen mode Exit fullscreen mode

n is local variable here.

Top comments (0)