Variables and data types.(JavaScript)

04/25/2023

Japanese version.

A variable is a name that is used to store a value in a program.

In programming, we work with data that is required for processing. This data can be in the form of numbers, strings, booleans, and so on. Variables allow us to store this data within a program.

Variables can be thought of as "containers" for storing values. Each container is given a name, which is used to refer to the value stored inside. For example, in the following code, we assign the value of 10 to a variable named x:

let x = 10;

By using variables, we can store and reuse values that are needed for complex calculations or processing. The value of a variable can also be changed at any point in the program.

Variable names can be chosen freely by the programmer. However, it is important to choose a name that is easy to understand and distinguish from other parts of the program.

Declaration(Create)

Variable declaration is the process of assigning a name to a value, so that the value can be referred to by using that name.

For example, in the following code, we assign the value of 10 to a variable named x and then use x to output the value:

let x = 10;

console.log(x); // 10

To declare a variable, we use keywords such as var, let, or const. Each keyword has different properties.

var is an old way of declaring variables in JavaScript and can be used in global or local scope.

let is a variable declaration method that can be used in block scope and does not allow re-declaration of variables with the same name. Variables declared with let cannot be used before they are declared.

const is a variable declaration method that can be used in block scope and cannot be reassigned after its initial value is set. However, the properties of objects or elements of arrays can be modified.

var

var is a variable declaration method that is used in older versions of JavaScript and can be used in global or local scope.

To declare a variable using var, we write:

var x = 10;

In this example, we assign the value of 10 to a variable named x using var.

Variables declared with var can be used before they are declared. However, in such cases, the value of the variable is undefined.

console.log(y); // undefined
var y = 20;

Variables declared with var can be re-declared with the same name. However, if the variable is re-declared in the global scope, the value of the existing variable is changed.

var z = 30;
var z = 40; // can be re-declared
console.log(z); // 40

Variables declared with var can be used in global or local scope. However, if the variable is declared in local scope, it can only be used within the function in which it is declared.

var is more flexible than let or const in some ways, but it has the disadvantage of having a slightly more complex syntax. Therefore, it is currently recommended to use let or const instead of var.

Why you should not use var

There are several reasons why you should not use var in modern JavaScript:

For these reasons, it is recommended to use let or const instead of var in modern JavaScript. let and const have block scope and do not allow re-declaration or using variables before they are declared, which can improve code quality and make it easier to understand and maintain.

  1. Scope issues
  2. Re-declaration issues
  3. Issues with using variables before declaration
  4. Lack of block scope
Scope issues

Variables declared with var are either in global scope or function scope, depending on where they are declared. This can lead to scope issues and make it hard to read and understand the code. Variables declared in function scope can also be accessed from outside the function, which can lead to unexpected behavior and variable name conflicts.

Re-declaration issues

Variables declared with var can be re-declared with the same name, which can lead to unintended overwriting of variables. In complex programs, accidentally using the same variable name can cause problems.

Issues with using variables before declaration

Variables declared with var can be used before they are declared, but they will have the value of undefined. This can cause bugs in your code.

Lack of block scope

Variables declared with var do not have block scope, which can cause conflicts when the same variable name is used in multiple blocks. This can lead to unexpected values being assigned to variables.

Situations for using var

let and const are relatively new features and may not be supported in older browsers. In this case, var can be used to declare variables.

There are also cases where JavaScript is used on the tool only in older versions, and in such cases, var is used instead of let and const.

let

let is a variable declaration keyword with block scope. Variables declared with let are only valid within the block in which they are declared. Here's an example of declaring a variable using let:

let x = 10;

In this example, a variable named x is declared using let and is given a value of 10.

Variables declared with let cannot be used before they are declared, as this will result in a reference error:

console.log(y); // Uncaught ReferenceError: y is not defined
let y = 20;

Also, variables declared with let cannot be re-declared with the same name. Attempting to do so will result in a syntax error:

let z = 30;
let z = 40; // Uncaught SyntaxError: Identifier 'z' has already been declared

Compared to var, let is less prone to scope and re-declaration issues, resulting in more readable code. Therefore, it is recommended to use let instead of var.

const

const is a keyword used to declare constants. Variables declared with const cannot be reassigned. Here's an example of declaring a constant using const:

const PI = 3.14159;

In this example, a constant named PI is declared using const and is given a value of 3.14159.

Since constants cannot be reassigned, attempting to do so will result in a syntax error:

const age = 30;
age = 40; // Uncaught TypeError: Assignment to constant variable.

Variables declared with const can also be used with objects and arrays. However, since the variable itself cannot be reassigned, the object or array cannot be completely replaced. Elements within an object or array can still be modified:

const person = {
  name: 'John',
  age: 30
};

person.age = 40; // OK

person = { name: 'Jane', age: 40 }; // Uncaught TypeError: Assignment to constant variable.

const is recommended when declaring values that are not meant to be changed. Constants are used to avoid reassignment issues, and it is important for them to remain immutable.

Scope

The scope of a variable refers to the range of code where that variable can be accessed.

Scopes include global scope and local scope (function scope and block scope), each of which has its own characteristics. A correct understanding of scopes can improve code comprehension and maintainability.

Global Scope

The global scope is a scope in JavaScript where variables and functions can be defined and accessed from anywhere in the code. This means that variables defined in the global scope can be referenced from anywhere in the program. Here's an example of a variable defined in the global scope:

var x = 10;

function foo() {
  console.log(x); // 10
}

foo(); // 10

In this example, a variable named x is defined in the global scope. It can also be accessed from within the foo() function.

There are some issues with using the global scope. For example, if multiple files use the same variable name in the global scope, it can cause unexpected behavior. Additionally, since variables defined in the global scope can be modified from anywhere in the code, it can reduce the maintainability of the program.

Therefore, when defining variables in the global scope, it is recommended to use unique prefixes in variable names to avoid naming conflicts. It is also recommended to declare variables in local scopes as much as possible.

In JavaScript, if global variables are defined in different files, they can affect each other because the code in different files share the same global scope.

For example, if variable x is defined in the global scope in script1.js and the same variable x is defined in the global scope in script2.js, any changes made to the variable in one file will affect the value of the variable in the other file because they share the same global scope.

Therefore, when using global variables in different JavaScript files, it is important to be aware of naming conflicts. One way to avoid naming conflicts is to avoid using the same variable names in different files. Alternatively, in ES6 and later, you can use let or const to limit the scope of the variable and avoid global scope pollution.

Local Scope

Local scope is the scope of a variable that is defined within a block, function, or another block defined inside a function. Variables declared in the local scope are accessible only within the same block or function in which they are declared.

There are several advantages to using local scope. For example, declaring variables in local scope can help avoid naming conflicts. Additionally, variables used within a function are less likely to be accidentally modified or have naming conflicts with other parts of the code, which can improve the maintainability of the code.

When declaring variables in local scope, it is recommended to use let or const. These keywords help avoid unintended redeclaration or reassignment of variables.

Function Scope

Function scope refers to the scope of variables defined inside a function that can only be accessed within that function. Function scope helps to avoid naming conflicts and improve the maintainability of code.

Here's an example of function scope:

function foo() {
  var x = 10;
  console.log(x); // 10
}

foo(); // 10
console.log(x); // Uncaught ReferenceError: x is not defined

In this example, a variable named x is defined inside the foo() function and assigned a value of 10. x can only be accessed within the foo() function, and attempting to access it outside of the function will result in a reference error.

Function scope means that variables declared inside a function can only be used within that function and not outside of it. This avoids naming conflicts with variables used in other functions or in the global scope.

Block Scope

Block scope refers to the scope of variables declared inside a block ({}) that can only be accessed within that block. Block scope helps to avoid naming conflicts and improve the maintainability of code.

Here's an example of block scope:

function foo() {
  if (true) {
    var x = 10;
    let y = 20;
    const z = 30;
  }
  console.log(x); // 10
  console.log(y); // Uncaught ReferenceError: y is not defined
  console.log(z); // Uncaught ReferenceError: z is not defined
}

foo();

In this example, variables x, y, and z are declared using var, let, and const keywords respectively inside an if statement block. However, attempting to access y and z outside of the if block will result in reference errors. On the other hand, x is defined within the function scope and can be accessed outside of the if block.

Block scope is supported by new keywords like let and const introduced in ES6 and later. These keywords help limit the scope of variables to the block in which they are declared, and avoid unintended redeclaration or reassignment of variables.

Using block scope helps limit the scope of variables to the necessary block, which can improve code readability and maintainability.

Naming convention for variables

The following characters are allowed in variable names.

  • Letters (a-z, A-Z)
  • Digits (0-9)
  • Underscore (_)
  • Dollar sign ($)

In JavaScript, variable names cannot start with a number. Here are the rules for naming variables in JavaScript:

  1. Variable names must begin with a letter, $, or _.
  2. Variable names cannot use reserved words such as if, while, for, and so on.
  3. Variable names should be meaningful, especially in reflecting the role or purpose of the variable.
  4. Variable names should be short and concise but also clear and descriptive.

Here are some examples of naming conventions for variables:

// Valid variable names
let firstName = 'John';
let age = 30;
let $currency = 'USD';
let _maxLimit = 100;

// Invalid variable names
let 1stNumber = 10; // Cannot start with a number
let full-name = 'John Doe'; // Cannot use hyphens
let if = true; // Cannot use reserved words as variable names

Initializing variables

Variable initialization refers to assigning an initial value to a variable. In JavaScript, you can set an initial value for a variable when you declare it.

For example, you can declare a variable and set its initial value as follows:

let age = 30;

In this case, the variable age is initialized with the value 30.

You can also assign a value to a variable after declaring it:

let age;
age = 30;

In this case, the variable age is first initialized with undefined, and then assigned the value 30.

If you declare a variable without assigning it an initial value, it will be automatically initialized to undefined.

let age;

console.log(age); // Output: undefined

Data type

A data type is a concept that represents the type of data that a program deals with. Computers have various types of data, such as numbers, strings, and boolean values. In order to process these data in a program, it's necessary to specify their data types.

For example, a program that calculates numbers uses the number data type, a program that displays strings uses the string data type, and a program that determines boolean values uses the boolean data type.

In JavaScript, the data types that can be used are classified as follows:

Primitive types represent a single value and each has its own data type. On the other hand, object types represent a collection of values and do not have their own data type.

In JavaScript, the data type of a variable is not determined at the time of declaration, but is dynamically determined by assigning a value to the variable. In addition, different data types can be assigned to the same variable.

---

Links

JavaScript Articles