search
HomeWeb Front-endFront-end Q&ASummarize 15 JavaScript development skills (organized and shared)

This article will share with you some techniques that are often used in projects. JavaScript has many cool features that most beginners and intermediate developers don’t know. I hope everyone has to help.

Summarize 15 JavaScript development skills (organized and shared)

1. Conditionally add attributes to an object

We can use the expansion operator (. ..) to quickly add properties to JS objects conditionally.

const condition = true;
const person = {
  id: 1,
  name: 'John Doe',
  ...(condition && { age: 16 }),
};

The && operator returns the last evaluated expression if each operand evaluates to true. So an object {age: 16} is returned, which is then expanded to be part of the person object.

If condition is false, JavaScript will do something like this:

const person = {
  id: 1,
  name: '前端小智',
  ...(false), 
};
// 展开 `false` 对对象没有影响
console.log(person); // { id: 1, name: 'John Doe' }

2. Check whether the attribute exists in the object

You can use the in keyword to check whether a certain attribute exists in the JavaScript object.

const person = { name: '前端小智', salary: 1000 };
console.log('salary' in person); // true
console.log('age' in person); // false

3. Dynamic property names in objects

Setting object properties using dynamic keys is simple. Just use ['key name'] to add properties:

const dynamic = 'flavour';
var item = {
  name: '前端小智',
  [dynamic]: '巧克力'
}
console.log(item); // { name: '前端小智', flavour: '巧克力' }

The same trick can be used to reference object properties using dynamic keys:

const keyName = 'name';
console.log(item[keyName]); // returns '前端小智'

4. Use dynamic Object destructuring by key

We know that when destructuring an object, you can use: to rename the destructured attributes. But, did you know that you can also deconstruct the properties of an object when the key name is dynamic?

const person = { id: 1, name: '前端小智' };
const { name: personName } = person;
console.log(personName); // '前端小智'

Now, we use dynamic keys to destructure properties:

const templates = {
  'hello': 'Hello there',
  'bye': 'Good bye'
};
const templateName = 'bye';
const { [templateName]: template } = templates;
console.log(template); // Good bye

5. Null value merging?? Operator

The ?? operator is useful when we want to check whether a variable is null or undefined. When its left operand is null or undefined, it returns its right operand, otherwise it returns its left operand.

const foo = null ?? 'Hello';
console.log(foo); // 'Hello'
const bar = 'Not null' ?? 'Hello';
console.log(bar); // 'Not null'
const baz = 0 ?? 'Hello';
console.log(baz); // 0

In the third example, 0 is returned because even though 0 is considered false in JS, it is not null or undefined. You may think that we can use the || operator, but there is a difference between the two.

You may think that we can use the || operator here, but there is a difference between the two.

const cannotBeZero = 0 || 5;
console.log(cannotBeZero); // 5
const canBeZero = 0 ?? 5;
console.log(canBeZero); // 0

6. Optional chain?.

Do we often encounter such errors: TypeError: Cannot read property 'foo' of null. This is an annoying problem for every developer. Optional chaining was introduced to solve this problem. Let’s take a look:

const book = { id:1, title: 'Title', author: null };
// 通常情况下,你会这样做
console.log(book.author.age) // throws error
console.log(book.author && book.author.age); // null
// 使用可选链
console.log(book.author?.age); // undefined
// 或深度可选链
console.log(book.author?.address?.city); // undefined

You can also use the following function optional chain:

const person = {
  firstName: '前端',
  lastName: '小智',
  printName: function () {
    return `${this.firstName} ${this.lastName}`;
  },
};
console.log(person.printName()); // '前端 小智'
console.log(persone.doesNotExist?.()); // undefined

7. Use the !! operator

!! Operator can be used to quickly convert the result of an expression to a Boolean value (true or false):

const greeting = 'Hello there!';
console.log(!!greeting) // true
const noGreeting = '';
console.log(!!noGreeting); // false

8. String and Integer Conversion

Use operators to quickly convert strings to numbers:

const stringNumer = '123';
console.log(+stringNumer); //123
console.log(typeof +stringNumer); //'number'

To quickly convert numbers to strings, you can also use operators, followed by an empty string:

const myString = 25 + '';
console.log(myString); //'25'
console.log(typeof myString); //'string'

These type conversions are very convenient, but they result in less clarity and code readability. Therefore, actual development requires careful selection and use.

9. Check for false values ​​in the array

Everyone should have used array methods: filter, some, every, these methods can be used together Boolean method to test true and false values.

const myArray = [null, false, 'Hello', undefined, 0];
// 过滤虚值
const filtered = myArray.filter(Boolean);
console.log(filtered); // ['Hello']
// 检查至少一个值是否为真
const anyTruthy = myArray.some(Boolean);
console.log(anyTruthy); // true
// 检查所有的值是否为真
const allTruthy = myArray.every(Boolean);
console.log(allTruthy); // false

Here’s how it works. We know that these array methods accept a callback function, so we pass a Boolean as the callback function. The Boolean function itself accepts a parameter and returns true or false depending on the truth of the parameter. So:

myArray.filter(val => Boolean(val));

is equivalent to:

myArray.filter(Boolean);

10. Flattening arrays

There is a method on the prototype Array flat can make a single array from an array of arrays.

const myArray = [{ id: 1 }, [{ id: 2 }], [{ id: 3 }]];
const flattedArray = myArray.flat(); 
//[ { id: 1 }, { id: 2 }, { id: 3 } ]

You can also define a depth level, specifying how deep a nested array structure should be flattened. For example:

const arr = [0, 1, 2, [[[3, 4]]]];
console.log(arr.flat(2)); // returns [0, 1, 2, [3,4]]

11.Object.entries

Most developers use the Object.keys method to iterate over objects. This method only returns an array of object keys, not values. We can use Object.entries to get keys and values.

const person = {
  name: '前端小智',
  age: 20
};
Object.keys(person); // ['name', 'age']
Object.entries(data); // [['name', '前端小智'], ['age', 20]]

To iterate over an object we can do the following:

Object.keys(person).forEach((key) => {
  console.log(`${key} is ${person[key]}`);
});
// 使用 entries 获取键和值
Object.entries(person).forEach(([key, value]) => {
  console.log(`${key} is ${value}`);
});
// name is 前端小智
// age is 20

Both of the above methods return the same results, but Object.entries is easier to get the key-value pairs.

12.replaceAll method

In JS, to replace all occurrences of a string with another string, we need to use the following Regular expression shown:

const str = 'Red-Green-Blue';
// 只规制第一次出现的
str.replace('-', ' '); // Red Green-Blue
// 使用 RegEx 替换所有匹配项
str.replace(/\-/g, ' '); // Red Green Blue

But in ES12, a new method called replaceAll was added to String.prototype, which replaces all occurrences of a string with another string value.

str.replaceAll('-', ' '); // Red Green Blue

13. Number separator

You can use underscores as number separators, which makes it easy to count the number of 0s in the number.

// 难以阅读
const billion = 1000000000;
// 易于阅读
const readableBillion = 1000_000_000;
console.log(readableBillion) //1000000000

下划线分隔符也可以用于BigInt数字,如下例所示

const trillion = 1000_000_000_000n;
console.log(trillion); // 1000000000000

14.document.designMode

与前端的JavaScript有关,设计模式让你可以编辑页面上的任何内容。只要打开浏览器控制台,输入以下内容即可。

document.designMode = 'on';

15.逻辑赋值运算符

逻辑赋值运算符是由逻辑运算符&&、||、??和赋值运算符=组合而成。

const a = 1;
const b = 2;
a &&= b;
console.log(a); // 2
// 上面等价于
a && (a = b);
// 或者
if (a) {
  a = b
}

检查a的值是否为真,如果为真,那么更新a的值。使用逻辑或 ||操作符也可以做同样的事情。

const a = null;
const b = 3;
a ||= b;
console.log(a); // 3
// 上面等价于
a || (a = b);

使用空值合并操作符 ??:

const a = null;
const b = 3;
a ??= b;
console.log(a); // 3
// 上面等价于
if (a === null || a === undefined) {
  a = b;
}

注意:??操作符只检查 null 或 undefined 的值。

【相关推荐:javascript学习教程

The above is the detailed content of Summarize 15 JavaScript development skills (organized and shared). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金. If there is any infringement, please contact admin@php.cn delete
React: The Foundation for Modern Frontend DevelopmentReact: The Foundation for Modern Frontend DevelopmentApr 19, 2025 am 12:23 AM

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

The Future of React: Trends and Innovations in Web DevelopmentThe Future of React: Trends and Innovations in Web DevelopmentApr 19, 2025 am 12:22 AM

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

React: A Powerful Tool for Building UI ComponentsReact: A Powerful Tool for Building UI ComponentsApr 19, 2025 am 12:22 AM

React is a JavaScript library for building user interfaces. Its core idea is to build UI through componentization. 1. Components are the basic unit of React, encapsulating UI logic and styles. 2. Virtual DOM and state management are the key to component work, and state is updated through setState. 3. The life cycle includes three stages: mount, update and uninstall. The performance can be optimized using reasonably. 4. Use useState and ContextAPI to manage state, improve component reusability and global state management. 5. Common errors include improper status updates and performance issues, which can be debugged through ReactDevTools. 6. Performance optimization suggestions include using memo, avoiding unnecessary re-rendering, and using us

Using React with HTML: Rendering Components and DataUsing React with HTML: Rendering Components and DataApr 19, 2025 am 12:19 AM

Using HTML to render components and data in React can be achieved through the following steps: Using JSX syntax: React uses JSX syntax to embed HTML structures into JavaScript code, and operates the DOM after compilation. Components are combined with HTML: React components pass data through props and dynamically generate HTML content, such as. Data flow management: React's data flow is one-way, passed from the parent component to the child component, ensuring that the data flow is controllable, such as App components passing name to Greeting. Basic usage example: Use map function to render a list, you need to add a key attribute, such as rendering a fruit list. Advanced usage example: Use the useState hook to manage state and implement dynamics

React's Purpose: Building Single-Page Applications (SPAs)React's Purpose: Building Single-Page Applications (SPAs)Apr 19, 2025 am 12:06 AM

React is the preferred tool for building single-page applications (SPAs) because it provides efficient and flexible ways to build user interfaces. 1) Component development: Split complex UI into independent and reusable parts to improve maintainability and reusability. 2) Virtual DOM: Optimize rendering performance by comparing the differences between virtual DOM and actual DOM. 3) State management: manage data flow through state and attributes to ensure data consistency and predictability.

React: The Power of a JavaScript Library for Web DevelopmentReact: The Power of a JavaScript Library for Web DevelopmentApr 18, 2025 am 12:25 AM

React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

React's Ecosystem: Libraries, Tools, and Best PracticesReact's Ecosystem: Libraries, Tools, and Best PracticesApr 18, 2025 am 12:23 AM

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

React and Frontend Development: A Comprehensive OverviewReact and Frontend Development: A Comprehensive OverviewApr 18, 2025 am 12:23 AM

React is a JavaScript library developed by Facebook for building user interfaces. 1. It adopts componentized and virtual DOM technology to improve the efficiency and performance of UI development. 2. The core concepts of React include componentization, state management (such as useState and useEffect) and the working principle of virtual DOM. 3. In practical applications, React supports from basic component rendering to advanced asynchronous data processing. 4. Common errors such as forgetting to add key attributes or incorrect status updates can be debugged through ReactDevTools and logs. 5. Performance optimization and best practices include using React.memo, code segmentation and keeping code readable and maintaining dependability

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment