search
HomeWeb Front-endJS TutorialThe relationship between js functions and exclamation points

In JavaScript development, we may encounter some js functions, and these js functions are preceded by exclamation marks. Have you ever thought about js functions with exclamation marks and without exclamation marks? What's the difference! Let’s take a look at what this article has to say!

What happens if you add an exclamation point (!) before function?

For example, the following code:

!function(){alert('iifksp')}()        // true

The value obtained after running on the console is true. Why is true? It is easy to understand because of this anonymous function There is no return value. The default return value is undefined. The negation result is naturally true. So the question is not about the result value, but why can the negation operation make the self-tuning of an anonymous function legal?

We may be more accustomed to adding brackets to call anonymous functions:

(function(){alert('iifksp')})()        // true

or:

(function(){alert('iifksp')}())        // true

Although the positions of the brackets above are different, the effect is completely Same.

So, what are the benefits that make many people so fond of this exclamation point method? If it is just to save one character, it is too unnecessary. Even a 100K library may not save much space. Since it is not space, it means that there may be time considerations. The facts are difficult to tell. Performance is mentioned at the end of the article.

Back to the core question, why can this be done? The even more central question is, why is this necessary?

In fact, whether it is parentheses or exclamation points, there is only one thing that the entire statement can do legally, which is turning a function declaration statement into an expression.

function a(){alert('iifksp')}        // undefined

This is a function declaration. If you call it with parentheses directly after such a declaration, the parser will naturally not understand it and report an error:

function a(){alert('iifksp')}()        // SyntaxError: unexpected_token

Because such code is confused Function declaration and function call. Function a declared in this way should be called as a();.

But the brackets are different. It converts a function declaration into an expression. The parser no longer processes function a as a function declaration, but as a function expression , and therefore it can only be accessed when the program executes function a.

So, Any method that eliminates the ambiguity between function declarations and function expressions can be correctly recognized by the parser. For example:

var i = function(){return 10}();        // undefined
1 && function(){return true}();        // true
1, function(){alert('iifksp')}();        // undefined

Assignment, logic, even commas, various operators can tell the parser that this is not a function declaration, it is a function expression. Moreover, unary operations on functions can be regarded as the fastest way to eliminate ambiguity. The exclamation mark is just one of them. If you don’t care about the return value, these unary operations are all valid:

!function(){alert('iifksp')}()        // true
+function(){alert('iifksp')}()        // NaN
-function(){alert('iifksp')}()        // NaN
~function(){alert('iifksp')}()        // -1

Even the following keywords work well:

void function(){alert('iifksp')}()        // undefined
new function(){alert('iifksp')}()        // Object
delete function(){alert('iifksp')}()        // true

Finally, the brackets do the same thing. Disambiguation is its real job, not the function as a whole, so regardless of the brackets Whether it is enclosed in the declaration or the entire function is enclosed, it is legal:

(function(){alert('iifksp')})()        // undefined
(function(){alert('iifksp')}())        // undefined

Having said so much, in fact, what I am talking about are some of the most basic concepts - statements, expressions, expressions Statements, these concepts are as easy to confuse as pointers and pointer variables. Although this kind of confusion has no expressive impact on programming, it is a stumbling block that can break your head at any time because of it.

Finally let’s discuss performance. I simply created a test on jsperf: http://jsperf.com/js-funcion-expression-speed , which can be accessed with different browsers and run the test to see the results. I also listed the results in the following table (because I am relatively poor, the test configuration is a bit embarrassing, but there is nothing I can do: Pentium dual-core 1.4G, 2G memory, win7 Enterprise Edition):

The relationship between js functions and exclamation points

It can be seen that the results produced by different methods are not the same, and they vary greatly and vary from browser to browser.

But we can still find many commonalities among them: new method is always the slowest - this is also a matter of course. Others Many differences in aspects are actually not big, but one thing is for sure, the exclamation mark is not the most ideal choice. Looking back at the traditional brackets , always performs very quickly in the test , and in most cases is faster than the exclamation mark - so there is no problem with the method we usually use, and it can even be said to be optimal. The plus and minus signs perform amazingly in Chrome, and are generally very fast in other browsers, and have better effects than the exclamation mark.

Of course this is just a simple test and cannot explain the problem. But some conclusions make sense: parentheses and plus and minus signs are optimal.

But why do so many developers love exclamation points? I think this is just a matter of habit, and the advantages and disadvantages between them can be completely ignored. Once you get used to a coding style, this convention will transform your program from confusing to readable. If you get used to the exclamation point, I have to admit, it has better readability than parentheses. I don’t have to pay attention to bracket matching when reading, and I don’t have to carelessly forget about it when writing——

The above is the detailed content of The relationship between js functions and exclamation points. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

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.

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

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),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.