阿里云主机折上折
  • 微信号
Current Site:Index > Variable declaration specification

Variable declaration specification

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

In JavaScript, variable declaration is a fundamental component of code, and the way variables are declared directly impacts code readability, maintainability, and performance. Below are common variable declaration standards and practical details.

Replace var with const and let

ES6 introduced const and let, which address the issues of hoisting and block scope with var. Prefer const for immutable variables and use let only when reassignment is needed.

// Correct example
const PI = 3.1415926;
let counter = 0;

// Incorrect example
var oldVariable = 'deprecated';

Avoid Implicit Global Variables

Assigning values without a declaration keyword creates global variables, which will throw an error in strict mode.

function leakExample() {
  globalVar = 'leaked'; // Pollutes the global scope
}

Variable Naming Conventions

Use camelCase for variable names and UPPER_CASE for constants. Names should be descriptive, avoiding single characters (except for loop variables).

// Good naming
const MAX_RETRIES = 3;
let currentUserRole = 'admin';

// Poor naming
const a = 5; // Meaningless
let xyz = 'temp'; // Ambiguous

Separate Declaration and Initialization

For complex logic, declare variables first and assign values later. Use literals for initializing arrays/objects.

// Separate declaration and initialization
let config;
if (env === 'production') {
  config = { apiUrl: 'https://api.example.com' };
} else {
  config = { apiUrl: 'http://localhost:3000' };
}

// Array/object literals
const emptyArray = [];
const emptyObj = {};

Block Scope Practices

Leverage the block scope features of let and const to avoid variable leakage.

// Block scope example
function calculate(values) {
  if (values.length > 0) {
    const result = process(values);
    console.log(result); // Only available inside the if block
  }
  // console.log(result); // ReferenceError
}

Merging Declarations in the Same Scope

let or const declarations in the same scope can be merged, but var carries the risk of redeclaration.

// Merged declarations
const API_KEY = '123',
      API_SECRET = '456';

// Risk with var
var x = 1;
var x = 2; // No error

Temporal Dead Zone (TDZ) Considerations

let/const have a Temporal Dead Zone (TDZ), and accessing them before declaration will throw an error.

console.log(tmp); // ReferenceError
let tmp = 'value';

Declaration Standards for Destructuring Assignment

Keep destructuring clear. For deeply nested structures, consider step-by-step destructuring.

// Object destructuring
const { id, metadata: { createdAt } } = user;

// Array destructuring
const [first, , third] = items;

// Splitting complex destructuring
const { metadata } = user;
const { createdAt } = metadata;

Special Cases in Function Scope

Function declarations are hoisted, but function expressions are not. Arrow functions are better suited for callbacks.

// Function declaration hoisting
validFunc(); // Executes normally
function validFunc() {}

// Function expression
invalidFunc(); // TypeError
const invalidFunc = function() {};

Guarding Against Dynamic Type Conversion

Explicitly declare types to avoid unexpected behavior from implicit conversions.

// Explicit types
const count = Number(inputValue);
const hasItems = Boolean(items.length);

// Risky example
const total = '100' + 50; // "10050"

Export Standards in Modular Environments

For top-level export in modules, prefer named exports over default exports.

// utils.js
export const formatDate = (date) => { /*...*/ };
export const parseString = (str) => { /*...*/ };

// Importing side
import { formatDate } from './utils';

Variable Declarations in Loops

Loop bodies create new block scopes. Using let avoids closure pitfalls.

// Correct loop declaration
for (let i = 0; i < 10; i++) {
  setTimeout(() => console.log(i), 100); // Outputs 0-9
}

// Issue with var
for (var j = 0; j < 10; j++) {
  setTimeout(() => console.log(j), 100); // Outputs 10 ten times
}

Handling Immutable Data

Use Object.freeze or third-party libraries for deep immutability.

const config = Object.freeze({
  timeout: 30,
  retries: 3
});
// config.timeout = 60; // TypeError (strict mode)

Supplementary Notes on Type Annotations

In TypeScript, add type annotations. For plain JS, supplement with JSDoc.

// TypeScript
const userName: string = 'Alice';

// JSDoc
/**
 * @type {number}
 */
const itemCount = 5;

Managing Variable Declaration Placement

Avoid declaring variables with the same name in nested blocks, as it can cause confusion.

function problematic() {
  let value = 1;
  if (condition) {
    let value = 2; // Shadows the outer variable
    console.log(value); // 2
  }
  console.log(value); // 1
}

Special Handling for Environment Variables

Explicitly declare the source of browser globals and Node.js environment variables.

// Browser environment
const { localStorage } = window;

// Node.js environment
const { env } = process;

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

如果侵犯了你的权益请来信告知我们删除。邮箱: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 ☕.