|||

Javascript Refresher

If you are like me and you procrastinated learning javascript until your kids were dependant on it to eat, then this quick refresher post might be of some value. To get things started, I have created a very simple page in jsfiddle. Feel free to copy the code from the following snippets and test it out at JsFiddle.

A word of caution, this is going to be a long long post. Let’s begin:

Comments

  • List item
  • Single line and multiline (Same as C#)

Variables

  • always declare variables with var keyword in local scope
  • variables not declared by the var keyword automatically become global variables
  • dont use global variables they cause global namespace pollution
  • all global variables get attached to the window object and can be accessed using window object via dot notation.
  • types are automatically inferred by the value on the right side of = operator (like C# var keyword)
  • use typeof” keyword to check the type of a variable
// Global variables
function add(first,second) {
  // Change this to var a = first for it be local
  a = first;     
  return a + second;
}
   
write("1 + 2 = " + add(1,2));
write("a = " + a);
write("3 + 4 = " + add(3,4));
write("a = " + a);
  
if(window.a)
  write("a is global");
else
  write("a is NOT global or is undefined");  


// typeof 
var streetNumber = 42; 
var streetAddress = "123 address";
write(typeof streetNumber + " = " + streetNumber);
write(typeof streetAddress + " = " + streetAddress);

Null

  • Null is a primitive js type
  • Null means absence of a value
  • Null in a boolean comparison evaluates to false
  • zero and empty string although are not null, but they will evaluate as false in boolean comparison as well
  • Null means an object or variable does not have a value. A null reference.
// Null evals false in bool comaprsion
var myValue = null;
if(!myValue)
    write('null evals to false');

// Non null evals true in bool comparison
var hasValue = 1;
if(hasValue)
   write('hasValue is NOT null');

// zero evals false in bool comparison
var zeroVal = 0;
if(!zeroVal)
   write('zero value evals false in bool comparison'); 

var emptyString = "";
if(!emptyString)
  write('empty string evals false in bool comparison'); 

Undefined

  • Undefined is a primitive js type that means unknown value
  • when a property on an object is called that does not exists it returns an undefined
  • Also evaluates to false in a boolean comparison
  • Undefined means an object or variable was never initialized
  • For c# devs, undefined in some ways is comparable to the default(T)
// Undefined
var something;
write("Initial value of something = " + something);

if(!something)
  write("undefined evaluates to false");   
    
var person = { name : "Raghu" };
write("Name: " + person.name);
write("Age: " +  person.age);    // prints undefined

Objects

  • Everything in js is an object except string,number,boolean, null and undefined
  • objects can be declared in two ways:
  • object literal notation: var myObj = { name: Raghu’, age = 30 };
  • new keyword notation: var myObj = new Object(); myObj.name = Raghu”;
  • functions are also objects and calling toString on functions return the function body itself.
  • objects can also be nested.
  • if an object property has a space in the name then it must be enclosed in double quotes, as space is a reserved JS keyword.
  • To access a property which has a space in it, we must use the [ ] syntax. example: - cust[“company name”];
// Objects

// empty object
var empty = {};
write(typeof empty);
write(empty.toString());

// new keyword notation
var person = new Object();
person.name = "Raghu";
write(person.name);

// object literal notation
var john = { name : "John", age : 20 };
write(john.name);
write(john.age);
write(john.toString());

// write own implementation of toString
john.toString = function() {
  return "Name = " + this.name + " Age = " + this.age;
};
write(john.toString());

// functions are also objects
write(write.toString());

//  length of a function object returns the number of parameters
function add(one, two){
  return one + two;
}
write(add.length);

// nested objects
var nestedObj = {
  address : { 
    number : 1, 
    street : "brunswick"
  }
};
write(nestedObj.address.street);

Equality

  • primitive types are equal if their values are equal.
  • objects are only equal to themselves, since every object has its own unique memory location.
  • Two types of equality operators == and ===
  • == will coerce (force) the two operands into the same type and then do a comparison
  • === does not coerce the operands
  • never use == or != for comparison, always use the === and !==
  • always use round brackets ( ) when doing a comparison operation especially when concatinating with strings
// Equality

// objects are equal to themselves
var joe = { name : "Joe" };
write("Object equals to itself : " + (joe === joe));

// + operator coercion : BE CAREFULL !!!!
var sameJoe = { name : "Joe" };
write("Object equals to itself (without braces): " + sameJoe === sameJoe);

// two separate objects are not equal
write("Two separate objects are equal : " + (joe === sameJoe));

// primtive types are equal if their values match
write("apple === apple :" + ("apple" === "apple"));
write("16 === 16 :" + (16 === 16));

// That's why you never use == operator
write(' "" == 0 : ' + ("" == 0));

Functions

  • functions are objects and they inherit from the Object type.
  • .length returns the number of parameters it takes
  • .name returns the actual name of the defined function (not standard across all browsers)
  • functions can be declared in different ways as follows:
  • Standard function declaration. function square(x) { return x * x; }
  • Named and assigned declared
    • var squareFunc = function square(x) { return x * x; }
    • NOTE: With this declaration a function cant be invoked by the name anymore, it can only be invoked by the variable name now
    • assigned functions can be invoked by variableName(param1);
  • Anonymous and assigned function:
    • function name can be omitted with this declaration as it is of no use
    • but ideally use a name even if function is assigned to a variable as it will show up in the call stack during debugging
  • Anonymous and immediate invocation:
    • (function(x) { return x * x; })(5); // results in 25
    • no namespace pollution with this approach as function is self contained.
  • all extra parameters will be ignored.
  • no function overloading JS, the first one disappears in ether
  • parameters that are not supplied, default to Undefined’
  • objects are passed by ref and primitives are passed as values
  • every function object has an arguments objects which lists all the arguments in an array format.
  • You cannot explicitly create an arguments object. The arguments object only becomes available when a function begins execution.
  • The arguments object of the function is not an array, but the individual arguments are accessed the same way array elements are accessed. The index n is actually a reference to one of the 0n properties of the arguments object.
  • recursion is possible in javascript.
  • javascript supports closure, that means you can define a function within function.
// Function invocation 
function reverse(a)
{
  a = a.split('').reverse().join('');
  return a;
}

function reversePersonName(p)
{
  p.Name = reverse(p.name);    
  return p;
}

var name = "Tom";
write("Reversing string primitive = " + reverse(name));
write("Original string primitive = " + name);

var tom = new Object();
tom.name = "Tom";

write( reversePersonName(tom).name ); 
write( tom.name );

// Recursion 
write( 
  (function factorial(n) {
    if(n == 0 || n == 1)
      return 1;    
    return n * factorial(n  - 1);
  })(5));

// function's argument property
function add() {
  var total = 0;
  for(var i = 0; i < arguments.length; i++) {
    total += arguments[i];
  } 
  return total;
}

write(add());
write(add(1,2));
write(add(10,20,30));

// Closures
var a = "a";
function outer() {
  var b = "b";

  function middle() {
    var c = "c";

    function inner() {           
      write(a + b + c); 
    }

    inner();
  }
  middle();
}

outer();

Control Flow

  • { } block does NOT provide variable scope
  • The ONLY thing that creates a scope in javascript is a function
  • switch statement in JS looks same as C#
  • loops are same as C# except use var for variable declaration
  • JS has a for .. in loop which unlike c# only iterates over an object’s properties
  • while loop is same as C#
  • do while is same as C#

Exception Handling

  • try catch syntax is same as C#
  • throw keyword is used to throw exceptions
  • finally will always be executed.
// Exception handling
function exceptionThrower()
{
  throw  { name: "KichooException", message: "Kichoo did something wronng" } ;
}

try{
  exceptionThrower();
}
catch(kichooException){
  write("Exception name = " +  kichooException.name);
  write("Exception message = " +  kichooException.message);
}

Types and Libraries

  • Can use both single quotes or double quotes to encode a string.
  • if the string has a single quote use double quotes to start the string
  • if the sting needs double quotes then start with single quote, this required no escaping
  • NO multiline string sytax
  • escape sequences begin with a
  • Unicode symbols can be included by [code][/code]
  • for new line
  • in JS ALL numbers are floating point
  • JS arrays can store anything in them, i.e. a single array can contain string, numbers, regex and objects
  • push and pop methods on the array can make them behave like a stack
  • Dates have NO literal syntax, they must be declared by the new object syntax
  • new Date() is the current date
  • Datejs for more date functions
  • Json2 library for parsing json
  • NaN stands for Not a Number returns true or false is a global JS function
  • All Global functions: - http://www.w3schools.com/jsref/jsref_obj_global.asp

this Keyword

  • In JS this applies to the owner of the function
  • this keyword represent the immediate parent of the function in which it is accessed.
  • for exmaple - if a function was part of an object, the this keyword would refer to the object itself.
  • By using the bind method on a function, we can change the parent of a function and hence extend/leak the scope of a method.
// this keyword in an object

    var myObj = { name : "Raghu", 
         showName : function () { 
           write(this.name);
         } 
        }; 
    
    myObj.showName();
    
    // using the bind method to copy function to a global state
    var myObj = 
        { name : "Raghu", 
         showName : function () { 
           write(this.name);
         } 
        }; 
    
    myObj.showName();

    // bind to top level window object
    var sn = myObj.showName.bind(this);
    
    // This will now print window object's name property 
    sn();                               
    
    // Another example
    
    function def() {
      write(this.x);
    }
    
    var newDef = def.bind( { x: 123 } );
    newDef();
Up next Sharing common connection strings between projects GTD (Getting things done) — A simplified view
Latest posts Flutter CI/CD with Azure Devops & Firebase - iOS - Part 1 Flutter CI/CD with Azure Devops & Firebase - Android - Part 2 How to samples with AWS CDK A hashicorp packer project to provision an AWS AMI with node, pm2 & mongodb Some notes on Zeebe (A scalable process orchestrator) Docker-Compose in AWS ECS with EFS volume mounts Domain Driven Design Core Principles Apple Push Notifications With Amazon SNS AWS VPC Notes Building and Deploying apps using VSTS and HockeyApp - Part 3 : Windows Phone Building and Deploying apps using VSTS and HockeyApp - Part 2 : Android Building and Deploying apps using VSTS and HockeyApp - Part 1 : iOS How I diagnosed High CPU usage using Windbg WCF service NETBIOS name resolution woes The troublesome Git-Svn Marriage GTD (Getting things done) — A simplified view Javascript Refresher Sharing common connection strings between projects A simple image carousel prototype using Asp.net webforms and SignalR Simple logging with NLog Application logger SVN Externals — Share common assembly code between solutions Simple async in .net 2.0 & Winforms Clean sources Plus Console 2 — A tabbed console window