Table of Contents
Ternary operator
Short-circuit Evaluation
Declaring variables
If present
JavaScript for loop
Decimal exponent
Object properties
Arrow Function
Implicit return
Default parameter value
Template Literals
Destructuring Assignment
Multi-line string
Spread Operator
强制参数
Array.find
Object[key]
Double Bitwise NOT
Home Web Front-end JS Tutorial 19 Tips for JavaScript Coding

19 Tips for JavaScript Coding

Aug 08, 2017 pm 01:43 PM
javascript js coding

This article is suitable for any developer based on JavaScript. I wrote this article mainly about some abbreviated codes in JavaScript to help everyone better understand some of the basics of JavaScript. I hope these codes can help you better understand JavaScript from different perspectives.

Ternary operator

If you use the if...else statement, then this is a good way to save code.

Longhand:

const x = 20;
let answer;
if (x > 10) {
    answer = 'is greater';
} else {
    answer = 'is lesser';
}
Copy after login

Shorthand:

const answer = x > 10 ? 'is greater' : 'is lesser';
Copy after login

You can also nest like belowifStatement:

const big = x > 10 ? " greater 10" : x
Copy after login

Short-circuit Evaluation

When assigning the value of one variable to another variable, you may want to ensure that the variable is not null, undefined or empty. You can write a conditional statement or Short-circuit Evaluation with multiple if.

Longhand:

if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
     let variable2 = variable1;
}
Copy after login

Shorthand:

const variable2 = variable1  || 'new';
Copy after login

Don’t believe me, please believe in your own test first (you can put the following The code is pasted in es6console)

let variable1;
let variable2 = variable1  || '';
console.log(variable2 === ''); // prints true

variable1 = 'foo';
variable2 = variable1  || '';
console.log(variable2); // prints foo
Copy after login

Declaring variables

When declaring variables in a function, declaring multiple variables at the same time like the following can save you a lot of time and space:

Longhand:

let x;
let y;
let x = 3;
Copy after login

Shorthand:

let x, y, z=3;
Copy after login

If present

This is probably trivial, but worth mentioning. When doing "if checks", the assignment operator can sometimes be omitted.

Longhand:

if (likeJavaScript === true)
Copy after login

Shorthand:

if (likeJavaScript)
Copy after login

Note: These two methods are not the same Exactly the same, the abbreviation check will pass as long as likeJavaScript is true.

Here's another example. If a is not true, then what to do.

Longhand:

let a;
if ( a !== true ) {
// do something...
}
Copy after login

Shorthand:

let a;
if ( !a ) {
// do something...
}
Copy after login

JavaScript for loop

If you just want This little trick is very useful if you want native JavaScript without relying on external libraries like jQuery or Lodash.

Longhand:

for (let i = 0; i < allImgs.length; i++)
Copy after login

Shorthand:

for (let index in allImgs)
Copy after login

Array.forEachAbbreviation:

function logArrayElements(element, index, array) {
  console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// logs:
// a[0] = 2
// a[1] = 5
// a[2] = 9
Copy after login

Short-circuit Evaluation

If the parameter is null or undefined, we can simply use a Short-circuit logical operation to achieve one line of code replacement How to write six lines of code.

Longhand:

let dbHost;
if (process.env.DB_HOST) {
  dbHost = process.env.DB_HOST;
} else {
  dbHost = &#39;localhost&#39;;
}
Copy after login

Shorthand:

const dbHost = process.env.DB_HOST || &#39;localhost&#39;;
Copy after login

Decimal exponent

You may have seen this. It is essentially a strange way of writing numbers, that is, there are many 0 after a number. For example, 1e7 is essentially equivalent to 10000000 (1 is followed by 7 0). It represents the decimal notation equal to 10000000.

Longhand:

for (let i = 0; i < 10000; i++) {}
Copy after login

Shorthand:

for (let i = 0; i < 1e7; i++) {}
// All the below will evaluate to true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;
Copy after login

Object properties

Definition of object literals ) makes JavaScript more interesting. ES6 provides a simpler way to assign object properties. If the property name and value are the same, you can use the following abbreviation.

Longhand:

const obj = { x:x, y:y };
Copy after login

Shorthand:

const obj = { x, y };
Copy after login

Arrow Function

Classic functions are easy to read and can be written, but they do get a bit verbose and can confuse you especially when nested functions call other functions.

Longhand:

function sayHello(name) {
  console.log(&#39;Hello&#39;, name);
}

setTimeout(function() {
  console.log(&#39;Loaded&#39;)
}, 2000);

list.forEach(function(item) {
  console.log(item);
});
Copy after login

Shorthand:

sayHello = name => console.log(&#39;Hello&#39;, name);

setTimeout(() => console.log(&#39;Loaded&#39;), 2000);

list.forEach(item => console.log(item));
Copy after login

Implicit return

returnA keyword often used in functions will return the final result of the function. Arrow functions use a statement to implicitly return the result (the function must omit the {}, in order to omit the return keyword).

If a multi-line statement (such as an object) is returned, it is necessary to use () instead of {} in the function body. This ensures that the code is returned as a separate statement.

Longhand:

function calcCircumference(diameter) {
  return Math.PI * diameter
}
Copy after login

Shorthand:

calcCircumference = diameter => (
  Math.PI * diameter;
)
Copy after login

Default parameter value

You can useif statement to define the default values ​​of function parameters. In ES6, default values ​​can be defined in function declarations.

Longhand:

function volume(l, w, h) {
  if (w === undefined)
    w = 3;
  if (h === undefined)
    h = 4;
  return l * w * h;
}
Copy after login

Shorthand:

volume = (l, w = 3, h = 4 ) => (l * w * h);
volume(2) //output: 24
Copy after login

Template Literals

Are you tired of using it+To concatenate multiple variables into a string? Isn't there an easier way? If you can use ES6, you're lucky. In ES6, what you have to do is use apostrophes and ${}, and put your variables inside curly braces.

Longhand:

const welcome = &#39;You have logged in as &#39; + first + &#39; &#39; + last + &#39;.&#39;

const db = &#39;http://&#39; + host + &#39;:&#39; + port + &#39;/&#39; + database;
Copy after login

Shorthand:

const welcome = `You have logged in as ${first} ${last}`;

const db = `http://${host}:${port}/${database}`;
Copy after login

Destructuring Assignment

If you are using either With popular web frameworks, there are many opportunities to use arrays or data objects to pass information between APIs. Once the data object reaches a component, you need to expand it.

Longhand:

const observable = require(&#39;mobx/observable&#39;);
const action = require(&#39;mobx/action&#39;);
const runInAction = require(&#39;mobx/runInAction&#39;);

const store = this.props.store;
const form = this.props.form;
const loading = this.props.loading;
const errors = this.props.errors;
const entity = this.props.entity;
Copy after login

Shorthand:

import { observable, action, runInAction } from &#39;mobx&#39;;

const { store, form, loading, errors, entity } = this.props;
Copy after login

You can even specify the variable name yourself:

const { store, form, loading, errors, entity:contact } = this.props;
Copy after login

Multi-line string

You will find that the code you used to write multi-line strings will look like the following:

Longhand:

const lorem = &#39;Lorem ipsum dolor sit amet, consectetur\n\t&#39;
    + &#39;adipisicing elit, sed do eiusmod tempor incididunt\n\t&#39;
    + &#39;ut labore et dolore magna aliqua. Ut enim ad minim\n\t&#39;
    + &#39;veniam, quis nostrud exercitation ullamco laboris\n\t&#39;
    + &#39;nisi ut aliquip ex ea commodo consequat. Duis aute\n\t&#39;
    + &#39;irure dolor in reprehenderit in voluptate velit esse.\n\t&#39;
Copy after login

但还有一个更简单的方法。使用撇号。

Shorthand:

const lorem = `Lorem ipsum dolor sit amet, consectetur
    adipisicing elit, sed do eiusmod tempor incididunt
    ut labore et dolore magna aliqua. Ut enim ad minim
    veniam, quis nostrud exercitation ullamco laboris
    nisi ut aliquip ex ea commodo consequat. Duis aute
    irure dolor in reprehenderit in voluptate velit esse.`
Copy after login

Spread Operator

Spread Operator是ES6中引入的,使JavaScript代码更高效和有趣。它可以用来代替某些数组的功能。Spread Operator只是一个系列的三个点(...)。

Longhand:

// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()
Copy after login

Shorthand:

// joining arrays
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];
Copy after login

不像concat()函数,使用Spread Operator你可以将一个数组插入到另一个数组的任何地方。

const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4 , 6];
Copy after login

另外还可以当作解构符:

const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a) // 1
console.log(b) // 2
console.log(z) // { c: 3, d: 4 }
Copy after login

强制参数

默认情况下,JavaScript如果不给函数参数传一个值的话,将会是一个undefined。有些语言也将抛出一个警告或错误。在执行参数赋值时,你可以使用if语句,如果未定义将会抛出一个错误,或者你可以使用强制参数(Mandatory parameter)。

Longhand:

function foo(bar) {
  if(bar === undefined) {
    throw new Error(&#39;Missing parameter!&#39;);
  }
  return bar;
}
Copy after login

Shorthand:

mandatory = () => {
  throw new Error(&#39;Missing parameter!&#39;);
}

foo = (bar = mandatory()) => {
  return bar;
}
Copy after login

Array.find

如果你以前写过一个查找函数,你可能会使用一个for循环。在ES6中,你可以使用数组的一个新功能find()

Longhand:

const pets = [
  { type: &#39;Dog&#39;, name: &#39;Max&#39;},
  { type: &#39;Cat&#39;, name: &#39;Karl&#39;},
  { type: &#39;Dog&#39;, name: &#39;Tommy&#39;},
]

function findDog(name) {
  for(let i = 0; i<pets.length; ++i) {
    if(pets[i].type === &#39;Dog&#39; && pets[i].name === name) {
      return pets[i];
    }
  }
}
Copy after login

Shorthand:

pet = pets.find(pet => pet.type ===&#39;Dog&#39; && pet.name === &#39;Tommy&#39;);
console.log(pet); // { type: &#39;Dog&#39;, name: &#39;Tommy&#39; }
Copy after login

Object[key]

你知道Foo.bar也可以写成Foo[bar]吧。起初,似乎没有理由应该这样写。然而,这个符号可以让你编写可重用代码块。

下面是一段简化后的函数的例子:

function validate(values) {
  if(!values.first)
    return false;
  if(!values.last)
    return false;
  return true;
}

console.log(validate({first:&#39;Bruce&#39;,last:&#39;Wayne&#39;})); // true
Copy after login

这个函数可以正常工作。然而,需要考虑一个这样的场景:有很多种形式需要应用验证,而且不同领域有不同规则。在运行时很难创建一个通用的验证功能。

Shorthand:

// object validation rules
const schema = {
  first: {
    required:true
  },
  last: {
    required:true
  }
}

// universal validation function
const validate = (schema, values) => {
  for(field in schema) {
    if(schema[field].required) {
      if(!values[field]) {
        return false;
      }
    }
  }
  return true;
}

console.log(validate(schema, {first:&#39;Bruce&#39;})); // false
console.log(validate(schema, {first:&#39;Bruce&#39;,last:&#39;Wayne&#39;})); // true
Copy after login

现在我们有一个验证函数,可以各种形式的重用,而不需要为每个不同的功能定制一个验证函数。

Double Bitwise NOT

如果你是一位JavaScript新手的话,对于逐位运算符(Bitwise Operator)你应该永远不会在任何地方使用。此外,如果你不处理二进制01,那就更不会想使用。

然而,一个非常实用的用例,那就是双位操作符。你可以用它替代Math.floor()。Double Bitwise NOT运算符有很大的优势,它执行相同的操作要快得多。你可以在这里阅读更多关于位运算符相关的知识。

Longhand:

Math.floor(4.9) === 4  //true
Copy after login

Shorthand:

~~4.9 === 4  //true
Copy after login

The above is the detailed content of 19 Tips for JavaScript Coding. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Knowledge graph: the ideal partner for large models Knowledge graph: the ideal partner for large models Jan 29, 2024 am 09:21 AM

Large language models (LLMs) have the ability to generate smooth and coherent text, bringing new prospects to areas such as artificial intelligence conversation and creative writing. However, LLM also has some key limitations. First, their knowledge is limited to patterns recognized from training data, lacking a true understanding of the world. Second, reasoning skills are limited and cannot make logical inferences or fuse facts from multiple data sources. When faced with more complex and open-ended questions, LLM's answers may become absurd or contradictory, known as "illusions." Therefore, although LLM is very useful in some aspects, it still has certain limitations when dealing with complex problems and real-world situations. In order to bridge these gaps, retrieval-augmented generation (RAG) systems have emerged in recent years. The core idea is

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles