Six weird and useful things about JavaScript

Six weird and useful things about JavaScript

Today I will share with you some little-known facts about JavaScript. You may have heard of them, but they may also surprise you. Without further ado, let’s take a look!

1. Deconstruction Tips

Usually we need to use some properties of a multi-layered nested object, and we will deconstruct it and use it

let obj = {
  part1: {
    name: 'Zero One',
    age: 23
  }
}

// deconstruct const { part1: { name, age } } = obj
// Use console.log(name, age) // 0123

In this case, after you deconstruct name and age from part1, you cannot use the part1 attributes in the variable obj, such as:

// .... omitted const { part1: { name, age } } = obj
console.log(part1) // Uncaught ReferenceError: part1 is not defined

In fact, you can destructure multiple times, such as:

// .... omitted const { part1: { name, age }, part1 } = obj
console.log(part1) // {name: "零一", age: 23}

2. Digital separator

Sometimes you define a numeric constant in a file

const myMoney = 1000000000000

There are so many 0s, 1, 2... 6, 7... I feel dizzy counting them all. What should I do?

Tidy up the number separators!

const myMoney = 1_000_000_000_000

console.log(myMoney) // 1000000000000

There is no problem writing it this way, and it is more intuitive after the numbers are separated! !

3. Who is better in try...catch...finally?

In a normal function call, return generally ends the execution of the function early.

function demo () {
  return 1
  console.log('I am zero one')
  return 2
}

console.log(demo()) // 1

In try...catch...finally, return will not terminate execution early.

function demo () {
  try {
    return 1
  } catch (err) {
    console.log(err)
    return 2
  finally
    return 3
  }
}

console.log(demo()) // What does it return? ?

What will this program return? Think about it

Tow hours Later~

The answer is: 3

Finally, I concluded that finally is more powerful.

Then we can do some tricks

function demo () {
  try {
    return 1
  } catch (err) {
    console.log(err)
    return 2
  finally
    try {
      return 3
    finally
      return 4
    }
  }
}

console.log(demo()) // returns 4

4. Get the current call stack

function firstFunction() { secondFunction(); } 
function secondFunction() { thridFunction(); } 
function thridFunction() { console.log(new Error().stack); }

firstFunction();

//=> Error 
// at thridFunction (<anonymous>:2:17) 
// at secondFunction (<anonymous>:5:5) 
// at firstFunction (<anonymous>:8:5) 
// at <anonymous>:10:1

new Error().stack In this way, you can get the call stack information of the current code execution at any time, which is also a way to debug the code

5. Generate a random string with one line of code

When I first learned JS, I wanted to implement a function to generate a random string. This is how I did it.

function hash () {
  let s = ''
  const strs = [
    'a', 'b', 'c', 'd', 'e', ​​'f', 'g', 
    'h', 'i', 'j', 'k', 'l', 'm', 'n', 
    'o', 'p', 'q', 'r', 's', 't', 'u', 
    'v', 'w', 'x', 'y', 'z', '0', '1', 
    '2', '3', '4', '5', '6', '7', '8',
    '9',
  ]
  for(let i = 0; i < 10; i++) {
    s += strs[Math.floor(Math.random() * strs.length)]
  }
  returns
}

hash() // 'www7v2if9r'

What a hassle! It took me a long time to write the 26 letters and 10 numbers (of course, you can also use ASCII code, which will be more convenient)

Next, we will introduce a method that can achieve the function of "randomly generating a string" with only one line of super short code.

const str = Math.random().toString(36).substr(2, 10);
console.log(str); // 'w5jetivt7e'

We also got a 10-digit random string, which is pretty cool 😎, compared to the one I wrote, it’s so cool

First, Math.random() generates a number in [0, 1), which is 0.123312, 0.982931, etc. Then call the toString method of number to convert it into base 36. According to MDN, the base 36 conversion should include letters a~z and numbers 0~9. Because the generated number is 0.89kjna21sa or something like this, we need to cut off the decimal part, that is, cut off 10 characters from index 2 to get the random string we want.

Many open source libraries use this approach to create random IDs for DOM elements.

6. The fastest way to get DOM

Elements with an id attribute in HTML will be referenced by the global ID variable of the same name

<div id="zero2one"></div>

Originally, the DOM was obtained like this

const el = document.getElementById('zero2one')  
console.log(el) // <div id="zero2one"></div>

Now you can do this

console.log(zero2one) // <div id="zero2one"></div>

Isn't it convenient?^-^

Summarize

This is the end of this article about six weird but practical JavaScript techniques. For more relevant practical JavaScript techniques, please search previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JS determines whether there are duplicate values ​​in an array in three practical ways
  • 100 Practical JS Custom Functions You Can't Miss
  • Five practical js advanced skills
  • 12 practical ways to remove spaces in js
  • Some more practical js methods
  • Very practical js tab switching effect
  • js form validation method (practical)
  • js script learning more practical basis
  • Javascript Practical Tips

<<:  MySQL sorting principles and case analysis

>>:  HTML+CSS realizes scrolling to the element position to display the loading animation effect

Recommend

Quickly learn MySQL basics

Table of contents Understanding SQL Understanding...

View the port number occupied by the process in Linux

For Linux system administrators, it is crucial to...

JavaScript function encapsulates random color verification code (complete code)

An n-digit verification code consisting of number...

Vue large screen display adaptation method

This article example shares the specific code for...

How to use Linux locate command

01. Command Overview The locate command is actual...

Detailed explanation of Linux text processing tools

1. Count the number of users whose default shell ...

Linux uses stty to display and modify terminal line settings

Sttty is a common command for changing and printi...

10 Tips for Mobile App User Interface Design

Tip 1: Stay focused The best mobile apps focus on...

MySQL 5.7.12 installation and configuration tutorial under Mac OS 10.11

How to install and configure MySQL on Mac OS 10.1...

How to deploy k8s in docker

K8s k8s is a cluster. There are multiple Namespac...

Detailed explanation of Nginx's rewrite module

The rewrite module is the ngx_http_rewrite_module...

Implementation of MySQL joint index (composite index)

Joint Index The definition of the joint index in ...

mysql 8.0.12 winx64 download and installation tutorial

MySQL 8.0.12 download and installation tutorial f...