The 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')}() // trueThe 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')})() // trueor:
(function(){alert('iifksp')}()) // trueAlthough 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')} // undefinedThis 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_tokenBecause 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')}(); // undefinedAssignment, 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')}() // -1Even the following keywords work well:
void function(){alert('iifksp')}() // undefined
new function(){alert('iifksp')}() // Object
delete function(){alert('iifksp')}() // trueFinally, 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')}()) // undefinedHaving 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):

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!
JavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AMThe main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.
Understanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AMUnderstanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools






