JavaScript Particularities that Will Throw You Off - Part 1
Through the eyes of a Java dev
I recently started looking into JavaScript after having learned Java as my first programming language and oh boy... there are many weird things happening under the hood in JavaScript. This article will be a list of such oddities I notice while continuing to learn JavaScript. A continuation may follow in later blog posts.
Dynamic typisation
Javascript is unlike Java dynamically typed, there is therefore no need to declare an explicit type for methods and even for most data structures, from what I gather. There is also no need to declare the return type.
Automatic type conversion
Type conversion is not a new feature of programming languages, but JavaScript works again differently. While JS converts the integer 1 in the case of addition to a string data type, it does the completely opposite when substraction is involved - JS converts the string to an integer:
console.log("5" + 1);
// ->51
console.log("5" - 1);
// ->4
Using == or != also induce automatic type conversion:
console.log(null == undefined);
// -> true
console.log(0 == false);
// ->true
console.log("" == false);
// ->true
To be sure that no automatic type conversion happens, always use "===" and "!==":
console.log(null === undefined);
// -> false
console.log(0 === false);
// -> false
console.log("" == false);
// -> false
Logical operators and funny behavior
Logical operators such as "OR" ( || ) and "AND" ( && ) will only operate the part to their right when necessary:
console.log(null || "user")
// -> user
console.log("Caesar" || "user")
// -> Caesar
console.log("false && X")
// -> false
Pay therefore attention with JS ;).