Skip to content
jshacks.dev
Fundamentals

JavaScript for Java Developers a Practical Comparison

A guide for Java developers learning JavaScript: dynamic types, no overloading, prototype classes, equality, Map keys and the event loop. With output.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Node.js, npm and TypeScript logos.

A Java developer opening a JavaScript file sees familiar braces, classes, new, try and catch, and this, and could be forgiven for assuming the languages are close relatives. The names are the only thing they share: the similarity was a marketing decision in 1995, and the two languages work very differently underneath. Java is statically typed, class-based, compiled to bytecode and concurrent through threads. JavaScript is dynamically typed, prototype-based, run directly by an engine and concurrent through an event loop with promises. The code looks alike until it does something unexpected, and every unexpected result in the first weeks has the same root: an assumption carried over from Java. This post goes through the differences that matter most, with the output of each snippet, and ends with a short list of habits to build. The JavaScript runs on Node.js 24, and the Java is Java 21, with outputs written from the language rules.

The vocabulary map

JavaJavaScriptNotes
int, long, doublenumber, bigintOne 64-bit floating-point number type
StringstringImmutable, UTF-16, with template literals
ArrayList<T>ArrayNo type parameter, mixed contents
HashMap<K, V>Map, or ObjectMap for non-string keys
HashSet<T>Set
nullnull and undefinedTwo values
interfaceNoneObjects are matched by shape, called duck typing
finalconstFixes the binding, not the value
private#fieldPrivate fields in classes
Optional<T>?. and ??Operators in the language
Thread, ExecutorServicePromise, async, await, workersOne main thread

Types are on the values

java
int count = 5;
count = "five"; // compile error: incompatible types
JavaScript
let count = 5;
count = "five";

console.log(typeof count, count);
console.log(typeof null, typeof undefined, typeof [], typeof (() => {}));
Text
string five
object undefined object function

A variable has no type in JavaScript: the value does, and the variable can hold any value at any time. Nothing checks this before the program runs, so a typo or a wrong argument is found when the line executes. TypeScript adds a static checker on top of the same language, and most teams that come from Java adopt it for exactly this reason. Note the oddities in the second line: typeof null is "object", a mistake from the first version that cannot be fixed without breaking the web, and arrays report "object", so use Array.isArray().

No overloading

Java picks a method by the number and types of its parameters. JavaScript has one function per name, and extra or missing arguments are not errors.

JavaScript
function describe(a, b) {
  return `a=${a} b=${b} count=${arguments.length}`;
}

function describe(a) {
  return `only a=${a}`;
}

console.log(describe(1));
console.log(describe(1, 2));

function area(width, height = width) {
  return width * height;
}

console.log(area(3), area(3, 4));
Text
only a=1
only a=1
9 12

The second declaration replaced the first, since a function declaration with the same name in the same scope just redefines it, and the call with two arguments simply ignored the second. A missing argument is undefined. To get overload-like behavior, use default parameter values, as area does, or check the arguments and branch, or accept an options object. Passing an object of named options is the common replacement for a long parameter list or a builder.

Numbers and integer division

java
System.out.println(7 / 2);          // 3
System.out.println(7 / 2.0);        // 3.5
System.out.println(Integer.MAX_VALUE + 1); // -2147483648
JavaScript
console.log(7 / 2, Math.trunc(7 / 2));
console.log(2 ** 31 + 1, Number.MAX_SAFE_INTEGER + 2);
console.log(0.1 + 0.2 === 0.3, Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON);
console.log(10n ** 20n, 7 % 3, -7 % 3);
Text
3.5 3
2147483649 9007199254740992
false true
100000000000000000000n 1 -1

Dividing two integers in Java gives an integer, and in JavaScript every division gives a float, so use Math.trunc() for the whole part. There is no overflow to a negative number: JavaScript numbers are doubles, which lose precision above 2 to the power 53 instead of wrapping. For exact integers beyond that, use BigInt with the n suffix. For money, keep integer cents, as in Java you would reach for BigDecimal.

Equality

java
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b);       // false
System.out.println(a.equals(b));  // true
JavaScript
const a = "hi";
const b = "hi";
const c = new String("hi");

console.log(a === b, a === c, a == c);

const first = { id: 1 };
const second = { id: 1 };
console.log(first === second, JSON.stringify(first) === JSON.stringify(second));
Text
true false true
false true

Strings are primitives in JavaScript and === compares their contents, so there is no equals() for strings. Objects, arrays and functions are compared by identity, like Java's == on references, and there is no equals() or hashCode() method that the language calls. Use === for everything and avoid ==, which converts types. To compare objects by content, write a function or use isDeepStrictEqual from node:util.

Classes without interfaces

JavaScript has a class keyword, and underneath, classes are functions with prototypes. There is no interface type: an object satisfies a contract if it has the right properties.

JavaScript
class Shape {
  #name;
  static count = 0;

  constructor(name) {
    this.#name = name;
    Shape.count += 1;
  }

  get label() {
    return `shape:${this.#name}`;
  }

  area() {
    throw new Error("not implemented");
  }
}

class Square extends Shape {
  constructor(side) {
    super("square");
    this.side = side;
  }

  area() {
    return this.side ** 2;
  }
}

const shapes = [new Square(2), { area: () => 10, label: "duck" }];

for (const shape of shapes) {
  console.log(shape.label, shape.area(), shape instanceof Shape);
}

console.log(Shape.count, typeof Shape);
Text
shape:square 4 true
duck 10 false
1 function

The #name field is truly private, enforced by the language, and static works as in Java. The object literal in the array has no relation to Shape and works anywhere an object with area() and label is expected, which is duck typing and replaces the role of interfaces. A class is a function, so typeof Shape is "function". There is no method overloading, no protected keyword and no abstract classes, though a method that throws, as area does in the base class, is the usual way to mark one as required.

Collections and keys

java
Map<Point, String> map = new HashMap<>();
map.put(new Point(1, 2), "found");
System.out.println(map.get(new Point(1, 2))); // "found" if Point defines equals and hashCode
JavaScript
const map = new Map();
const key = { x: 1, y: 2 };

map.set(key, "found");
console.log(map.get(key));
console.log(map.get({ x: 1, y: 2 }));
console.log(map.get(`${1},${2}`));

map.set("1,2", "by string");
console.log(map.get(`${1},${2}`), map.size);
Text
found
undefined
undefined
by string 2

A Map compares keys by identity for objects, so a new object with the same fields is a different key, and no equals() is consulted. To key by value, build a string or number key, such as "1,2", as the last lines do. Arrays are not fixed-size or typed, so [1, "two", { three: 3 }] is legal, and generics do not exist at run time. Array methods replace streams: map, filter, reduce, find, some, every and flatMap all work on the array directly, and they are eager unless you use the iterator helpers.

null, undefined and optional values

JavaScript
const user = { profile: { email: null }, name: "Ada" };

console.log(user.profile?.email ?? "no email");
console.log(user.settings?.theme ?? "default");
console.log(user.missing, user.profile.email);

function greet(name) {
  return `Hello ${name ?? "stranger"}`;
}

console.log(greet(), greet(null), greet(""));
Text
no email
default
undefined null
Hello stranger Hello stranger Hello 

Reading a missing property gives undefined and not an exception, and null is a separate value that code assigns on purpose. The optional chaining operator ?. stops at a missing link, and ?? supplies a default when the left side is null or undefined, but not for an empty string, as greet("") shows. These two operators do what Optional does in Java, without wrapping the value.

Exceptions

JavaScript
function risky(kind) {
  if (kind === "type") throw new TypeError("bad type");
  if (kind === "plain") throw "just a string";
  return "fine";
}

for (const kind of ["ok", "type", "plain"]) {
  try {
    console.log(risky(kind));
  } catch (error) {
    console.log(error instanceof Error ? error.name : typeof error);
  } finally {
    console.log("cleanup for", kind);
  }
}
Text
fine
cleanup for ok
TypeError
cleanup for type
string
cleanup for plain

There are no checked exceptions: nothing forces a caller to handle or declare an error. A function can throw any value, so always throw Error objects, which carry a stack trace. There is a single catch with no type filter, and you test the error with instanceof inside it. Resource cleanup uses finally, or the newer using declaration, which plays the role of try-with-resources.

Concurrency: an event loop, not threads

java
ExecutorService pool = Executors.newFixedThreadPool(2);
Future<String> result = pool.submit(() -> "done");
System.out.println(result.get());
JavaScript
async function work() {
  await new Promise((resolve) => setTimeout(resolve, 5));
  return "done";
}

const result = work();
console.log("work started, not finished");
console.log(await result);

console.log(await Promise.all([work(), work()]));
Text
work started, not finished
done
[ 'done', 'done' ]

JavaScript runs your code on one thread, so there are no data races on ordinary variables and no synchronized. Waiting for I/O does not block: the work is handed to the runtime, and a promise reports the result later. Promise.all plays the role of invoking several tasks and waiting for all, as covered in the promises interview question. CPU-heavy work blocks the single thread, and needs a worker thread, which communicates through messages and does not share variables.

Modules and tooling

Java organizes code in packages and builds it with Maven or Gradle. JavaScript organizes it in files that import each other, as in the modules question, and uses npm with a package.json file for dependencies, which are installed into a node_modules folder. There is no compile step required for plain JavaScript, though most projects add a bundler, a test runner and a linter. A static checker, TypeScript, or type annotations in JSDoc comments, are the usual answer to the loss of compile-time types.

Habits to build

Use const by default. Use ===. Prefer arrow functions for callbacks, and know that this is set by the call, not by the class. Use Map and Set. Throw Error objects. Run a linter and a type checker. Write tests early, since the compiler will not catch a wrong argument. Learn the array methods well, because they are the language's collection library. And treat async code as the default for anything that waits.

Where the Java comparison stops

The deeper differences are in the object model, with prototypes and dynamic properties instead of fixed class layouts, in the absence of method dispatch on types, and in the ecosystem, where a single project often depends on hundreds of small packages. Java's reflection and annotations have no direct equivalent, and decorators in JavaScript work differently. The reference is in the MDN JavaScript guide and the Java language specification.

Taggedjava
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.