search
HomeWeb Front-endJS TutorialShare some little-known hidden syntax or techniques in JavaScript

Share some little-known hidden syntax or techniques in JavaScript

javaScript is often considered the easiest language to get started with and the hardest to master, and I couldn’t agree more. This is because JavaScript is a very old and very flexible language with arcane syntax and outdated features.

I've been using JavaScript for many years, and until now, I occasionally discover some hidden syntax or trick that I didn't know about before. While these properties may be less well known, they are still well known.

Note: Variable promotion, closures, proxies, prototypal inheritance, asynchronous waiting, generators, etc. are not included here.

void operator

JavaScript has a unary void operator. You may have seen it used as void(0) or void 0. The function of void is to return undefined. The operand on the right side of it will be calculated normally, but no matter what the result is, void will return undefined. Using "0" is just a convention. It is not necessary to use '0', it can be any valid expression, like void , it will still return undefined.

Share some little-known hidden syntax or techniques in JavaScript

// void operator
void 0                  // returns undefined
void (0)                // returns undefined
void 'abc'              // returns undefined
void {}                 // returns undefined
void (1 === 1)          // returns undefined
void (1 !== 1)          // returns undefined
void anyfunction()      // returns undefined

Why create a special keyword to return undefined instead of just returning undefined? Sounds a bit redundant, doesn’t it?

Fun Facts

Actually, prior to ES5, in most browsers, the original undefined = "abc" could be assigned a new value. So, in those days, using void was a way to ensure that the original value of undefined was always returned.

Constructor brackets are optional

Yes, the brackets we add after the class name when calling the constructor - completely optional! (provided that there is no need to Any parameters passed to the constructor)

The following two code styles are considered valid JS syntax and the results are the same!

Share some little-known hidden syntax or techniques in JavaScript

// Constructor with brackets
const date = new Date()
const month = new Date().getMonth()
const myInstance = new MyClass()

// Constructor without brackets
const date = new Date
const month = (new Date).getMonth()
const myInstance = new MyClass

Yes Omitting parentheses for IIFE (immediately executed function)

The syntax of IIFE (immediately invoked function expression) has always been a bit strange to me, why are there so many parentheses?

Actually, these extra brackets are just to tell the JavaScript parser that the code to be parsed is a function expression, not a function. Knowing this, you can imagine that there are many ways to omit those extra parentheses and still work efficiently with IIFE.

Share some little-known hidden syntax or techniques in JavaScript

// IIFE

(function () {
  console.log('正常形式的 IIFE 调用')
})()

// 清爽的 IIEF 
void function() {
  console.log('酷酷的 IIFE 调用')
}()

void The operator tells the parser that the code is a function expression. Therefore, we can skip the parentheses around the function definition. Guess what? We can use any unary operator (void, , !, -, etc) and it will still work!

Isn’t this simpler than the original way of writing and has more B cells? What's up?

But, if you are a keen observer, you may be thinking, don't unary operators affect the result returned by IIFE?

It will affect the results. But the good news is that if you just return the result and store it in some variable, then you don't need the extra parentheses.

Share some little-known hidden syntax or techniques in JavaScript

#with declaration

JavaScript has a with statement block, and with is actually a keyword in JS. The syntax of the with block is as follows:

Share some little-known hidden syntax or techniques in JavaScript

#The with statement can be conveniently used to reference properties that already exist in a specific object, but it cannot be used to add properties to the object. To create new properties on an object, you must explicitly reference the object.

Share some little-known hidden syntax or techniques in JavaScript

Fun Fact

with blocks looks cool, right? It's even better than object destruction. Well, not really.

Using the with statement is generally discouraged as it is deprecated and completely prohibited in strict mode. It turns out that using with blocks increases some performance and security issues in the language.

Function constructor

Function statements are not the only way to define new functions. Functions can be dynamically defined using the function() constructor and the new operator.

Share some little-known hidden syntax or techniques in JavaScript

Interesting Facts

Function constructor is the mother of all constructors in JavaScript. Even the constructor of Object is a Function constructor. And Function's own constructor is also Function itself.

Thus, calling object.constructor.constructor...enough times will eventually return the Function constructor on any object in JavaScript.

函数属性

我们都知道函数是JavaScript中的第一类对象。因此,没有人阻止我们向函数添加自定义属性。在 JS 中这样做是有效的,然而,它很少被使用。

那么我们什么时候要这样做?

这里有一些很好的用例。例如,

可配置函数

假设我们有一个函数叫做 greet。我们希望函数根据不同的地区打印不同的问候消息,这个区域设置也应该是可配置的。我们可以在某个地方维护全局 locale 变量,也可以使用如下所示的函数属性实现该函数

Share some little-known hidden syntax or techniques in JavaScript

function greet () {
  if (greet.locale === 'ch') {
    console.log('中国,你好')
  } else if (greet.locale === 'jp') {
    console.log('扣你机哇!')
  } else {
    console.log('Hello World')
  }
}

greet() // Hello World
greet.locale = 'ch';
greet() // 中国,你好

具有静态变量的函数

另一个类似的例子。比方说,希望实现一个生成有序数字序列的数字生成器。通常您将使用带有静态计数器变量的 Class 或 IIFE 来跟踪最后一个值。这样我们就限制了对计数器的访问,同时也避免了使用额外的变量污染全局空间。

但是,如果我们希望能够灵活地读取甚至修改计数器,而又不污染全局空间,该怎么办呢?

我们仍然可以创建一个类,有一个计数器变量和一些额外的方法来读取它;或者我们可以偷懒,使用函数自定义的属性。

Share some little-known hidden syntax or techniques in JavaScript

Arguments 的属性

我相信你们大多数人都知道函数中的arguments对象。它是一个类似数组的对象,可以在所有函数中使用。它具有在调用函数时传递给函数的参数列表。但它也有一些其他有趣的性质:

  • arguments.callee: 当前调用的函数

  • arguments.callee.caller:调用当前函数的函数

Share some little-known hidden syntax or techniques in JavaScript

注意:虽然ES5禁止在严格模式下使用callee & caller,但在许多编译后的库中仍然很常见。所以,学习它们是值得的。

标记模板字符串

模板字符串文字是ES6中许多很酷的附加内容之一,但是,知道标记模板字符串是比较少的?

1Share some little-known hidden syntax or techniques in JavaScript

标记模板字符串允许你通过向模板字符串添加自定义标记来更好地将模板文字解析为字符串。Tag只是一个解析器函数,它获取字符串模板解释的所有字符串和值的数组,标记函数应返回最终字符串。

在下面的例子中,我们的自定义标记 —— 高亮显示,解释模板文本的值,并将解释后的值包装在结果字符串中,使用元素进行高亮显示。

1Share some little-known hidden syntax or techniques in JavaScript

Getters & Setters

在大多数情况下,JavaScript对象是简单的。假设我们有一个 user 对象,我们试图使用user访问它的age属性。使用 user.age 得到年龄属性的值,如果没有定义,我们得到未定义的值。

但是,并不一定要这么简单。JavaScript 对象具有 getter 和 setter 的概念。我们可以编写自定义Getter函数来返回我们想要的任何东西,而不是直接返回对象上的值,设置一个值也是一样。

这使我们可以在获取或设置字段时拥有强大的能力,如 virtual fieldsfield validationsside-effects

1Share some little-known hidden syntax or techniques in JavaScript

逗号操作符

JavaScript有一个逗号操作符。它允许我们在一行中用逗号分隔多个表达式,并返回上一个表达式的结果。

1Share some little-known hidden syntax or techniques in JavaScript

在这里,所有表达式都将被求值,结果变量将被赋值给expressionN返回的值。

我们经常在for循环中使用了逗号操作符

for (var a = 0, b = 10; a <= 10; a++, b--)

有时在一行中编写多个语句

function getNextValue() {    return counter++, console.log(counter), counter
}

或者

const getSquare = x => (console.log (x), x * x)

+ 加号操作符号

想要快速地将字符串转换为数字吗?

只需在字符串前面加上+运算符。加号运算符也适用于负数、八进制、十六进制、指数值。更重要的是,它甚至可以转换 Date 或者 Moment.js对象的时间戳!

1Share some little-known hidden syntax or techniques in JavaScript

!! Operator

Technically speaking, it is not a separate JavaScript operator. It's just the JavaScript inverse operator used twice.

If the expression is a true value, return true; otherwise, return false.

1Share some little-known hidden syntax or techniques in JavaScript

~ Non-Operators

Let's face it - no one cares about bitwise operators. When can we use it!

Here is an everyday use case regarding the tilde or bitwise NOT operator.

It turns out that the NOT operator is valid when used with numbers ~N => -(N 1) This expression only evaluates to "0" when N is -1.

We can take advantage of this by putting ~ in front of the indexOf(...) function, which performs a boolean check if the item exists in the string or array.

1Share some little-known hidden syntax or techniques in JavaScript

Note: ES6 and ES7 added a new .include() method for strings and arrays respectively. Of course, this is a cleaner way to check if an item exists in an array or string than the tilde operator.

Use of tags

The break and continue statements can be used in conjunction with the lebel statement to return to a specific location in the code. Used for nested loops to reduce the number of loops.

1Share some little-known hidden syntax or techniques in JavaScript

Recommended tutorial: "JavaScript Video Tutorial"

The above is the detailed content of Share some little-known hidden syntax or techniques in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools