Variables and Data Types
Variables
Variables are containers for storing data. In JavaScript, variables are declared using the var
, let
, or const
keywords. var
is the declaration method from ES5 and has variable hoisting issues; let
and const
are block-scoped declaration methods added in ES6.
var name = "Zhang San"; // Function scope
let age = 25; // Block scope
const PI = 3.14; // Block scope, cannot be reassigned
Variable naming rules:
- Must start with a letter, underscore (_), or dollar sign ($)
- Subsequent characters can be letters, numbers, underscores, or dollar signs
- Case-sensitive
- Cannot use reserved words as variable names
Data Types
JavaScript is a weakly typed language. Data types are divided into two main categories: primitive types and object types.
Primitive Types (Basic Types)
- Number Type: Represents integers and floating-point numbers
let integer = 10;
let float = 3.14;
let hex = 0xFF; // Hexadecimal representation of 255
let infinity = Infinity;
let nan = NaN; // Not a Number
- String Type: Represents text data
let str1 = 'Single quotes';
let str2 = "Double quotes";
let str3 = `Template string ${integer}`; // ES6 template string
let str4 = "First line\nSecond line"; // Escape characters
- Boolean Type: Logical values true/false
let isTrue = true;
let isFalse = false;
- Null Type: Represents an empty value
let empty = null;
- Undefined Type: Represents undefined
let notDefined;
console.log(notDefined); // undefined
- Symbol Type (Added in ES6): Represents a unique value
let sym1 = Symbol('key');
let sym2 = Symbol('key');
console.log(sym1 === sym2); // false
- BigInt Type (Added in ES2020): Represents large integers
const bigNum = 9007199254740991n;
Object Types (Reference Types)
- Object Type: Key-value pair collection
let person = {
name: "Li Si",
age: 30,
sayHi: function() {
console.log("Hello!");
}
};
- Array Type: Ordered list
let colors = ["red", "green", "blue"];
let mixed = [1, "text", true, {name: "Wang Wu"}];
- Function Type: Executable code block
function add(a, b) {
return a + b;
}
let multiply = function(x, y) {
return x * y;
};
- Date Type: Date and time
let now = new Date();
let specificDate = new Date(2023, 0, 1); // January 1, 2023
- RegExp Type: Regular expression
let pattern = /javascript/i;
let regexp = new RegExp("javascript", "i");
Type Detection
JavaScript provides multiple methods for detecting data types:
- typeof Operator: Returns a string representation of the data type
typeof 42; // "number"
typeof "text"; // "string"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (historical legacy)
typeof {}; // "object"
typeof []; // "object"
typeof function(){};// "function"
- instanceof Operator: Checks if an object belongs to a specific class
[] instanceof Array; // true
{} instanceof Object; // true
new Date() instanceof Date; // true
- Object.prototype.toString Method: More precise type detection
Object.prototype.toString.call(42); // "[object Number]"
Object.prototype.toString.call("text"); // "[object String]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(undefined);// "[object Undefined]"
Type Conversion
JavaScript performs implicit type conversion automatically, but explicit type conversion is also possible.
Explicit Type Conversion
- Convert to String
String(123); // "123"
(123).toString(); // "123"
- Convert to Number
Number("123"); // 123
parseInt("123px"); // 123
parseFloat("3.14"); // 3.14
- Convert to Boolean
Boolean(1); // true
Boolean(0); // false
Boolean(""); // false
Boolean("text"); // true
Implicit Type Conversion
- String Concatenation
"3" + 4; // "34"
3 + "4"; // "34"
- Mathematical Operations
"5" - 2; // 3
"5" * "2"; // 10
- Logical Operations
if ("text") { // true
console.log("Execute");
}
Variable Scope
JavaScript has three types of scope:
- Global Scope: Variables declared outside functions
var globalVar = "Global variable";
- Function Scope: Variables declared with
var
function test() {
var localVar = "Local variable";
}
- Block Scope: Variables declared with
let
andconst
{
let blockVar = "Block variable";
const BLOCK_CONST = "Block constant";
}
Variable Hoisting
The JavaScript engine hoists variable and function declarations to the top of their scope before executing the code.
console.log(hoistedVar); // undefined
var hoistedVar = "Hoisted variable";
// The actual execution order is equivalent to:
var hoistedVar;
console.log(hoistedVar);
hoistedVar = "Hoisted variable";
let
and const
are also hoisted but not initialized, creating a temporal dead zone.
console.log(hoistedLet); // ReferenceError
let hoistedLet = "Not initialized";
Constants
Variables declared with const
must be initialized and cannot be reassigned.
const MAX_SIZE = 100;
MAX_SIZE = 200; // TypeError: Assignment to constant variable
However, the contents of objects and arrays can be modified:
const person = {name: "Zhao Liu"};
person.name = "Qian Qi"; // Allowed
person = {}; // TypeError
Destructuring Assignment
The destructuring assignment syntax added in ES6 makes it easy to extract values from arrays or objects.
- Array Destructuring
let [a, b, c] = [1, 2, 3];
console.log(a); // 1
- Object Destructuring
let {name, age} = {name: "Sun Ba", age: 40};
console.log(name); // "Sun Ba"
- Default Values
let [x = 1, y = 2] = [10];
console.log(x, y); // 10 2
Template Strings
ES6 template strings provide more powerful string handling capabilities.
let user = "Zhou Jiu";
let greeting = `Hello, ${user}!
Today is ${new Date().toLocaleDateString()}`;
Spread Operator
The spread operator ...
can expand arrays or objects.
let arr1 = [1, 2];
let arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]
let obj1 = {a: 1, b: 2};
let obj2 = {...obj1, c: 3}; // {a: 1, b: 2, c: 3}
Differences Between Primitive and Reference Types
- Different Storage Methods
- Primitive types: Stored in stack memory
- Reference types: Stored in heap memory, with reference addresses stored in the stack
- Different Copy Behaviors
// Primitive type
let num1 = 10;
let num2 = num1; // Value copy
num2 = 20;
console.log(num1); // 10
// Reference type
let obj1 = {value: 10};
let obj2 = obj1; // Reference copy
obj2.value = 20;
console.log(obj1.value); // 20
- Different Comparison Methods
// Primitive type
10 === 10; // true
// Reference type
{} === {}; // false
Deep Copy vs. Shallow Copy
- Shallow Copy: Copies only one level of properties
let original = {a: 1, b: {c: 2}};
let shallowCopy = {...original};
- Deep Copy: Recursively copies all levels
let deepCopy = JSON.parse(JSON.stringify(original));
Dynamic Typing Feature
JavaScript is a dynamically typed language; variable types can change at any time.
let dynamic = "String"; // string
dynamic = 42; // number
dynamic = true; // boolean
Strict Equality vs. Abstract Equality
- Strict Equality (===): No type conversion
1 === 1; // true
1 === "1"; // false
- Abstract Equality (==): Performs type conversion
1 == 1; // true
1 == "1"; // true
Type Conversion Rules
- Convert to Boolean
- Falsy values: false, 0, "", null, undefined, NaN
- All other values convert to true
- Convert to Number
Number(true); // 1
Number(false); // 0
Number(null); // 0
Number(undefined); // NaN
Number("123"); // 123
Number("123abc");// NaN
- Convert to String
String(123); // "123"
String(true); // "true"
String(null); // "null"
String(undefined); // "undefined"
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:作用域样式(@scope)
下一篇:运算符与表达式