3 Tips You Must Know When Learning JavaScript

3 Tips You Must Know When Learning JavaScript

Preface:

Often in Angular or React projects, seeing some old-school JavaScript code during code review will classify the developer as a beginner. But if you know the following 3 tips, you'll be considered the Yoda of modern JavaScript. So, let’s start our journey!

1. The magical extension operator

The spread operator, three dots ( ... ), is arguably my favorite operator in JavaScript. I mainly use it in the following 3 situations:

1. Copy array

const arr = [1, 2, 3, 4]
const newArr = [...arr]

console.log(newArr) // [1, 2, 3, 4]


2. Merge arrays

const numArr = [1, 2, 3, 4]
const alphaArr = ['a', 'b', 'c']
const newArr = [...numArr, ...alphaArr]

console.log(newArr) // [1, 2, 3, 4, 'a', 'b', 'c']


3. Expand the object

const rectangle = { width: 10, height: 10 }
const cube = { ...rectangle, length: 7 }

console.log(cube) // {width: 10, height: 10, length: 7}


2. Best way to perform null checks

Do you remember the first null check code you wrote? When JavaScript was not as advanced as it is today, I used to write this in my old code:

if (foo !== null && foo !== undefined) { }


Later, my life was saved by a simple if!

if (foo) {}


As long as the condition value foo is not one of the following values, it will be true.

  • null
  • undefined
  • NaN
  • Empty string ("")
  • false

In addition to simple if, modern JavaScript 's optional chaining operator?. and null coalescing operator?? can make our code more concise

1. Optional Chaining Operator

The optional chaining operator is a safe way to access properties of nested objects. This means we don't have to do multiple null checks when accessing a long list of object properties. The optional chaining operator makes expressions shorter and more concise when trying to access object properties that may not exist.

The following example checks whether the postal code of a customer's address is null:

const client = {
  name: 'Liu Xing',
  address:
    zipcode: '1234'
  }
}

// Old value method if (client && client.address && client.address.zipcode) {}
// A more modern approach to optional chaining if (client?.address?.zipcode) {}


2. Null coalescing operator

The null coalescing operator ( ?? ) is a logical operator that returns its right operand if its left operand is null or undefined , otherwise it returns its left operand.

const defaultMessage = 'Hello, the Zen of JavaScript'
const msg = defaultMessage ?? 'Hello Liu Xing';
console.log(msg); // Hello, the Zen of JavaScript'


If defaultMessage is null or undefined , it will print Hello Liu Xing

It becomes more powerful when we use it in sequence:

console.log(firstName ?? lastName ?? 'anonymous')


In this example, if firstName is not null/undefined , it will display firstName, otherwise, if lastName is not null/undefined , it will display lastName. Finally, if they are all null/undefined , it will display " anonymous ".

3. Using .map(), .reduce() and .filter()

Next, let’s talk about the powerful techniques of functional and reactive programming! When I first used it a few years ago, it really opened new doors for me. Every time I see this concise code, I am still struck by its beauty.

Today I will give examples of the three most commonly used methods: map, reduce and filter.

Before COVID, we went on vacation to Paris. So they went to the supermarket and bought some things. They bought food and daily necessities. But all items are in Euros and they want to know the price of each item and the total cost of their food in RMB.

Given that 1 Euro is equal to 7.18 Japanese Yen.

In the traditional way, we would do it using a classic loop:

const items = [
  {
    name: 'pineapple',
    price: 2,
    type: 'food'
  },
  {
    name: 'beef',
    price: 20,
    type: 'food'
  },
  {
    name: 'advocate',
    price: 1,
    type: 'food'
  },
  {
    name: 'shampoo',
    price: 5,
    type: 'other'
  }
]

let sum = 0
const itemsInYuan = []

for (let i = 0; i < items.length; i++) {
  const item = items[i]
  item.price *= 7.18
  itemsInYuan.push(item)
  if (item.type === 'food') {
    sum += item.price
  }
}

console.log(itemsInYuan)
/*
[
  { name: 'pineapple', price: 14.36, type: 'food' },
  { name: 'beef', price: 143.6, type: 'food' },
  { name: 'advocate', price: 7.18, type: 'food' },
  { name: 'shampoo', price: 35.9, type: 'other' }
]
*/
console.log(sum) // 165.14
Now let's use the functional programming method provided by JavaScript to implement this calculation.

const itemsInYuan = items.map(item => {
  const itemInYuan = { ...item }
  itemInYuan.price *= 7.18
  return itemInYuan
})

const sum = itemsInYuan.filter(item => item.type === 'food').reduce((total, item) => total + item.price, 0)

The above example uses the map method to convert Euros to Yen, uses filter to filter out non-food items, and uses reduce to calculate the sum of the prices.

This concludes this article about 3 tips you must know when learning JavaScript. For more relevant JavaScript tips, please search 123WORDPRESS.COM’s previous articles or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Share 5 JavaScript writing tips
  • Common JavaScript array operation skills (Part 2)
  • Common JavaScript array operation techniques
  • A practical guide to JavaScript destructuring assignment
  • Introduction and tips for using the interactive visualization JS library gojs
  • 20 JS abbreviation skills to improve work efficiency
  • Forty-nine JavaScript tips and tricks
  • Share 7 killer JS tips

<<:  HTML simple shopping quantity applet

>>:  About the processing of adaptive layout (using float and margin negative margin)

Recommend

HTML Several Special Dividing Line Effects

1. Basic lines 2. Special effects (the effects ar...

Introduction to network drivers for Linux devices

Wired network: Ethernet Wireless network: 4G, wif...

JavaScript implements displaying a drop-down box when the mouse passes over it

This article shares the specific code of JavaScri...

About MySQL innodb_autoinc_lock_mode

The innodb_autoinc_lock_mode parameter controls t...

Examples of using HTML list tags dl, ul, ol

Copy code The code is as follows: <!-- List ta...

Detailed explanation of the transition attribute of simple CSS animation

1. Understanding of transition attributes 1. The ...

Detailed explanation of JS browser storage

Table of contents introduction Cookie What are Co...

In-depth understanding of the matching logic of Server and Location in Nginx

Server matching logic When Nginx decides which se...

Solve the problem of MySQL using not in to include null values

Notice! ! ! select * from user where uid not in (...

Four ways to modify the default CSS style of element-ui components in Vue

Table of contents Preface 1. Use global unified o...

Detailed explanation of MySQL slow log query

Slow log query function The main function of slow...

Detailed steps to build the TypeScript environment and deploy it to VSCode

Table of contents TypeScript environment construc...

CSS3 mobile vw+rem method to achieve responsive layout without relying on JS

1. Introduction (1) Introduction to vw/vh Before ...

Realizing the effect of carousel based on jQuery

This article shares the specific code of jQuery t...