sarpay
5/21/2014 - 11:11 PM

JavaScript Notes

#JS JavaScript Notes

Declaration Conncepts & Scope of Variables

In JS there are two scopes, local scope and global scope. The scope determines the accessibility of the variables.

  • When a variable is declared outside a function it is globally scoped and can be used in the whole window.
  • When a variable is declared within a function it is a function scope and it is only available and accessed within that function.

VAR

  • Var can be accessible anywhere in the global scope or in a function scope and can be updated and redeclared within its scope.
  • Block scope is the code that lives between parenthesis {}. A variable declared with var in a block scope is available outside of that block scope.
// Accessibility Sample
for (var i=0; i < 10; i++) {
  console.log(i); //output: 0,1,2,....,9
}
console.log(i); //output: 10 (i can be accessed outside the scope).

// Redeclaration Sample
var a = 2;
if ( a === 2); {
   var a = 4; // the scope is global
   console.log(a); // prints outs the number 4
};
console.log(a); // prints outs the number 2

Hoisting. Hoisting means that any variable declared using Var will be hoisted to the top of the execution and will be available to the scope.

_myVar = "Banana"; // using a var before its is declared

var _myFunction = function(){
 _myVar = "Apple"; // using before the declaration
};

_myFunction(); // calling the variable before the declaration

var _myVar;

console.log(_myVar);

// outputs: Apple 
  • So we can confirm that a Var variable can be declared in any place, they have no block scope.

LET

Even if the Let variable is defined as same as the Var variable globally, the let variable will not be added to the global Window object.

var varVariable = “this is a var variable”;
let letVariable = “this is a let variable”;

console.log(window.varVariable); //this is a var variable
console.log(window.letVariable); //undefined
  • Let can only be accessible inside the block scope.

  • Let variables are usually used when there is a limited use of those variables. Say, in for loops, while loops or inside the scope of if conditions etc. Basically, where ever the scope of the variable has to be limited.

for (let i=0 ;i<10; i++) {
  console.log(i); //output: 0,1,2,....,9
}
console.log(i); //error: "i is not defined"
  • A Let variable can be updated if it is defined in different scopes.
  • Let variables cannot be re-declared while Var variables can be re-declared in the same scope.
// Redeclaration Samples

//Sample 1
let temp = "this is a temp variable";
let temp = "this is a second temp variable" // SyntaxError: temp is already declared

// Sample 2
let greeting = "say Hi";
 if (true) {
    let greeting = "say Hello instead";
    console.log(greeting); // "say Hello instead"
 };
 console.log(greeting); // "say Hi"

CONST

  • Only accessible inside the block scope just like let,
  • It can NOT be updated nor redeclared.
  • It must be declared when it is created.
  • It must be initialized
const car = "Honda";

const car = "Volvo"; 
// this will cause an error: 
// Identifier 'car' has already been declared.

car = "Skoda"; 
// this will cause an error: 
//Assignment to constant variable

However, the values inside a constant in ECMA 6 can be changed if you are using it as an object or array:

const OBJ =  {
  prop1 : "foo",
  prop2 : "bar",
  prop3 : 100
}

// no errors displayed
OBJ.prop1 = "another value";
OBJ.prop2 = "example text";
OBJ.prop3 = 453;

// ERROR...
OBJ = {
  newProp : "qwerty"
};

Same situation for a constant array:

const OBJ =  ["foo","bar"];

// no errors displayed
OBJ[0] = "another value";
OBJ[1] = "example text";

// but if you try to change the structure it self
// ERROR...
OBJ = {newProp : "qwerty"};

If you really want to prevent changes in a object, you can use Object.freeze

const OBJ = {
  prop1 : 1,
  prop2 : 2,
  propA : "A",
  propB : "B",
};

OBJ.prop1 = 3;

Object.freeze(OBJ);

// NOTHING HAPPENS...
OBJ.prop1 = 1;

What is the object type?

if (typeof checkedVal != 'undefined') {}
if (typeof maxRecords === 'number') {}
if (typeof firstName === 'string') {}
if (typeof optIn === 'boolean') {}

this Keyword

https://medium.com/@js_tut/the-magic-of-this-keyword-2ed897d6033b?sk=72968f72a56d321d5417378e52087dcb

The original designer of JavaScript decided to tie a secondary feature to this keyword. Not only is it used to point to an instance of an object from its own constructor or its methods (hence, this) it is also used to keep track of execution context which is often based on where a function was called from.

function Cat() {
  this.name = "felix";
  console.log(this); // Cat {name: "felix"}
}
let cat = new Cat(); // Cat {name: "felix"}

// -- or --

class Mouse {
  constructor() {
    this.name = "mappy";
    console.log(this); // Mouse {name: "mappy"}
  }
}
let mouse = new Mouse(); // Mouse{name: "mappy"}

In these examples function, the this reference points to itself.

Misc.

IFRAME

if (top != self) { top.location = location; } /* doesn not allow page to be framed */

FORM EVENTS

function processForm(e) {
    if (e.preventDefault) e.preventDefault();
    var searchVal = document.getElementById('s').value;
    document.getElementById('s').value = searchVal.replace(/-/g, '');
    document.getElementById('searchform').submit();
    return false;
}
(function() {
    var form = document.getElementById('searchform');
    if (form.attachEvent) {
        form.attachEvent("submit", processForm);
    } else {
        form.addEventListener("submit", processForm);
    }
})();

ENCODE / DECODE

function encode() {
  var obj = document.getElementById('dencoder');
  var unencoded = obj.value;
  obj.value = encodeURIComponent(unencoded).replace(/'/g,"%27").replace(/"/g,"%22");    
}
function decode() {
  var obj = document.getElementById('dencoder');
  var encoded = obj.value;
  obj.value = decodeURIComponent(encoded.replace(/\+/g,  " "));
}