search
HomeWeb Front-endJS TutorialJavaScript explained from a Java developer's perspective

We can’t explain all the details of JavaScript in one blog post. If you're involved in web application development at one level or another, our Java Tools and Technology Scope report reveals that the majority (71%) of Java developers fall into this category, but you're just having trouble with JavaScript. hinder.

There is no doubt that you already know Java and JavaScript. No matter how similar they are named, they do not share much in common with each other. Java's static typing, straightforward syntax, and verbosity are vastly different from JavaScript's dynamics, lack of consistency, and weirdness.

 However, JavaScript is the programming language of the web, and has recently gained considerable attention on the server side due to the development of Node.js and the JVM's own Nashorn JavaScript engine.

In this article, I don’t want to just talk about the good and bad aspects of JavaScript, or repeat the countless JavaScript tutorials that anyone can find for free. I want to list some technical points that are helpful in understanding JavaScript as a language, and understand it from a close horse perspective.

We will include the following language-level technical points in this article:

Universality of JavaScript

Functional programming issues in JavaScript

Different inheritance from Java

In addition, you will find some recommendations for tools that are not available without these tools , you don't want to start a JavaScript project, contains tools for code quality analysis and testing frameworks for build systems.

Advantages

Write it once and run it almost everywhere!

There is no doubt that JavaScript is the web programming language, the compilation target of many other languages, and the ultimate way to prove that sometimes people just want to have more free time. Still, that's not a bad thing. Every computer capable of browsing modern websites is equipped with a powerful and usable JavaScript engine. Best of all, JavaScript code can be run on the backend.

 Nashorn, a lightweight and high-performance JavaScript runtime built into our favorite JVM, is fully capable of interpreting JavaScript scripts and can also interpret JavaScript scripts with Java code in the project.

Given the freedom available to every computer running it, JavaScript becomes the perfect continuation of the Java experience.

 Functional programming: First-class citizens are functions, not recursion

  Functions in JavaScript are first-class citizens. They are values ​​that can be stored in variables, passed to other functions, and executed at the appropriate time.

 This opens the door to the world of functional programming, which is the perfect way to structure JavaScript programming.

Note that an object in JavaScript is a mapping of anything. Every attribute of the object is in the same mapping: functions, properties, constructors; variability brings greater hidden dangers, and With Java, you can at least ensure that method and field structures are stable to some extent.

 This, in turn, makes functional programming more advantageous: involving small, understandable functions and immutable data structures is the way to run in JavaScript.

 This is not without basis. The following is an example of defining a reduce function in JavaScript, from the book "Eloquent JavaScript".

function forEach(array, action) {
for (var i = 0; i < array.length; i++) {
action(array[i]); //apply action to every element of the arra.
}
}
  
function reduce(combine, base, array) {
forEach(array, function (element) {
base = combine(base, element); // and here we apply function passed as ‘combine’ parameter to ‘base’ and ‘element’
});
return base;
}
  
function add(a, b) { // btw, this is how you define a function in JavaScript
return a + b;
}
  
function sum(numbers) {
return reduce(add, 0, numbers);
}

Note: We are not using the recursive version of reduce here. JavaScript does not feature tail calls [Note 1], which means that the recursive version of each function will use the depth of the stack. Like Java, if you recurse too deep, the program will crash.

 Inheritance: Just like the real world

 JavaScript inheritance is based on prototypes. That is, you do not extend the type of other types, but in fact, the instances you have inherit functionality from other instances.

Imagine that object A is like a map, which we just mentioned a little bit, but from a different perspective, and then another map-like object B inherits everything from A.

This means that B can access all parts of A: A’s methods, fields, etc.

In practice, I've never seen anyone actually use simple prototype-based inheritance. Usually when someone needs inheritance, he just constructs the class, so you can use all the broad skills and working patterns of class-based inheritance.
——Rene Saarsoo, XRebel front-end engineer

I’m not sure what Java developers should take away from this, but beware of differences in inheritance methods, pay special attention to parent objects, and not accidentally change the behavior of the entire program.

  Things to avoid at all times

Listing unreliable JavaScript design decisions is easier than you think. The most obvious place to avoid in a JavaScript program is the declaration of global variables.

 Note that in JavaScript, whenever you define a variable without using the var keyword, the defined variables are pushed to the top of the scope in which they are defined. This means that every variable defined in this way will run to the top of the global scope, causing conflicts and unexpected headaches for you and your colleagues.

  Strict mode can be turned on. Just write "use strict" at the top of your script file and an inadvertently written global variable declaration will show an error.

Another important difference between JavaScript and Java is that the former is a dynamically typed language, and the essence is that everything can be of any type. This is obvious and cannot be emphasized enough: do not reuse the same variable for different types of values.

  The tracking was originally a string type variable, but now it has become a floating point number or function, trust me!

Also, I don’t want to get too deep into the discussion of types and booleans, but be wary of implicit type conversions that the JavaScript engine throws at you.

 Tips to Get the Job Done

 As I mentioned above, when programming you need to pay more attention to the syntax and quirks of the language than just know it. Projects rarely fail due to language deficiencies, more often they are related to deficiencies in the overall project framework. Here are some tools to help you deliver your projects.

 Static Code Analysis

Most projects are different, and their complexity and requirements lead to a lot of details on how you go about your code base. Nonetheless, there is a consistent goal everywhere, and that is code quality.

 Yes, code quality, the most important job for any developer is delivery. But don't compromise on quality, and don't be reluctant to share the code you submit with colleagues because you don't feel confident in it.

Fortunately, JavaScript has a decent solution - JSHint. JSHint is a static analysis tool tailored for JavaScript, similar to FindBug for Java code. JSHint can run through your code base and highlight suspicious or problematic areas that, even if you don't create bugs right away, may become difficult to maintain in the future. Supporting it in your project is fairly simple. Do yourself a favor - if you're writing JavaScript code, use JSHint to make it safer and less awkward.

  REPL

  REPL stands for "Read-Eval-Print Loop" [Note 2], which is a powerful tool for many dynamic languages. If you have seen Scala or Groovy, you will definitely be able to understand this concept.

 One way to activate JavaScript REPL is to open the browser's console, which produces an interface for evaluating JavaScript code.

JavaScript explained from a Java developers perspective

Another more convenient tool is jjs, which is bundled with JDK1.8.

JavaScript explained from a Java developers perspective

It is a command line tool that allows you to access the Nashorn JavaScript engine in the JDK, fully capable of executing even the most rigorous JavaScript scripts.

 Testing

 With any project, you want to run some tests. Testing is especially important for dynamically typed languages, and it is best to choose a testing framework. I recommend Jasmine, which is a behavior-driven development framework for testing JavaScript.

JavaScript explained from a Java developers perspective

In Jasmine, you use describe to describe your test suite, which blocks access to the code you want to test. After the code under test is completed, you expect some results.

Obviously this is not meant to be a tutorial, but I wanted to give you a glimpse of how elegant JavaScript code can look. Jasmine is one of the best practices for JavaScript projects, and we privately apply it to the ZeroTurnaround project in product development, especially for the JavaScript-rich interactive analyzer XRebel that runs continuously.

 Build Tools

Finally, the more important thing your project will need is a build tool. If you're using JavaScript in a Java project, make sure you can avoid the Java build tools, and that's almost enough. However, for independent JavaScript projects, there is no need to introduce the behemoth-Maven [Note 3].

The build tool that can be considered for JavaScript projects is GulpJS [Note 4]. It is a plugin-based build system for which you assign tasks. The task can be "copy the .js file in the src directory to dest", or "compress my JavaScript code for production environment". What’s shocking is that GulpJS adds filters to task-related file streams, so you can add the above two tasks into one effective clean.

There are also a large number of available plug-ins. With a proper build system, you will find that collaboration in the project will be much easier.

 Conclusion

  We have only seen the tip of the JavaScript iceberg and tried to introduce some concepts and tools that Java developers should know when solving JavaScript. Naturally, there's no comprehensive list of techniques to learn here, but if you're ready to dive into a JavaScript project without looking back, this will get you started, and embracing JavaScript's quirks will help you not be frustrated as often.

 Do you know the secrets or best practices that make JS developers happy? There is no doubt that it should be shared! Comment below or chat with me on Twitter: @shelajev. I'd love to hear your thoughts!

Note 1: In computer science, tail call refers to the situation where the last action in a function is a function call: that is, the return value of this call is directly returned by the current function. In this case, the calling position is called the tail position. If this function calls itself at the tail position (or another function that calls itself at the tail position, etc.), this situation is called tail recursion, which is a special case of recursion. Tail calls are not necessarily recursive calls, but tail recursion is particularly useful and easier to implement. http://zh.wikipedia.org/wiki/Tail call

Note 2: REPL is a simple, interactive programming environment. The term is often used to refer to a Lisp interactive development environment, but can also refer to the command-line mode and programs such as APL, BASIC, Clojure, F#, Haskell, J, Julia, Perl, PHP, Prolog, Python, R, Programming languages ​​such as Ruby, Scala, Smalltalk, Standard ML, Tcl, and Javascript have similar programming environments. This is also called an interactive toplevel. http://zh.wikipedia.org/wiki/%E8%AF%BB%E5%8F%96%EF%B9%A3%E6%B1%82%E5%80%BC%EF%B9%A3%E8 %BE%93%E5%87%BA%E5%BE%AA%E7%8E%AF

Note 3: In addition to its program building capabilities, Maven also provides advanced project management tools that Ant lacks. Since Maven's default build rules are highly reusable, simple projects can often be built with two or three lines of Maven build scripts, while using Ant requires more than a dozen lines. In fact, many Apache Jakarta projects now use Maven due to its project-oriented approach, and the adoption of Maven by corporate projects continues to grow. http://www.oschina.net/p/maven

Note 4: Writing HTMLCSS Javascript from scratch is a thing of the last century. Today’s JavaScript is written through editors such as CoffeeScript that support syntactic abbreviations. If you want to use one tool to complete code cleaning and optimization after writing JavaScript, Gulp is your best choice. GulpJS is similar to Ant or Maven for Java. http://www.oschina.net/p/gulp

 Original text: javascript-explain-it-like-im-a-java-developer Translation: labazhou


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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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