Important concepts in Javascript

Scope

Scope is a certain region of a program where a defined variable exists & can be accessed. Different types of scope are -> function scope and block scope. var is function scope.

function fname()
{
// function scope
}

let & const are block scope

{
// block scope
}

Hoisintg

Hoisting is a JavaScript technique that moves variables and function declarations to the top of their scope before code execution begins. Within a scope no matter where functions or variables are declared, they're moved to the top of their scope.

console.log(a);
 var a=10;

o/p: undefined Instead of an error, we get output as undefined, It's because of hoisting, we are able to access the variable before its declaration. Why undefined & not 10, because due to hoisting only declaration move to the top of scope & not definition.

var a;  // declaration
a=10;  // definition or initialization

Let's see how hoisting works in let & const, so we will get an error in case of let & const as both are block scope, we can't access them before initialization. let & const variables are hoisted but in the temporal dead zone. Functions are too hoisted, we can call a function before its declaration & it will work fine,Class are not hoisted.

This keyword

Value of This keyword depends on how it invoked. In JavaScript this is the context of a function invocation (a.k.a. exection). The language has 3 function invocation types:

  1. function invocation
  2. method invocation
  3. constructor invocation

function invocation

-> this in function invocation is window object in normal mode, & undefined in strict mode.can modify it using call, apply,bind.

arrow function

-> arrow function dont have their own execution context, so they always point to parent scope this. we cant modify arrrow fn this using call,apply,bind, it will always point to parent scope this.

method invocation

-> this refer to methods object, we can modify it using call,apply, bind.

constructor invocation

-> this refers to newly created object, we cant modify it using call,apply or bind.