Web programming

Understanding Variables in JavaScript

Ngoc Phuong

Ngoc Phuong

24-02-2020 . 41 view

An indispensable part in any programming language is a variable, so what is a variable, how is a variable in JavaScript declared? Let's find out.

I. What is a variable?

A variable is used to store data for a value that could be an object, a number, an array, or a string...

1. Where is the variable stored?

Variables in JavaScript are stored in the browser's memory.

2. Declaring a variable in JavaScript

To declare a variable we use the keywords var, let, const.

  • var: declares a variable that can be accessed within or outside of the function, globally.
  • let: declares a variable that can only be accessed within the block around it, defined by a pair of {}.
  • const: is used to declare a constant, and its value is unchangeable throughout the program.

II. Rules for naming variables

Naming variables in JavaScript must follow some rules:

  • The variable name must be letter, case can be either upper or lower, digits from 0-9, underscore () and dollar sign ($).
  • The variable name starts with a letter or an underscore (), starting with a number is wrong.
  • Cannot use reserved words (such as JavaScript keywords) as a variable name.
  • Variable names are case-sensitive

Here are some examples:

  	// Đúng
  	var x;

  	// Đúng
  	var $x;

  	// Đúng
  	var _x;

  	// Đúng
  	var x111;

  	// Sai
  	var 1111x;

III. Variable data type

Unlike some languages when declaring a variable in JavaScript, we do not need to declare a data type for the variable, when executing, the data type is automatically determined. That also means a variable can store values of different data types.

The ECMAScript standard defines seven data types as follows:

  • Boolean type
  • Null type
  • Undefined type
  • Number type
  • String type
  • Symbol Type (new in ECMAScript 6)
  • Object type

IV. The Scope of Variables in JavaScript

1. Global variable (global scope)

A global variable is declared outside a function.

A global variable can be accessed both from outside and inside a function.

2. Local variable (local scope)

A local variable is declared within a function.

A local variable cannot be accessed outside of a function.

3. Example

Example of the scope of a variable in JavaScript

var x = 5;  // biến toàn cục 

function test() {
        let y = 10; // biến cục bộ 
}
console.log("Gọi biến toàn cục: ",x); // Chạy bình thường
console.log("Gọi biến cục bộ: ",y); // Xuất hiện lỗi undefined variable do biến y chỉ được gọi trong hàm.

 

Ngoc Phuong
Ngoc Phuong

Web Developer

Thank you for visiting my website. My name is Ngoc Phuong, and I have over 10 years of experience in website development. I am confident in stating that I am an expert in creating impressive and effective websites. If you need a website designed, please feel free to contact me via email at [email protected].

0 feedback