📜 ⬆️ ⬇️

Incredible javascript - tricks, misunderstandings and unusual features

Sooner or later, any developer is faced with incomprehensible problems, and given the many "features" of Vanilla JS, this happens quite often here. Regardless of the reasons, the search for solutions may be delayed or lead to the creation of another bike. And the right path often lies on the surface, you just need to know where to look for it and how to apply the knowledge gained. We will talk about the strangeness and surprises of JS and their correct interpretation with experts in this field Claudia Hernández and Jakob Mattsson.



Claudia hernández


Claudia - Senior Frontend Engineer in the Paris office Dailymotion. She crossed the Atlantic to work on projects for companies such as Air France, EDF, Groupe SEB and AĂ©roport de Paris. When does not write the code, reads books. Claudia also loves to travel and learn new cultures.

- Claudia, good afternoon! Please tell us a little about yourself and your work.
')
Claudia Hernández: Hello! My name is Claudia Hernández, I am a Mexican developer. Now is a senior manager at Dailymotion in Paris. Soon we are going to launch the most important project on which the company has been working for several years. We are preparing a complete redesign of the platform. The most interesting thing is that we replaced our old stack and switched to more interesting technologies, such as React. I had the opportunity to learn about GraphQL and Apollo. We were given the freedom to choose the technologies that, in our opinion, best fit the project. Every day, I work with designers and backend developers to bring the new platform to the end.

- At HolyJS you will make a presentation on " Down the Rabbit Hole: JavaScript in Wonderland" . This is not your first time talking about this, tell me, how does a report change over time? Do new unusual problems and solutions appear? Or the number of "tricks" is growing with the development of the language itself?

Claudia Hernández: The JavaScript language will soon be 22 years old. In JS, things that are possible until recently seemed unreal to us. We have fantastic tools, such as Babel, which allows us to test even unapproved functions.

Evolution makes many tricks obsolete over time. For example, the trick of using the ~ operator in conjunction with the Array#indexOf method is not mandatory, since a new function has appeared in ES7 Array#includes .

We live in a rapidly changing world where all new features are constantly being added, tested and approved or rejected by the community. This will definitely solve many problems that we faced in the past, but I am sure that this will also cause new problems that we haven’t thought about yet.

I truly believe that it is very important for us developers to understand the consequences of all these changes in JS. It's very easy to get started in JS, but it's hard to understand the language fully. And, paradoxically, many of these errors have a real logical / historical explanation - and simply recognizing problems at an early stage would eliminate the ensuing headache.

- Not everyone likes spoilers, but really want to understand what to expect. Is the “immersion” planned in particular of the language and certain constructions, such as call, join, filter, or will it be a story about new features planned for release?

Claudia Hernández: JavaScript is a very extensive, wide language. It has many features that I could talk about, but I’m talking about exactly what has caused me trouble in the past. Now the conversation is actually divided into 4 parts, according to the number of topics that I will discuss. One section is entirely devoted to explaining the internal elements of the Array#sort sorting method. I will talk in detail about the real algorithms behind it in every JS engine. It's hard to believe, but sometimes your own sorting method in JS can be faster than your own! I bet a few developers really thought about this possibility, but this knowledge may be useful when you have to handle complex sorting cases. In addition, I will explain the mystery of the “JS Fuck” syntax, which many people seem to recognize, but have no idea how it actually works.

- How do you think, how often does a regular developer, without a decade of experience behind him, have questions that require non-trivial solutions and the use of "tricks"?

Claudia Hernández: I do not think that “meeting” with an error depends on experience. We often work on different projects with many different requirements, and when one of these “tricks” is useful for a specific task, it is only a matter of time. It is not only about the tricks themselves, but also about the logic underlying them.

The expressiveness of JS allows us to find thousands of different solutions for a problem and move forward. Understanding the language itself will help us ultimately become better.

- Please tell us about the beautiful and unusual examples of manipulations with the code in JS?

Claudia Hernández: A good example is the bitwise operators in JS. They are rarely used by developers ... why? Their behavior is to take a number as a parameter, convert it to a sequence of bits, perform some operation on these bits, and then convert the result to a number. It is very unusual if we start using these capabilities in our daily work.

However, we can use truncate. It is faster than using

 Math.trunc(): const float = 281.0901 ~~float               // 281 float | 0            // 281 float << 0          // 281 float >> 0         // 281 float >>> 0       // 281 

The disadvantages are that you need to be careful with very large numbers, since these operators perform 32-bit conversions, and the results may be erroneous for values ​​over 2 billion

- Is there a certain "layer" of development, where the use of the tricks of JS is especially important?

Claudia Hernández: Actually, no. Understanding these reservations means understanding the language. Understanding language in deep form is part of the developer’s life. For me, the ultimate goal of this report is to demonstrate not the quirkiness of JS, but the fact that JS is in fact a very complex language that deserves proper study from beginning to end.

- Tell me, please, what is your opinion about the use of the “magic types” NaN, null and undefined? Or for you, they have long ceased to be a mystery?

Claudia Hernández: Checking that our variables are different from undefined or null is part of our daily life. At least I do it quite often. We need these comparisons to handle empty states in our applications. They still surprise me sometimes. Null refers to object, even if it is a primitive type, undefined is the type itself, undefined and null are freely equal, and so on. Too many exceptions. We must be careful when using them.

- Do you have a cheat sheet for the correct application of NaN, null and undefined in the program code? Could you give a couple of examples of what is not exactly worth doing?

Claudia Hernández: I do not have a cheat sheet. When I check whether an array exists or not, I usually check to see if the array object is null or not. Usually it looks like this:

 !yourArray.length 

But maybe you also want to check if the variable you are referring to is really an array (and not some other type of object with a length property like arguments or NodeList), so you can add to this:

 !Array.isArray(yourArray) || !yourArray.length 

If you really wanted to know if the JS value in this array is empty or null? To find out if a value exists in a given position, you can simply do:

 position < yourArray.length 

And finally, to determine if the specified value in your array was defined and contains something other than null, you can simply add:

 typeof yourArray[position] !== 'undefined' && youArray[position] !== null 

This can be simplified:

 yourArray[position] != null 

- Recently, the article “ Why use static types in JavaScript? ” Dealt with the Flow library. The following article addresses the advantages and disadvantages of such a development. How do you feel about the ability to switch between dynamic and static types in JS? Can this be considered a trick, or is this the right direction for language development?

Claudia Hernández: I came from Java / C ++. The fact that JS is a dynamically typed language was unusual only at the very beginning. Now I think that many developers feel quite comfortable with this paradigm and really know how to use it to their advantage.

Sometimes the dynamic nature of JS can be useful. It seems to me that static typing adds a lot of unnecessary verbiage to the code; it becomes overloaded. However, I do not say that we should refuse them. I understand their advantages, for example, reducing the number of errors, the clarity of the code for a large team, easier detection of problems. I know that there are cases when adding a static check type is preferable to others.

The point is that if you really want to make sure that your code works properly, you should rely more on your test suite than just on type checking. Good tests can catch most of the errors caused by the wrong types.

- Thank you so much for the conversation. We will be glad to welcome you at the conference HolyJS 2017 Piter.

Claudia Hernández: Thank you!

Jakob mattsson


Jakob - technical director, consultant, but first and foremost a developer. He worked in various companies, including start-ups, financial organizations and venture funds. He was engaged in several programming languages, and also wrote several of his own. He is passionate about working with JavaScript, explaining it with a combination of simplicity and applicability. Being a fan of libraries, published 65 JavaScript modules.

- Jakob, good afternoon! Please tell us a little about yourself and your work.

Jakob Mattsson: Good afternoon! I was born and raised in Sweden, so I have something in common with you. I'm used to cold. A few days of summer a year, and then 360 days of frost.

I started programming in high school and from the very beginning I participated in startups. I worked on everything from advertising and feedback systems to sports fishing and financial services applications. Currently I live in London and work in the infamous hedge fund.

I like to spend my time creating and researching systems, both in coding and out of it, for example, Rubik's cube or studying the housing market.

- At HolyJS you will make a report " Forgotten funky functions ". Do not you think that everyone wants to hear about newfangled things, for example, transducers or the next implementation of Array # map and Array # filter, and you share some other information. What is the reason? Or is everything new - is it well forgotten old?

Jakob Mattsson: I think there has already been a lot of talk about new libraries. Everyone always tries to talk about modern. For me, this is not the main thing in JavaScript. Let me explain.

I did not start programming in JavaScript because it was popular and fashionable. I started programming JS because it was simple and affordable. I was not one of those developers who create websites and therefore had to learn JavaScript. I just needed a simple and portable scripting language.

I spent a couple of weeks to decide which one to use for the project. This was around the time when the very first version of Node.js came out. Candidates were Bash, Perl, Ruby, Python and JavaScript. Everyone has their own opinion about which one is better, but for me JavaScript had two main advantages:

1) It worked everywhere (in browsers, on desktop computers, etc.).
2) JS has a surprisingly simple syntax. Standard loops, ifs and switches. I liked in JS that there were no namespaces, classes or the like. Only the correct functions (with closures) and the best syntax of objects in the world (JSON).

Despite the fact that JavaScript was simple, you could create from it all the other complicated things and non-trivial concepts. Namespaces are just objects. Classes are just functions. Private variables are simply ordinary variables captured in closures. And so on. This was beautiful.

Today JavaScript is changing and evolving. It loses touch with the simple core, many new developers may not even think about these problems and changes, and this is very important. That's why I decided to talk about the classic parts: the forgotten old, as you said.

- Do you think async / await, which has reached the fourth stage in ECMAScript, can be considered something unusual, or is it the standard expected functionality?

Jakob Mattsson: I have two opinions:

1) On the one hand, it is just syntactic sugar and is not unusual.
2) On the other hand, this is a good example of changing the language. I'm talking about how JavaScript has changed over the past couple of years - and continues. JS was very simple, and you could write code without much effort. Now JavaScript is trying to change. He has the power because it works in various environments, but gradually it loses its lightness. It seems to me a little sad.

- If you go back to our topic, do you often have to use “non-standard” JS in your work when writing code, creating clever constructions, or is there always an ugly but standard solution?

Jakob Mattsson: I think the ability to do non-standard things is important, and you should do it, but only when you really need it. I mainly do “magic” things at low levels. Non-standard JS should be avoided in high-level application code, where domain objects and business logic live, but it can be useful in creating frameworks and powerful functions.

There are no such things to be avoided "always." There is a time and place for even the craziest things. There is a very good explanation for this in the essay “Beating the averages” by Paul Graham (founder of Y Combinator). I think he shaped the way I think about programming languages.

- Could you tell us about non-standard code examples, which, except as a trick, cannot be called.

Jakob Mattsson: I don't think there are such things. Abstracted, this is quite a normal situation. I think the only thing I would be careful about is that you need to ask yourself the question “will it work the same in all environments”, because if the answer is no, then this is most likely a bad idea.

- In your or third-party projects, have you encountered unusual behavior of programs? Have there been any places that seemed unusual to you, incorrectly working even with correct writing? What should the developer do in this case?

Jakob Mattsson: When something does not work or behaves strangely, despite the fact that the code is written “correctly,” then the problem is usually not in the computer, but in who is sitting behind it.

Perhaps the developer misinterprets the terms of reference. Maybe he does not have a sufficient understanding of the tools - language, structure, libraries, environment. It is for this reason that it is important to understand the basics and the inner workings.

A classic example in JavaScript is the use of a loop variable in for-loop, which goes to the closure. I think that every JS developer who used it before his latest updates encountered this. You need to study the tools and surround yourself with smart people who can explain and help in difficult situations and then a positive result will not take long.

- Thank you so much for the conversation. We look forward to seeing you at the HolyJS conference in St. Petersburg.

Jakob Mattsson: Thank you. See you at the conference.

The full topics of reports that our speakers will present at the nearest Holy JS Piter, sound like this:
Claudia Hernández: Down the Rabbit Hole: JavaScript in Wonderland
Jakob Mattsson: Forgotten funky functions
In addition to Claudia and Jacob, other experts will speak at the conference with interesting reports of varying complexity on JS. See what awaits participants, for example, here .
And we opened access to 10 key reports from the last event here .

Source: https://habr.com/ru/post/329302/


All Articles