The == operator performs type conversion before comparing values, while the === operator compares both the value and the type without any type conversion.
0 == “”; // true 1 == “1”; // true 1 == true; // true 0 === “”; // false 1 === “1”; // false 1 === true; // false |
If a function is called with a missing argument, the argument is assigned the value undefined
.
Undefined values can cause issues in your code, so it’s a good practice to assign default values to arguments.
function myFunction(x, y) { if (y === undefined) { y = 0; } } |
ECMAScript 2015 (ES6) introduced the ability to define default parameters in function declarations.
function (a=1, b=1) { /*function code*/ } |
Always include a default case in your switch statements, even if you believe it isn’t necessary.
switch (new Date().getDay()) { case 0: day = “Sunday”; break; case 1: day = “Monday”; break; case 2: day = “Tuesday”; break; case 3: day = “Wednesday”; break; case 4: day = “Thursday”; break; case 5: day = “Friday”; break; case 6: day = “Saturday”; break; default: day = “Unknown”; } |
Always treat numbers, strings, and booleans as primitive values, not objects.
Declaring them as objects can slow down execution and lead to unintended side effects.
let x = “John”; let y = new String(“John”); (x === y) // is false because x is a string and y is an object. |
Or even worse:
let x = new String(“John”); let y = new String(“John”); (x == y) // is false because you cannot compare objects. |
The eval() function executes text as code, but it should generally be avoided.
Since it allows arbitrary code execution, it poses a significant security risk.