java script tricky things

Zihadul Islam
2 min readMay 8, 2021

Truthy and Falsy Values

Falsy Values

Falsy values are values that JavaScript’s built-in type coercion converts to false or in a Boolean context are considered false. In simple terms we could say, variables that do not have values or do not exist but it’s more than that. Below are a list of all falsy values

  • false
  • 0 Both positive and negative
  • 0n BigInt, when used as a boolean, follows the same rule as a Number
  • ‘’
  • null
  • undefined
  • NaN

Truthy Values

Anything aside from what’s mentioned above is truthy. Simply any variable with a value is truthy.

Below are some truthy values

  • true
  • {} An object (whether empty or not)
  • [] An array (whether empty or not)
  • 25 Numbers (whether positive or negative)
  • ‘true’ Non empty strings
  • ‘false’ Non empty strings
  • new Date() Date object
  • 12n BigInt, when used as a boolean, follows the same rule as a Number
  • Infinity

When should you use == and when should you use ===

When in doubt, use ===. This will save you from a ton of potential bugs.

If you are supporting a use case where you can be a little lenient about the type of incoming data, then use ==. For example, if an API accepts both “true” and true from the client, use ==. In short, do not use == unless you have a strong use case for it.

Null and Undefined

Null is used to represent an intentional absence of value. It represents a variable whose value is Null.

Example: var name = null;

Undefined is used to represent an Unintentional absence of value.It represents a variable whose value is undefined.

Example: var name ;

Scope:

Global scope: There’s only one Global scope in the JavaScript document. The area outside all the functions is considered the global scope and the variables defined inside the global scope can be accessed and altered in any other scopes.

Local Scope: Variables declared inside the functions become Local to the function.

Block Scope: A block scope is the area within if, switch conditions or for and while loops. Generally speaking, whenever you see {curly brackets}, it is a block.

Closure:

A closure gives you access to an outer function’s scope from an inner function

--

--