Appearance
Data Types and Variables
Data Types
Computers, as the name suggests, are machines capable of performing mathematical calculations, so computer programs can naturally handle various numerical values. However, computers can process much more than just numbers; they can also handle text, graphics, audio, video, web pages, and various other types of data. Different types of data require different data types to be defined. In JavaScript, the following data types are defined:
Number
JavaScript does not distinguish between integers and floating-point numbers; both are represented as Number. The following are all valid Number types:
javascript
123; // Integer 123
0.456; // Floating-point 0.456
1.2345e3; // Scientific notation for 1.2345x1000, equivalent to 1234.5
-99; // Negative number
NaN; // NaN represents Not a Number, used when a result cannot be computed
Infinity; // Infinity represents an infinite value, shown when a number exceeds the maximum representable value in JavaScript
Since computers use binary, sometimes it is more convenient to represent integers in hexadecimal, which uses the prefix 0x and digits 0-9, a-f, for example: 0xff00, 0xa5b4c3d2, etc., which are equivalent to decimal values.
Number can be used for basic arithmetic, following standard mathematical rules:
javascript
1 + 2; // 3
(1 + 2) * 5 / 2; // 7.5
2 / 0; // Infinity
0 / 0; // NaN
10 % 3; // 1
10.5 % 3; // 1.5
Note that % is the modulus operation.
It is important to note that JavaScript's Number does not distinguish between integers and floating-point numbers; that is, 12.00 === 12
. (In most other languages, integers and floating-point numbers cannot be compared directly.) Furthermore, the maximum range for integers in JavaScript is not ±263, but rather ±253, so integers exceeding 253 may not be represented accurately:
javascript
// Calculating the area of a circle:
var r = 123.456;
var s = 3.14 * r * r;
console.log(s); // 47857.94555904001
// Printing the maximum integer representable by Number:
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
String
A string is any text enclosed in single quotes ' or double quotes ". For example, 'abc', "xyz", etc. Note that '' or "" is merely a representation, not part of the string, so the string 'abc' contains only the characters a, b, and c.
Boolean
Boolean values are represented as true or false, consistent with Boolean algebra. A Boolean value can only be true or false, which can be directly expressed as true or false or derived through Boolean operations:
javascript
true; // This is a true value
false; // This is a false value
2 > 1; // This is a true value
2 >= 3; // This is a false value
The && operation is a logical AND; it results in true only if all operands are true:
javascript
true && true; // This && expression evaluates to true
true && false; // This && expression evaluates to false
false && true && false; // This && expression evaluates to false
The || operation is a logical OR; it results in true if at least one operand is true:
javascript
false || false; // This || expression evaluates to false
true || false; // This || expression evaluates to true
false || true || false; // This || expression evaluates to true
The ! operation is a logical NOT; it flips true to false and vice versa:
javascript
! true; // Results in false
! false; // Results in true
! (2 > 5); // Results in true
Boolean values are often used in conditional statements, for example:
javascript
var age = 15;
if (age >= 18) {
alert('adult');
} else {
alert('teenager');
}
Comparison Operators
When comparing Numbers, Boolean values can be obtained through comparison operators:
javascript
2 > 5; // false
5 >= 2; // true
7 == 7; // true
In fact, JavaScript allows comparisons of any data type:
javascript
false == 0; // true
false === 0; // false
Be particularly cautious with the equality operator ==. JavaScript was designed with two comparison operators:
- The == comparison, which automatically converts data types before comparing, often leading to bizarre results.
- The === comparison, which does not perform automatic type conversion; if types are inconsistent, it returns false. If they match, it compares values.
Due to this design flaw in JavaScript, avoid using == and consistently use === instead.
Another exception is that NaN, a special Number, is not equal to any other value, including itself:
javascript
NaN === NaN; // false
The only way to check for NaN is with the isNaN() function:
javascript
isNaN(NaN); // true
Lastly, be aware of floating-point equality comparisons:
javascript
1 / 3 === (1 - 2 / 3); // false
This is not a design flaw in JavaScript. Floating-point arithmetic can introduce errors because computers cannot precisely represent infinitely repeating decimals. To compare two floating-point numbers for equality, calculate the absolute difference and check if it's less than a certain threshold:
javascript
Math.abs(1 / 3 - (1 - 2 / 3)) < 0.0000001; // true
BigInt
To accurately represent integers larger than 253, you can use the built-in BigInt type, represented by appending an n to the integer, for example, 9223372036854775808n. You can also use BigInt() to convert Numbers and strings into BigInt:
javascript
// Using BigInt:
var bi1 = 9223372036854775807n;
var bi2 = BigInt(12345);
var bi3 = BigInt("0x7fffffffffffffff");
console.log(bi1 === bi2); // false
console.log(bi1 === bi3); // true
console.log(bi1 + bi2);
Using BigInt allows for normal addition, subtraction, multiplication, and division, but you cannot mix BigInt with Number in calculations:
javascript
// Using BigInt:
console.log(1234567n + 3456789n); // OK
console.log(1234567n / 789n); // 1564, division result is still BigInt
console.log(1234567n % 789n); // 571, modulus
console.log(1234567n + 3456789); // Uncaught TypeError: Cannot mix BigInt and other types
null and undefined
null represents a "null" value, which is different from 0 and an empty string ''; 0 is a numerical value, and '' represents a string of length 0, whereas null indicates "empty."
In other languages, similar representations exist; for instance, Java uses null, Swift uses nil, and Python uses None. However, in JavaScript, there is also undefined, which indicates "undefined."
The designers of JavaScript intended null to represent an empty value and undefined to signify an undefined value. This distinction has proven mostly useless; in most cases, null should be used. Undefined is only useful for checking whether function arguments were passed.
Array
An array is a collection of elements arranged in order, where each value is called an element. JavaScript arrays can include any data type. For example:
javascript
[1, 2, 3.14, 'Hello', null, true];
This array contains six elements. Arrays are represented by [], with elements separated by commas.
Another way to create an array is through the Array() function:
javascript
new Array(1, 2, 3); // Creates the array [1, 2, 3]
However, for the sake of code readability, it is strongly recommended to use [] directly.
Elements in an array can be accessed by their index. Note that indexing starts at 0:
javascript
var arr = [1, 2, 3.14, 'Hello', null, true];
arr[0]; // Returns the element at index 0, which is 1
arr[5]; // Returns the element at index 5, which is true
arr[6]; // Index out of range, returns undefined
console.log(arr[0], arr[5], arr[6]);
Object
A JavaScript object is an unordered collection of key-value pairs, for example:
javascript
var person = {
name: 'Bob',
age: 20,
tags: ['js', 'web', 'mobile'],
city: 'Beijing',
hasCar: true,
zipcode: null
};
In JavaScript, keys of objects are always of string type, and values can be any data type. The above person object defines six key-value pairs, where each key is also called a property of the object, for example, the name property of
person is 'Bob', and the zipcode property is null.
To access a property of an object, use the object variable followed by the property name:
javascript
person.name; // 'Bob'
person.zipcode; // null
Variable
The concept of a variable is essentially the same as that of a variable in algebra; in programming, a variable can represent not just numbers but any data type.
In JavaScript, a variable is represented by a variable name, which is a combination of uppercase and lowercase letters, digits, $ and _, and cannot start with a digit. Variable names also cannot be JavaScript keywords like if, while, etc. A variable is declared using the var statement, for example:
javascript
var a; // Declares variable a, its value is now undefined
var $b = 1; // Declares variable $b and assigns it a value of 1
var s_007 = '007'; // s_007 is a string
var Answer = true; // Answer is a Boolean true
var t = null; // t's value is null
Variable names can also be in Chinese, but it's advisable to avoid complicating things.
In JavaScript, the equals sign = is used for variable assignment. Any data type can be assigned to a variable, and the same variable can be reassigned multiple times, potentially with different data types. However, note that a variable can only be declared once with var:
javascript
var a = 123; // a's value is the integer 123
a = 'ABC'; // a becomes a string
Languages where the type of a variable is not fixed are called dynamic languages, in contrast to static languages, which require a variable's type to be specified when defined. If a type mismatch occurs during assignment, an error is thrown. For example, Java is a static language, and its assignment statement looks like this:
java
int a = 123; // a is an integer type variable, declared with int
a = "ABC"; // Error: cannot assign a string to an integer variable
Compared to static languages, dynamic languages are more flexible for this reason.
Do not confuse the assignment operator = in an assignment statement with the equals sign in mathematics. For example, in the following code:
javascript
var x = 10;
x = x + 2;
If understood mathematically, x = x + 2 would not hold. In programming, the assignment statement first evaluates the expression on the right, x + 2, yielding 12, and then assigns that value to variable x. Since x's previous value was 10, after reassignment, x's value becomes 12.
To display a variable's content, you can use console.log(x); opening Chrome's console will show the result.
javascript
// Printing variable x
var x = 100;
console.log(x);
Using console.log() instead of alert() is beneficial as it avoids annoying pop-up dialogs.
Strict Mode
JavaScript was designed with a focus on ease of learning for beginners, thus not mandating the use of var for variable declarations. This design flaw led to serious consequences: if a variable is used without being declared with var, it automatically becomes a global variable:
javascript
i = 10; // i is now a global variable
If different JavaScript files on the same page do not declare variables with var and happen to use the variable i, it can lead to variable i interfering with one another, producing hard-to-debug errors.
Variables declared with var are not global; their scope is limited to the function body where they are declared (the concept of functions will be discussed later), and variables with the same name do not conflict in different function bodies.
To fix this severe design flaw in JavaScript, ECMA introduced strict mode in subsequent specifications. JavaScript code running in strict mode is required to declare variables using var; using a variable without var will cause a runtime error.
To enable strict mode, write the following at the beginning of your JavaScript code:
javascript
'use strict';
This is a string; browsers that do not support strict mode will treat it as a string statement, while those that do will run JavaScript in strict mode.
To test whether your browser supports strict mode:
javascript
function hello() {
'use strict';
// If the browser supports strict mode,
// the following code will throw a ReferenceError:
helloStr = 'hello';
console.log(helloStr);
}
hello();
Run the code; if an error occurs, fix it and run it again. If no error occurs, your browser is too old and needs an upgrade.
Variables not declared with var will be treated as global variables. To avoid this flaw, all JavaScript code should use strict mode. The JavaScript code we write later will all adopt strict mode.
Another way to declare variables is with let, which is also the recommended method in modern JavaScript:
javascript
// Declaring a variable with let:
let s = 'hello';
console.log(s);
We will discuss the differences between var and let in detail later.