Check if – Javascript

Hi, in this post we are going to see the result of some comparisons when we use an “If & else”

Checking empty string

const name = ""; // "" is Falsy or "cristina" is Truthy

if (name) {
  console.log("enter if --> true");
} else {
  console.log("enter else ---> false");
}

Result:

Checking null value

const name = null; // null is Falsy

if (name) {
  console.log("enter if --> true");
} else {
  console.log("enter else ---> false");
}

Result:

Or we can do this:

const name = null; // null is Falsy

if (!name) { // if null is falsy
  console.log("enter if --> true");
}

Result:

Checking undefined

const name = undefined; // undefined is Falsy

if (name) {
  console.log("enter if --> true");
} else {
  console.log("enter else ---> false");
}

Result:

The undefined is a variable that has been declared but not assigned a value

let name; // name  is undefined because undefined is a variable that has been declared but not assigned a value

if (name === undefined) {
  console.log("enter if --> true");
}

if (typeof name === "undefined") {
  console.log("enter if --> true");
}

Result:

Note: Don’t be confuse null is an object but the type of undefined is undefined.

We can evaluate if is false or true

// evaluates to false because name === undefined
let name; // name is undefined

if (name) { // undefined is true? 
  console.log("enter if --> true");
} 

We can do this:

let name; // name is undefined and udefined is falsy

if (!name) { // if name is falsy
  console.log("enter if --> true");
}

Result:

By Cristina Rojas.