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

Springboot+VUE to realize login and registration

This article example shares the specific code of ...

HTML Nine-grid Layout Implementation Method

Diversifying website layouts is our front-end spe...

Solution to VMware virtual machine no network

Table of contents 1. Problem Description 2. Probl...

MySQL 5.7.17 compressed package installation-free configuration process diagram

There are two versions of MySQL database manageme...

Packetdrill's concise user guide

1. Packetdrill compilation and installation Sourc...

Use tomcat to deploy SpringBoot war package in centos environment

Prepare war package 1. Prepare the existing Sprin...

A brief discussion on the implementation of fuzzy query using wildcards in MySQL

In the MySQL database, when we need fuzzy query, ...

Tips for implementing multiple borders in CSS

1. Multiple borders[1] Background: box-shadow, ou...

js implements table drag options

This article example shares the specific code of ...

Detailed explanation of location and rewrite usage in nginx

1. Summary of location usage Location can locate ...

Summary of MySQL ALTER command knowledge points

When we need to change the table name or modify t...

MySQL 5.7.17 installation graphic tutorial (windows)

I recently started learning database, and I feel ...

The pitfall record of case when judging NULL value in MySQL

Table of contents Preface Mysql case when syntax:...

How to recover deleted MySQL 8.0.17 root account and password under Windows

I finished learning SQL by myself not long ago, a...