Scopes and Closures

Like in other programming languages, variable scope in JavaScript is not created by blocks, instead its created from functions.
Ex:
var x = 1;
if(x === 1) {
var y = 'one';
}
console.log(x);
console.log(y); // prints 'one' as the scope is not block based

For the most part, scopes in JS are created via functions
var x = 1;
function assignValue() {
if(x === 1) {
var y = 'one';
}
}
console.log(x);
console.log(y); // will throw runtime error

Note *** variables ‘x’ from outer scope can be used inside function but not vice versa as in case of ‘y’

Global variables in JS are evil especially from browser perspective because we load everything at once and we dont know if our global variable names are conflicting with others from different libraries. For this reason we put our logic in a function expression and invoke that function but again the problem could be same if some 3rd party library has same global function. Hence we go for IIFE – Immediately Invoked Function Expression
(function () {
var a = 10;
var b = 20;
console.log(a+b);
})();
With IIFEs global namespace is not polluted.

Without declaring and defining a variable, if we try to use it we get and error.
By declaring and without defining a variable we get ‘undefined’

If we declare a variable, we can do both read and write operations fine, but if dont declare a variable then we can do write operation alone (and not read operation)
var x;
x = 10; // write operation
console.log(x); // read operation

console.log(y); // leads to runtime error as we cannot read before declaring
z = 10; // is fine as we can write without declaring a variable

The Window Object
Whenever we declare a variable outside a function then that variable becomes global. All the global variables and functions are wrapped inside a GLOBAL/ROOT object. This global object name depends on which runtime we are using for running JS.
If its the browser then the Global Object name is ‘window’.
If its node, then its called ‘global’

Scopes can be hierarchical: Variables declared inside a function (INNER VARS) can access variables declared outside the function (OUTER VARS)

Introduction to Functions

Functions cannot be overloaded in JS: Function defined with n arguments can be passed with n args where extra args will be ignored.

function foo() {
return "Hello World";
}
foo();

Functions can be created as

  1. Function Expression
  2. Anonymous Function Expression
  3. Functions as arguments
  4. Functions on objects

1. Function Expression
Functions as values (FIRST CLASS CITIZENS)
var myFunc = function foo() {
return "Hello World";
}
myFunc();

2. Anonymous Function Expression
In the below expression function name is not required as we call with assigned variable anyways which is aka AFE
var myFunc = function() {
return "Hello World";
}
myFunc();

3. Functions as Arguments
var myFunc = function() {
return "Hello World";
}
var executorFunc = function(fn) {
fn();
}
executorFunc(myFunc);

4. Functions on Objects
var myObj = {
"prop1": true
}
myObj.myFunc = function() {
console.log("Hello World");
}
console.log(myObj);
myObj.myFunc();

Default Function Arguments
‘arguments’: is an indexed object with list of arguments passed to method
‘this’: Understanding ‘this’ keyword in JS
var person = {
"firstName": "Niranjan",
"lastName": "Tallapalli",
"getFullName": function() {
console.log(person.firstName + ' ' + person.lastName);
}
}

person.getFullName(); // would work fine BUT
// imagine this scenario
var person2 = person; // object address is copied
person = {};
person2.getFullName(); // this would have person reference which is empty hence results in “undefined undefined”
// instead refer to the object on which getFullName is invoked which is done via “this” keyword

Note: *** Functions are objects behind the scenes in JS ***

Array functions
myArr.push(element); // will add element at the end of an array
myArr.pop(); // will remove last element from array
myArr.shift(); // removes element from beginning of array
myArr.unshift(element); // push element at the beginning of array
myArr.forEach(function(item, index, arr) {
console.log(item +' '+index);
})

Arrays and Wrapper Objects in JavaScript

Arrays
Every array in JS behind the scenes is an Object which means array element can be accessed with index as an integer and also as a string
myArr[0] is same as myArr["0"]

As arrays are objects, can we use DOT NOTATION here? No because the property name is a number which is invalid identifier

If array is an object then how does myArray[0] works? Its because JS does Type Coercion behind the scenes and converts number to string.

Since array indexes are just property names in an object, we can assign element to any index, say

myArr[100] = "xyz";
*** myArr.length -> gives 101 because its actually not the length of an array rather its equal to (max_index + 1)
var myArr = ["hello", "how", "are"];
console.log(myArr.length);
myArr[20] = "you";
console.log(myArr.length);

If you try to access a index which is not defined then you get value ‘undefined’ rather than ArrayIndexOutOfBoundsException like in Java
var myArr = [100, 200];
console.log(myArr[0] +';'+ myArr[1] +';'+ myArr[2]);

Note: Additional elements in array can be added dynamically

Wrapper Objects in JS
By default when we create a variables, they are created as primitives but when we use DOT NOTATION on primitive, JS converts primitive into its corresponding wrapper object and performs the DOT OPERATION and then discards the object.
var value = "Hello World";
value.length; // here value primitive is converted into wrapper string object and then performs length
typeof value; // shows "string" which is a primitive

Similar wrappers are available for Number, Boolean and also Symbol(in ES6)

Mawazo

Mostly technology with occasional sprinkling of other random thoughts

amintabar

Amir Amintabar's personal page

101 Books

Reading my way through Time Magazine's 100 Greatest Novels since 1923 (plus Ulysses)

Seek, Plunnge and more...

My words, my world...

ARRM Foundation

Do not wait for leaders; do it alone, person to person - Mother Teresa

Executive Management

An unexamined life is not worth living – Socrates

javaproffesionals

A topnotch WordPress.com site

thehandwritinganalyst

Just another WordPress.com site

coding algorithms

"An approximate answer to the right problem is worth a good deal more than an exact answer to an approximate problem." -- John Tukey

%d bloggers like this: