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

Detailed code examples of seven methods for vertical centering with CSS

When we edit a layout, we usually use horizontal ...

MySQL integrity constraints definition and example tutorial

Table of contents Integrity constraints Definitio...

Use of JavaScript sleep function

Table of contents 1.sleep function 2. setTimeout ...

Detailed explanation of how a SQL statement is executed in MySQL

Overview I have recently started learning MySQL r...

How to use Docker-compose to build an ELK cluster

All the orchestration files and configuration fil...

Jenkins packaging microservices to build Docker images and run them

Table of contents Environment Preparation start 1...

Create an SSL certificate that can be used in nginx and IIS

Table of contents Creating an SSL Certificate 1. ...

Practical notes on installing Jenkins with docker-compose

Create a Directory cd /usr/local/docker/ mkdir je...

HTML4.0 element default style arrangement

Copy code The code is as follows: html, address, ...

Vue implements button switching picture

This article example shares the specific code of ...

Fixed a bug caused by scrollbar occupying space

background This bug was caused by滾動條占據空間. I check...

AsyncHooks asynchronous life cycle in Node8

Async Hooks is a new feature of Node8. It provide...

Analysis of the solution to Nginx Session sharing problem

This article mainly introduces the solution to th...

How InnoDB implements serialization isolation level

Serialization implementation InnoDB implements se...