A first look at JavaScript through the eyes of a Java developer
Java and JavaScript are not the same thing! Now you know the main secret of the Masons. In this article, I want to share with you thoughts and thoughts about the JavaScript language through the eyes of a Java developer. I will compare data structures, types, functions, objects, classes, and other common features of Java and JavaScript.
Foundation
JavaScript is an interpreted, scripting language for writing scripts. This means that the code you write will be executed line by line, from instruction to instruction, from script to script. Java is a compiled language, which means that before starting a Java program, the compiler must translate all the code you wrote into a special machine code that is understandable for the JVM - bytecode .
The disadvantages for a Java developer who started writing in JS related to these differences will be the following:
- Before starting compilation of your code written in Java, the compiler will conduct parsing and semantic analysis for you, and in case of problems, will notify you of this. It turns out that you have the opportunity to find out about the error before launching the application. In JS, due to the lack of a compiler, there is no such check. And the mistakes made by you at the time of writing the code will be detected only after the script is launched.
- The following inconvenience is only possible for JS versions prior to ES5. Because JavaScript is executed line by line style of writing functions that call other functions will differ from the principles of Bob's “uncle” Pure code , preached for writing programs in Java. In JS, if you need to call the bar () function from the foo () function , you must define bar () before foo () . If you do the opposite, as in Java - applications, then the call may fail in some older browsers.
// Пример на Java
public class JavaVsJS {
public static void foo(String name) {
bar(name);
}
private static void bar(String name) {
System.out.println(name);
}
public static void main(String[] args) {
JavaVsJS.foo("Igor Ivanovich");
}
}
// Пример на JavaScript
var name = "Igor Ivanovich";
// Функция bar() определена до своего вызова в foo()
function bar(name) {
document.write(name);
}
function foo(name) {
bar(name);
}
foo(name);
Variables and their types
JavaScript is a weakly typed language, unlike Java. On the one hand, it gives more flexibility, on the other - more opportunities to fire a shot in the leg. To declare a variable in JS, it is sufficient to use the var keyword , after which indicate the variable name and, if necessary, the value. In practice, it is not necessary to even use the var keyword .
var name_1 = "Igor Ivanovich";
name_2 = "Renat Raphaelevich";
Now about the types. In JS, there are no different types for integers and floating point numbers. They are combined in type number . String , boolean are the same as in Java. JS has an Object type . If in Java it is a superclass of all classes, then in JS it is just one of the types.
var a_number = 10; // number
var b_number = 10.01; // number
var a_string = "10"; // string
var b_string = "10.1"; // string
var tr = true; //boolean
var person = {name: "Igor", secondName: "Ivanovich"}; //object
The Java developer should not be confused. Now let's try to perform operations between objects of different types and see what happens.
10 +1
> 11
10 +"1"
> "101"
true && false
> false
true && 1
> 1
true && 0
> 0
true && "1"
> "1"
false && "1"
> false
false && 0
> false
0.1 + 0.7
> 0.7999999999999999
Some results may confuse the Java developer a bit. For example, the ability to use the boolean type in this way: true && 1 and at the same time get some kind of result. In Java, it is impossible to carry out such an operation because the compiler will give an error saying that you cannot use the && operator with types other than boolean . Now let's pay attention to another difference between JS and Java: the === and ! == operators . These are comparison operations needed by a weakly typed language such as JS. === - will return true if the compared objects are equal in value and their types coincide. ! ==, respectively, will return true if the compared objects are not equal in value or their types do not match. Let's look at a few examples:
10 == 10
> true
10 == "10"
> true
10 === "10"
> false
10 != "10"
> false
10 !== "10"
> true
10 !== 10
> false
Functions
In JS, as well as in Java, functions can return / not return a value, with or without arguments. You can call the function both in JS code, as shown in the example above, and by responding to a specific event on the html markup element.
//Описание функции foo()
function foo() {
document.write("Calling foo");
}
When you click on the button on the page, “Calling foo” will be printed as a result of calling the function. Now about the oddities that a Java developer might pay attention to. Let us return to the example above, where the function foo () calls the function bar () in itself - which is used only as an internal function. According to the idea, we expect that it can be made private. But there are no access selectors in JS. There is no way to make the private field a simple addition of this word before the function declaration. Let's go further. Let's create an object - an instance of a class with its fields and one method.
function getLocation() {
if (this.person === "Igor" && this.age > 25) {
document.write("Your name " + this.person + ", location = Vishnevaia 1");
} else {
document.write("Your name " + this.person + ", location = rp Sokoloviy");
}
}
function Person(person, age) {
this.person = person;
this.age = age;
this.getLocation = getLocation;
}
var igor = new Person("Igor", 26);
igor.getLocation();
document.write("
");
getLocation();
If you look at this code through the eyes of a Java developer, it can be noted that the Person function is a constructor of objects of the Person class and a definition of the fields and methods included in the class. The getLocation () function is a function of the Person class . Inside it, we use access to the fields of the instance class this.person and this.age . It is logical that this function using the current instance of the Person class should work only with it and the last call to the getLocation () functionshouldn't work. But, in JS this is normal, because the concepts of a class, function, class methods are blurred. Weak typing in everything. By executing this script you will receive the following output in the browser window:
Your name Igor, location = Vishnevaia 1
Your name undefined, location = rp Sokoloviy
However, rewriting the code as follows, defining a function inside the class, its call is not available for the class instance:
function Person(person, age) {
this.person = person;
this.age = age;
this.getLocation = function () {
if (this.person === "Igor" && this.age > 25) {
document.write("Your name " + this.person + ", location = Vishnevaia 1");
} else {
document.write("Your name " + this.person + ", location = rp Sokoloviy");
}
};
}
var igor = new Person("Igor", 26);
igor.getLocation();
document.write("
");
getLocation();
The last call will result in an error, because the getLocation () function is not defined. It turns out that even in JS there are no access modifiers, but there is a scope of functions and variables controlled with curly braces. JavaScript is wonderful with a huge number of options to shoot yourself in the foot.
Arrays
When we talk about arrays, we represent a data structure that stores the same type of elements, which are accessed by index. This is in Java. When it comes to JS and its weak typing, then real anarchy comes into play. In the following example, we create 4 arrays. In the first there are elements of different types, in the second only numbers, in the third boolean , in the fourth boolean and number :
var mix = [3, "Igor Ivanovich", "Renat Raphaelevich", "Sergey Sergeevich", 1, 12.3, true];
var numbers = [1,2,3,4,5];
var booleans = [false, false, true];
var mix2 = [false, 1, 2];
document.write("Type elements in mix: ");
for (element in mix) {
document.write(typeof mix[element] + " ");
}
document.write("
Type elements in numbers: ");
for (element in numbers) {
document.write(typeof numbers[element] + " ");
}
document.write("
Type elements in booleans: ");
for (element in booleans) {
document.write(typeof booleans[element] + " ");
}
document.write("
Type elements in mix2: ");
for (element in mix2) {
document.write(typeof mix2[element] + " ");
}
var sum = numbers[0] + numbers[1];
document.write("
sum numbers = " + sum);
After executing the script, we will see the type of each element of each array and the sum of the first two digits from the array of numbers.
Type elements in mix: number string string string number number boolean
Type elements in numbers: number number number number number
Type elements in booleans: boolean boolean boolean
Type elements in mix2: boolean number number
sum numbers = 12
Conclusion
When you first touch the JavaScript language, the Java developer may experience all of the above comments and questions. When I first met JS, I did not experience the most fun emotions. Rather, it was like this: "What the ...?" Many differences and misunderstandings lie in the difference between the typifications of two languages. I don’t know why JS needs weak typing.
Perhaps there are benefits why this was done. If you know the answer, write in the comments.
Yes, there is TypeScript, which seems to be typed, but in the end it will be translated into the same JS. Personally, I am not a supporter of weak typing, but my colleague, who recently tried JavaScript, was for some reason delighted with it. Perhaps this is a matter of taste. And what do you think is better than weak or strong typing?