Transitioning from Java to JavaScript — Quick guide on the basics you need to immediately know
I’ve always considered myself primarily as back-end or Java developer. Recently I’ve taken steps to up-skill, all in a mission to make myself a more-rounded engineer with full-stack experience. One of the new skills I wanted to learn was in front-end technologies, and as is widely known, the “language of the web” is JavaScript.
Coming from a Java 7 background (I’m old enough to remember when that was considered new…); I fooled myself into thinking that JavaScript and Java, with their similarities, would be easy to pick up without much preparatory learning. As you can guess, I was wrong. As it turns out though, I’m not the only one who thought this.
So for the help of other engineers transitioning from classical OO programming languages (like Java) to JavaScript that are in a similar path; I’ve assembled a quick guide on the basics you need to immediately know. This article talks about the basics of vanilla JavaScript and not into the advanced libraries/frameworks such as AngularJS or ReactJS.
On a stranger note: some of the benefits of JavaScript (but possibly not unique to JS) are being gradually introduced into Java (e.g. var
as local variable type in Java 10). If you are transitioning from a newer version of Java (8+), some of the concepts will be familiar.
JavaScript key points
As described on MDN:
JavaScript® (often shortened to JS) is a lightweight, interpreted, object-oriented language with first-class functions, and is best known as the scripting language for Web pages
The basic syntax is intentionally similar to both Java and C++ to reduce the number of new concepts required to learn the language
JavaScript can function as both a procedural and an object oriented language
JavaScript is a tolerant language; ideal for newcomers or those from typically “heavy” OO languages.
If there is one take-away from this article that you learn; it’s that JavaScript (the interpreter) makes assumptions about code execution.
Much of the language quirks I’ve seen are tied to this concept. Keep this concept in mind as you read through.
Runtime Environment
- In Java, the JVM is the runtime environment for applications. Java applications are compiled into Java bytecode and executed within the JVM.
- For JavaScript, the web browser is the runtime environment for client-side JavaScript and there is no obvious compilation step to be performed. Most web browsers. like Chrome and Firefox, have developer tools that allow the inspection and execution of JavaScript (? link to articles)
- Node.js is a server-side environment that is operates in a similar capacity to the JVM. If you feel you require more information on NodeJS, see this article on what exactly is node.js.
JavaScript vs ECMAScript
- There is no real difference. ECMAScript/ES is the specifications for a scripting language developed by Brendan Eich of Netscape (which became JavaScript). Effectively JavaScript is an implementation of ECMAScript. Other implementations include JScript and ActionScript. However, JavaScript and ECMAScript have been liberally used interchangeably.
- When developing in JavaScript, it is important to know the features that you can use with each browser/runtime environment. Much like enterprise adoption of the new Java release cadence, browser support for ES versions is lagging behind the current release. For more information, see the current browser support of ECMAScript.
Vanilla JavaScript vs. React/Angular/Ember/Backbone/Meteor/etc.JS
- Vanilla or Native Javascript is the programming language for adding dynamic behaviour to web pages (primarily by changing the DOM). However as requirements grew in complexity, so did the rise of application frameworks/libraries like jQuery, ReactJS, AngularJS, etc.. These frameworks/libraries are what is used to build rich and modern client-side applications. It is generally encouraged to have an understanding of JavaScript before learning these frameworks/libraries.
Printouts
- Every Hello World application starts with detailing the method of printing information, usually with an implicit imported object that has the ability to print. In Java, this is
System.out.println("string");
. In JavaScript, this isconsole.log("string");
.
Variable declaration and definition
- Variables are declared and defined (Java’s “instantiation”) with mostly similar syntax. Java is a statically-typed language in which every value-type has to be defined at compile-time. JavaScript is dynamically-typed and does not require type constraints.
var myNum = 42;
myNum = "forty-two";
- Variables are declared using the keyword type
var
. In ECMAScript2015/ES6, two more types were also added:let
andconst
. The differences betweenlet
,const
andvar
are to do with variable scope, and thatconst
allows for immutable primitives.
Variable scope
var
is function scoped. It is available inside the function and it’s nested blocks (e.g. any flow control block likeif
orfor
) and nested functions. Java doesn’t have the concept of nested methods (excepting the idea of using Lambda’s introduced in Java 8). It can be considered similar to Java as if you were to declare the variable at the top of a function.
public void doSomething() {
String sameAsJsVar = "undefined";
if(true) {
System.out.println(sameAsJsVar); // undefined
}
}
let
is block scoped instead of function scoped.let
is the most comparable variable declaration keyword to Java’s local variable scope. It still allows access in nested blocks, but if declared in a nested block
let a = 1;
if(true) {
let b = 2;
}
console.log(a); // 1
console.log(b); // ReferenceError: b is not defined
const
has the same scope aslet
, however the difference would be if you added Java’sfinal
keyword before the variable (thus making it immutable).- For more information on JavaScript variable declarative keywords, their quirks and what should you use by default (spoiler alert: it’s
const
), see this article on var, let, const, and when to use them.
Access Modifiers
- There are no access modifiers in JavaScript, unlike Java (e.g.
public
private
protected
and the default/package-private). For the most part, everything is accessible. - There is design patterns using Closures that can employed to provide the equivalent to private/public data, such as the Module pattern. If you require more information, see this article for the basics and a code example.
Primitive Types in JavaScript
- Number — equivalent to
double
in Java - String — no such thing as a
char
- Boolean — no explanation needed!
- Symbol — ES6 addition; Here is an in-depth article into it’s use.
- Undefined
- Null
Null and Undefined
- Undefined and null are similar to Java’s
null
. In JavaScriptundefined
acts as Java’snull
equivalent of default value implicit assignment when a variable is declared but not instantiated (or “defined” in JavaScript terms)
// JAVA
public class Main {
static String fieldVar;
public static void main(String[] args) {
System.out.println(fieldVar); // null
}// JAVASCRIPT
let jsVar;
console.log(jsVar); // undefined
- Null is a separate value type, similar to
undefined
. However, this is not implicitly assigned as it is in Java and is explicitly assigned. Also to note; thattypeof null
actually returns anObject
type rather thannull
!
JavaScript Type Coercion
- The JavaScript interpreter makes a best guess when it comes to type coercion, and follows some of the same rules as Java. e.g.
// JAVA
public static void main(String[] args) {
String a = "123";
int b = 45;
System.out.println((a + b).getClass().getName() + (a + b));
// java.lang.String12345}// JAVASCRIPT
let a = "123";
let b = 45;
let c = a + b;
console.log(typeof c + c); // string12345
- As JavaScript has an interpreter that makes assumptions, there are further type coercions. Values have an implicitly associated Boolean value depending on a certain sensible value. In Java, the
if
block needs a boolean check where the value included must return a clearboolean
value. In JavaScript, type coercion means that the variable can be tested directly. For example;
// NUMBER BOOLEAN COERCION
let a = 0;
let b = 1;
console.log(a ? "a is true" : "a is false"); // false
console.log(b ? "b is true" : "b is false"); // true// STRING BOOLEAN COERCION
var a = "";
var b = "string";
console.log(a ? "a is true" : "a is false"); // false
console.log(b ? "b is true" : "b is false"); // true
- JavaScript has a form of Java’s autoboxing, where it automatically wraps primitive as objects when they are accessed as objects, for the duration of the access. However, they return to their primitive type afterwards, so you cannot assign properties or do other typical object assignments.
let myString = "Hello";
console.log(myString.length); // 5
console.log(typeof myString); // string
myString.someProp = true;
console.log(myString.someProp); // undefined
- If you require more, see this article for more information on the weird and wonderful of JavaScript’s type conversion
Equality operator
- JavaScript has two types of equality operators.
==
compares type and value (performing automatic type coercion before the equals check)===
compares only the type . It is generally safer coming from Java to use the===
operator as your default, unless there is a specific requirement not to.
let num = 10;
let numStr = "10";
num == numStr ? console.log(true) : console.log(false) // true
num === numStr ? console.log(true) : console.log(false) // false
- Be aware that while property values that are primitive types are easy for comparison, direct object comparison in JavaScript isn’t as straight-forward as JavaScript objects, unless pointing at the same memory reference, aren’t equal. See this StackOverflow post for more information on methods for determining object equality.
// OBJECT BY REFERENCE
var obj1 = {"name": "myObj"};
var obj2 = obj1;
obj1 == obj2 ? console.log(true) : console.log(false) // true
obj1 === obj2 ? console.log(true) : console.log(false) // true// OBJECT BY VALUE
var obj1 = {"name": "myObj"};
var obj2 = {"name": "myObj"};
obj1 == obj2 ? console.log(true) : console.log(false) // false
obj1 === obj2 ? console.log(true) : console.log(false) // false
Objects — Declaration and Definition
- Vanilla JavaScript is object-orientated, but it is classless. JavaScript objects do not follow Java’s class/object conventions. JavaScript does have a concept of classes (as of ES5) but these are different to Java classes and are essentially “special functions”
- Objects in JavaScript use the JSON format for notation. The JSON data structure is crucial to understand to use JavaScript effectively.
let myObj = {};
is an example of the minimum requirements to declare an object (empty).let person = { "name":"Greg"};
is an example of a Person object with the property of name. - Objects can contain variables, functions, and other objects. These can be declared and defined by assigning the value to a variable on the object.
// ADDING A PROPERTY
let person = {"name":"Greg"};
person.surname = "Byrne"
console.log(person.name + " " + person.surname); // Greg Byrne// ADDING A JS FUNCTION
person.dance = function() {
console.log(this.name + " is dancing");
}
person.dance(); // Greg is dancing// ADDING A NESTED OBJECT
let person2 = {
"name":"Gregg",
"characteristics": {
"relation": "evil twin"
}
}
console.log(person2.characteristics);
// object {"relation":"evil twin"}
- Java has a compile-time feature to ensure that accessible Object properties exist. JavaScript can access non-existent properties at runtime as they will be declared, but they will be defined with the implicit value type of
undefined
// JAVA
class Person {
String name = "Greg";
}
class Main {
public static void main(String[] args) {
Person person = new Person();
System.out.println(person.name); // Greg
System.out.println(person.surname);
// Error: surname cannot be resolved or is not a field
}
}// JAVASCRIPT
let person = {"name":"Greg"};
console.log(person.surname); // undefined
Objects — Accessing Properties
- JavaScript and Java both use the dot notation to access values or functions on Objects (e.g.
person.name
). JavaScript can also access properties using the square brackets. The dot notation should be used by default as convention, but square bracket access is useful when accessing properties that:
- Use syntax that use reserved notation
- Use syntax that are not applicable as variable names (like numbers)
- Use a mutable variable name (i.e. a variable name that constantly changes)
let caseFile = {
"case.subject": "Stolen Gnomes"
};console.log(caseFile.case.subject);
// TypeError: Cannot read property 'subject' of undefinedconsole.log(caseFile["case.subject"]); // Stolen Gnomes
- Objects can self reference properties using the
this
keyword similar to Java. Functions are described further down.
let caseFile = {
"caseName": "Stolen Gnomes",
"investigator": "Sherlock Gnomes",
"getCaseDetails": function() {
return this.caseName + " - Investigator: " + this.investigator;
}
}console.log(caseFile.getCaseDetails);
// Stolen Gnomes - Investigator: Sherlock Gnomes
Arrays
- Arrays are operate similarly in JavaScript to Java. Their simple instantiation differs slightly:
// JAVA
int[] javaArr = {1,2,3};
System.out.println(javaArr.length); // 3// JAVASCRIPT
let myArray = [1,2,3];
console.log(myArray.length); // 3
- In JavaScript, Arrays are also Objects and are mutable like other JavaScript objects.
let myArray = [1,2,3];
console.log(typeof myArray); // objectmyArray.arrayType = "number";
console.log(myArray.arrayType); // number
console.log(myArray[4]) // undefined
- Arrays also have implicit functions available. See the MDN JavaScript Array reference guide for more information
myArray.push(4);
console.log(myArray); // [ 1, 2, 3, 4 ]myArray.pop();
console.log(myArray); // [ 1, 2, 3]myArray.shift();
console.log(myArray); // [ 2, 3 ]myArray.unshift(5);
console.log(myArray); // [ 5, 2, 3 ]var print = function printElement(element) {
console.log(element);
}
myArray.forEach(print);
// 5
// 2
// 3
Functions
- Functions are comparable to Java methods. However, JavaScript treats functions differently to those in Java. They do not need to be assigned to classes (as JavaScript does not use the typical class concept), the interpreter will try to make assumptions about function contracts, and functions can be treated as values.
- You don’t need to supply a type value to function parameters in it’s contract.
function add(a, b) {
console.log(a + b);
}
add(1, 2); // 3
add("1", "2"); // 12
- JavaScript interpreter makes assumptions and allows for flexible arguments. Similar to how non-existent object properties are automatically declared, JavaScript will declare any arguments that don’t exist. This means that JavaScript does not have Java’s concept of overloading methods.
function hello(firstName, lastName) {
console.log("Hello " + firstName + " " + lastName);
}
hello("Greg", "Byrne"); // Hello Greg Byrne
hello("Greg"); // Hello Greg undefined
hello("Evil", "Greg", "Byrne"); // Hello Evil Gregfunction returnNothing() {
return;
}
console.log(returnNothing()); // undefined
- Functions can be treated like values. This means that functions can be assigned to a variable and passed to arguments of functions. The function isn’t executed where it is defined, but can be called using the function parentheses
()
on the variable. Where a variable does not have an assigned function but is called using the function parentheses, an error will occur.
// FUNCTION AS VARIABLE
let func = function myFn() {
console.log("function is executed");
};
func(); // function is executed// ANONYMOUS FUNCTION AS VARIABLE
let anonymousFunction = function() {
console.log("anonymous function is executed");
};
anonymousFunction(); // anonymous function is executed// EXECUTING A VAR WHICH IS NOT A FUNCTION
let notFunction= 1;
notFunction(); // TypeError: notFunction is not a function// FUNCTION AS ARG TO ANOTHER FUNCTION
let print = function(messageFn) {
console.log(messageFn());
}print(function() {return "Passing function directly"});
// Passing function directlylet getMessage = function() {
return "Passing function by variable"
}
print(getMessage); // Passing function by variableprint("hi"); // TypeError: messageFn is not a function
- As functions can be treated like variables, Objects can be assigned variables that are functions. Assigning variables that are functions to objects gives JavaScript objects the equivalent of methods on a Java class object.
let object = {};
object.printHi = function() {
console.log("Hi there!");
}
object.printHi(); // Hi there!
- Functions have an implicit default argument called
arguments
. This is an object that contains every argument that was passed to the function (not the parameters of the function).
function listPassedArgs() {
console.log(arguments);
}
listPassedArgs(1, 2, 3); // { '0': 1, '1': 2, '2': 3 }
- Functions can be written using Arrow functions (with improved syntax in ES6). This is a common way in which JavaScript functions are created today, but they mostly serve as a short-hand way to write functions as we’ve described. Arrow functions do have additional quirks such as not having a
this
orargument
. For more information see this article on Function expressions and arrows.
// NO ARG, SINGLE EXECUTABLE LINE
let hi = () => console.log("Hi");
hi(); // Hi// ARG, SINGLE EXECUTABLE LINE
let hiToName = (name) => console.log("Hi " + name);
hiToName("Greg"); // Hi Greg// ARGS, MULT-LINE EXECUTION
let hiToFullName = (name, surname) => {
let fullName = name + " " + surname;
console.log("Hi " + fullName);
}
hiToFullName("Greg", "Byrne"); // Hi Greg Byrne
In-built Objects
- JavaScript has a number of built-in objects (like Array) such as Date and Math, more than any one article can give detailed information on. It is good to be aware that these exist. See the MDN Standard built-in objects reference guide for more information.
Conclusion
This article, as outlined, only describes a collection of the basics of JavaScript; these are the concepts you immediately need to know to be progress in any effective way from a language such as Java.
There is much more to learn in more advanced topics like Closures, Prototyping, Asynchronous, and newer ECMA features, which I hope to document in the future. Until then, the above knowledge is enough to get you started, and if you can’t wait, you can always look up other articles that explore the content more deeply.
I would also recommend checking out Koushik Kothagel’s JavaScript for Developers YouTube playlist course to see video tutorials on some of the info above.
If you liked this article, please share your like with a friendly clap.
If you didn’t like this article and would like to register your resentment, you can do so by giving a hateful clap
The opinions expressed in this publication are those of the author. They do not purport to reflect the opinions or views of any organisation or business that the author may be connected to.