Skip to content

Instantly share code, notes, and snippets.

@srsandy
Last active July 10, 2020 12:58
Show Gist options
  • Save srsandy/e2301cc7cf29516c9e17a8aaef8d5926 to your computer and use it in GitHub Desktop.
Save srsandy/e2301cc7cf29516c9e17a8aaef8d5926 to your computer and use it in GitHub Desktop.
JavaScript Notes

Javascript Notes

var, let & const

  • var provides functional scoping but not block scoping. var allow to log the variable without declaring it though it shows undefined.
  • let provides functional scoping as well as block scoping.
  • const provies functional scoping as well as block scoping but you cannot reassign value to a const type variable.

let and const will not allow you the log the variable without declaring it.

Keyword Scope Hoisting Can Be Reassigned Can Be Redeclared
var Function scope Yes Yes Yes
let Block scope No Yes No
const Block scope No No No

Hositing

If we try to use a variable before it has been declared and initialized, it will return undefined.

  console.log(x);
  var x = 5;

Output: undefined.

However, if we try to remove var keyword, so now we are no longer declaring the variable, only initializing it. It will return a ReferenceError and stop the execution of the script.

  console.log(x);
  x = 5;

Output: ReferenceError: x is not defined.

This is because of Hoisting. In Javascript, variable and function declarations are moved to the top of their scope.

// The code we wrote
console.log(x);
var x = 10;

// How JavaScript interpreted it
var x;
console.log(x);
x = 10;

Since only the declaration is hoisted, not the initialization, the value returned is undefined.

Javascript saved x to memory before the execution of the script. Since it was called before it was defined, the result is undefined and not 10.

Arrow function & this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment