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

The principle and application of ES6 deconstruction assignment

Table of contents Array destructuring assignment ...

How to change the dot in the WeChat applet swiper-dot into a slider

Table of contents background Target Effect Ideas ...

MySQL joint table query basic operation left-join common pitfalls

Overview For small and medium-sized projects, joi...

Web design dimensions and rules for advertising design on web pages

1. Under 800*600, if the width of the web page is...

Detailed explanation of downloading, installing and using nginx server

download http://nginx.org/en/download.html Unzip ...

Detailed explanation of node.js installation and HbuilderX configuration

npm installation tutorial: 1. Download the Node.j...

How to expand Linux swap memory

Swap memory mainly means that when the physical m...

How to set the border of a web page table

<br />Previously, we learned how to set cell...

How to use VIM editor in Linux

As a powerful editor with rich options, Vim is lo...

MySQL master-slave replication configuration process

Main library configuration 1. Configure mysql vim...

Analysis of MySQL example DTID master-slave principle

Table of contents 1. Basic Concepts of GTID 2. GT...

How to install Mysql5.7 in Centos6

environment Centos 6.6 MySQL 5.7 Install If the s...

Summary of commonly used operators and functions in MySQL

Let’s build the data table first. use test; creat...