JavaScript as seen from Java

When SE, who has only touched Java, touched JavaScript for the first time I couldn't implement it as I expected, so I made a note.

Where confused

  1. Type inference
  2. How to write a function
  3. Processing order
  4. Callback

1. Type inference

You can declare a variable with "var". Variables can contain ** functions ** as well as values.

2. How to write a function

When writing a method in Java, write it outside the class or method and call it. In JavaScript, there are other ways to write it.

Anonymous function

Define a function and put it in a variable. There is no function name, and when calling it, call it by variable name.

sample01.js


//Function definition & variable declaration
var hoge = function(counts) {
    //processing
};

//Function call
hoge(i);

Immediate function

The method version of the inner class if expressed in Java. It is defined and called as it is.

sample02.js


//Function definition & function call
(
    function(counts) {
        //processing
    }
)(i);

3. Processing order

Java executes processes and method calls in order from the top, In JavaScript, even if you call a function, it may be executed after other processing is completed, and it did not behave like Java.

JavaScript is single thread

I saw in various articles that JavaScript is asynchronous, so Like Java's asynchronous processing, I was seriously burned when I thought "multi-threaded parallel processing!"

(Reference) Did you mistake JavaScript asynchronous processing for parallel processing?

JavaScript execution unit is a function

I thought, "If it's multithreaded, it can't be helped if the called function is executed at an unintended timing." I was even more confused when I realized that it wasn't multithreaded in the first place. Given that JavaScript is single-threaded, After all, it is strange that the processing inside the function is not executed the moment the function is called, why? If you think that you call the function It seems that the processing in the function is not executed but is registered in the execution queue.

sample03.js


//Caller function
function A() {
    console.log('aaa');
    B();
    console.log('ccc');
};

//Function to be called
function B() {
    console.log('bbb');
};

If there is a function like the above and function A is called, the processing order is as follows in Java. It executes the processing in the order described and calls the function. A.1 Start function A execution A.2 "aaa" output A.3 Call function B B.1 Function B start execution B.2 "bbb" output B.3 Function B end of execution A.4 "ccc" output A.5 Function A end of execution

However, in the case of JavaScript, the processing order is as follows. A.1 Start function A execution A.2 "aaa" output ** A.3 Register function B to execution queue ** A.4 "ccc" output A.5 Function A end of execution B.1 Function B start execution B.2 "bbb" output B.3 Function B end of execution

In JavaScript, the processing of function B is not executed during the processing of function A. It doesn't work as I expected to write it like Java. It is necessary to describe the source with the execution queue in mind. If you know this difference, it will work as you want, but this time I don't know how to handle the return value. How can I receive the return value of the method and continue processing?

4. Callback

In JavaScript, processing is executed in function units For example, what if you want to continue processing using the return value of the called function? The first thing that came to my mind was to stop calling the function and write all the processing in one function. In this case, you can do as described in the processing order without being aware of the execution queue! I couldn't read it. At this point, we finally reach the significance of callbacks.

Callback function

I see it a lot, but I didn't understand the significance of its existence. I understood that JavaScript is a single thread and the processing unit is a function, and I found the significance of existence. By using the callback function, the processing after calling the function can be described. I felt that executing the function put in the argument in the function is very different from java. If you describe all the processing you want to do after calling the function in the callback function, It will execute the processing in the order described! Finally, we have reached the stage where we can implement it with JavaScript at will.

sample04.js


//Define function A (register the argument function in the execution queue after outputting "aaa")
var A = function(callback) {
    console.log('aaa');
    callback()
};

//Define function B
var B = function(callback) {
    console.log('bbb');
    callback()
};

//Define function C
var C = function() {
    console.log('ccc');
};

//Caller function
function call() {
    A(
        B(
            C()
        )
    )
};

The processing order is as follows, which is the same as Java. I didn't want to try to do something after registering function B in the execution queue in function A. All the processing after the function call is described in the called function or in the callback function of the called function. A.1 Start function A execution ** A.2 "aaa" output ** A.3 Register function B in the execution queue A.4 End of function A execution B.1 Function B start execution ** B.2 "bbb" output ** B.3 Register function C in the execution queue B.4 Function B end of execution C.1 Function C start execution ** C.2 "ccc" output ** C.3 Function C end of execution

The callback function can also be used to perform the following processing using the return value of the function. The ability to pass a function as an argument is very different from Java.

Then, he meets the callback hell.

Promise function

Callback hell is now an old story and can be avoided with the Promise function. Hell is gone with Promise.then (), and you can easily control the process depending on the result of the called function. In particular, Promise.all () registers the function in the execution queue after the processing of the passed Promise function is completed. You can also control the processing order by calling a function in a loop.

(Reference) Try to organize JavaScript synchronous, asynchronous, callback, promise area

Summary

Although type inference and how to write functions are not in Java, they were relatively easy to understand, The processing order seems to be natural even from the viewpoint of JavaScript or a general program language. There was little information to explain. It seems to be a matter of course ………… As a person who only knows Java, it was a culture shock.

Recommended Posts

JavaScript as seen from Java
Note: Differences from Java as seen from C #
The road from JavaScript to Java
Call Java method from JavaScript executed in Java
Using JavaScript from Java in Rhino 2021 version
Java and JavaScript
Call Java from JRuby
Changes from Java 8 to Java 11
Sum from Java_1 to 100
Eval Java source from Java
Access API.AI from Java
From Java to Ruby !!
Migration from Cobol to JAVA
Try calling JavaScript in Java
Java starting from beginner, override
Creating ElasticSearch index from Java
New features from Java7 to Java8
Connect from Java to PostgreSQL
Save Java HTML as PDF
Java, instance starting from beginner
Java life starting from scratch
Using Docker from Java Gradle
From Ineffective Java to Effective Java
Execute non-Java instructions from Java
Call Kotlin's sealed class from Java
Java, abstract classes starting from beginners
Code Java from Emacs with Eclim
Deep Learning Java from scratch 6.4 Regularization
Java, JavaScript, C # (difference in assignment)
Delegate some Java processing to JavaScript
Run node.js from android java (processing)
[Java] December 28, 2020 will be formatted as December 28, 2021?
Avoid Java Calendar as much as possible
[Java] Remove whitespace from character strings
Akka hands-on preparation procedure from Java
Access Teradata from a Java application
Note 1: Elementary, stumbling blocks (java, javascript)
Use Chrome Headless from Selenium / Java
From Java to VB.NET-Writing Contrast Memo-
Java overload constructor starting from beginner
Work with Google Sheets from Java
Java, interface to start from beginner
About Eclipse environment (Java, Liberty, JavaScript)
Reintroducing Java 8 available from Android Studio 2.4
Call TensorFlow Java API from Scala
[Java] Conversion from array to List
Sample code using Minio from Java
JSON in Java and Jackson Part ③ Embed JSON in HTML and use it from JavaScript