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

How to pass the value of the select drop-down box to the id to implement the code

The complete code is as follows : HTML code: Copy ...

CSS3 realizes various graphic effects of small arrows

It’s great to use CSS to realize various graphics...

MySQL msi installation tutorial under windows10 with pictures and text

1. Download 1. Click the latest download from the...

Detailed steps to build an NFS file sharing server in Linux

Linux builds NFS server In order to achieve data ...

Example statements for indexes and constraints in MySQL

Foreign Keys Query which tables the primary key o...

The most commonly used HTML tags to create web pages

1. Optimization of commonly used HTML tags HTML s...

Advanced Usage Examples of mv Command in Linux

Preface The mv command is the abbreviation of mov...

Linux installation apache server configuration process

Prepare the bags Install Check if Apache is alrea...

How to implement Svelte's Defer Transition in Vue

I recently watched Rich Harris's <Rethinki...

Implementing parameter jump function in Vue project

Page Description:​ Main page: name —> shisheng...

How to get the height of MySQL innodb B+tree

Preface The reason why MySQL's innodb engine ...

Example of how to enable Brotli compression algorithm for Nginx

Brotli is a new data format that can provide a co...

Pure CSS to change the color of the picture

The css technique for changing the color of an im...