Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Use === Comparison

The == operator performs type conversion before comparing values, while the === operator compares both the value and the type without any type conversion.

Example

0 == “”;        // true
1 == “1”;       // true
1 == true;      // true

0 === “”;       // false
1 === “1”;      // false
1 === true;     // false

Use Parameter Defaults

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.

Example

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*/ }

End Your Switches with Defaults

Always include a default case in your switch statements, even if you believe it isn’t necessary.

Example

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”;
}

Avoid Number, String, and Boolean as Objects

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.

Example

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:

Example

let x = new String(“John”);             
let y = new String(“John”);
(x == y) // is false because you cannot compare objects.

Avoid Using eval()

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.