Confusing Thing In JavaScript

The most popular reason for calling Javascript confusing is its implicit typecasting [changing data type of variables by itself] and its asynchronous nature. Here is discus some JavaScript confusing things.

1. Truthy and falsy

The following values are always falsy:

  • false
  • 0 (zero)
  • ‘’ or “”(empty string)
  • null
  • undefined
  • NaN

Everything else is truthy:

  • ‘0’ (a string containing a single zero)
  • “false” (a string containing the text “false”)
  • [] (an empty array)
  • {} (an empty object)
  • function() {} (an “empty” function)

2. Double equal vs triple equal

3. Scope

  • Local scope
  • Global scope

JavaScript has function scope. Each function creates a new scope. Variables declared within a JavaScript function, become local to the function. Local variables have function scope, they can only be accessed from within the function. A variable declared outside a function, becomes global.

4. Hoisting

x = 5; // Assign 5 to x
var x; // Declare x

Using a let variable before it is declared will give a Reference error. Using a const variable before it is declared, is a syntax errror. Because variables defined with let and const are hoisted to the top of the block, but not Initialized.

5. “this” keyword

  • “this” always refers to an object.
  • “this” refers to an object which calls the function it contains.
  • In the global context “this” refers to window object.

In an object method, “this” refers to the “owner” of the method.

6. Call, bind, apply.

7. Closure

8 . “new” keyword

9. Callback function

10. Recursion