阿里云主机折上折
  • 微信号
Current Site:Index > Variables and Data Types

Variables and Data Types

Author:Chuan Chen 阅读数:56620人阅读 分类: JavaScript

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)

  1. 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
  1. 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
  1. Boolean Type: Logical values true/false
let isTrue = true;
let isFalse = false;
  1. Null Type: Represents an empty value
let empty = null;
  1. Undefined Type: Represents undefined
let notDefined;
console.log(notDefined); // undefined
  1. Symbol Type (Added in ES6): Represents a unique value
let sym1 = Symbol('key');
let sym2 = Symbol('key');
console.log(sym1 === sym2); // false
  1. BigInt Type (Added in ES2020): Represents large integers
const bigNum = 9007199254740991n;

Object Types (Reference Types)

  1. Object Type: Key-value pair collection
let person = {
  name: "Li Si",
  age: 30,
  sayHi: function() {
    console.log("Hello!");
  }
};
  1. Array Type: Ordered list
let colors = ["red", "green", "blue"];
let mixed = [1, "text", true, {name: "Wang Wu"}];
  1. Function Type: Executable code block
function add(a, b) {
  return a + b;
}

let multiply = function(x, y) {
  return x * y;
};
  1. Date Type: Date and time
let now = new Date();
let specificDate = new Date(2023, 0, 1); // January 1, 2023
  1. RegExp Type: Regular expression
let pattern = /javascript/i;
let regexp = new RegExp("javascript", "i");

Type Detection

JavaScript provides multiple methods for detecting data types:

  1. 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"
  1. instanceof Operator: Checks if an object belongs to a specific class
[] instanceof Array;    // true
{} instanceof Object;   // true
new Date() instanceof Date; // true
  1. 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

  1. Convert to String
String(123);        // "123"
(123).toString();   // "123"
  1. Convert to Number
Number("123");      // 123
parseInt("123px");  // 123
parseFloat("3.14"); // 3.14
  1. Convert to Boolean
Boolean(1);         // true
Boolean(0);         // false
Boolean("");        // false
Boolean("text");    // true

Implicit Type Conversion

  1. String Concatenation
"3" + 4;            // "34"
3 + "4";            // "34"
  1. Mathematical Operations
"5" - 2;            // 3
"5" * "2";          // 10
  1. Logical Operations
if ("text") {       // true
  console.log("Execute");
}

Variable Scope

JavaScript has three types of scope:

  1. Global Scope: Variables declared outside functions
var globalVar = "Global variable";
  1. Function Scope: Variables declared with var
function test() {
  var localVar = "Local variable";
}
  1. Block Scope: Variables declared with let and const
{
  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.

  1. Array Destructuring
let [a, b, c] = [1, 2, 3];
console.log(a); // 1
  1. Object Destructuring
let {name, age} = {name: "Sun Ba", age: 40};
console.log(name); // "Sun Ba"
  1. 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

  1. Different Storage Methods
  • Primitive types: Stored in stack memory
  • Reference types: Stored in heap memory, with reference addresses stored in the stack
  1. 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
  1. Different Comparison Methods
// Primitive type
10 === 10; // true

// Reference type
{} === {}; // false

Deep Copy vs. Shallow Copy

  1. Shallow Copy: Copies only one level of properties
let original = {a: 1, b: {c: 2}};
let shallowCopy = {...original};
  1. 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

  1. Strict Equality (===): No type conversion
1 === 1;    // true
1 === "1";  // false
  1. Abstract Equality (==): Performs type conversion
1 == 1;     // true
1 == "1";   // true

Type Conversion Rules

  1. Convert to Boolean
  • Falsy values: false, 0, "", null, undefined, NaN
  • All other values convert to true
  1. Convert to Number
Number(true);    // 1
Number(false);   // 0
Number(null);    // 0
Number(undefined); // NaN
Number("123");   // 123
Number("123abc");// NaN
  1. Convert to String
String(123);    // "123"
String(true);   // "true"
String(null);   // "null"
String(undefined); // "undefined"

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.