Tech Junkie Blog

Latest Posts

Friday, January 19, 2018

Since an array is a collection of elements of objects, values, etc.  The most common function performed on it is to iterate through each elements of the array.  The most frequent way to do that is with a for loop.

Let's say you have an array with the following:

var numbers = ["one","two","three","four","five"];

The numbers array above contains five string elements, which also has a indexes associated with the it.  There's also a length that is defined with each array that we will use for the for loop we are about to write.  So what do the you length of the numbers array will be?

If we output the array to the browser with the statement console.log(numbers.length) do you think we will get the length to be 5 or 4?

If you guess 5 you are correct because there are five elements in the array.  However, the arrays have zero based indexes therefore the index is always length -1

for(var i = 0; i < numbers.length; i++)
{
     console.log(numbers[i]);
}

The loop above loops through the array by comparing the value of i to the length of the numbers array.  It simply use the value of i as the index in the body of the loop.  So the loop above will produce the following output:


Notice we use the operand i < numbers.length instead of i <= numbers.length because if we try to access an element with the fifth index we will get an undefined.  That's the good and bad thing about JavaScript it does not crash your program, however it let's you get away with a lot of things.




So if you type the following

        for (var i = 0; i <= numbers.length; i++) {

            console.log(numbers[i]);

        }


You will get the same result except the fifth index will be undefined.

But another scenario is that some developer decides to delete an element of the array with the delete keyword, leaving the array with an empty element or undefined.  How would you handle that situation?  First let's create the situation where that could happen.  By the arrays with empty elements are called sparse arrays or loose arrays.  Tight arrays are arrays with all the elements defined.

So let's create a sparse array with the delete keyword.

delete numbers[2];

If you output the numbers array now you will see that the element with index 2 is now missing or undefined.  If you use the for loop again to output the browser you will see the following

        for (var i = 0; i < numbers.length; i++) {

            console.log(numbers[i]);

        }

As you can see the element with index 2 is undefined which happens to be the string "three"

Now let's say you want to output only elements that are defined, what do you do?

Well there are two ways to do that, the first is to check to see if the element is "undefined" then skip the element the "continue" keyword to go to the next iteration.

You would write the loop like this:


        for (var i = 0; i < numbers.length; i++) {











         
            if(numbers[i] == undefined)
                   continue;
            else
               console.log(numbers[i]);

        }

The loop above skips the current iteration of the for loop if an undefined is found, but writes out the value of the element if it has a valid value.

Another method is to check to see if the element is exists at all, which also checks for null values.  To check to see if the element exists with a valid value you can put a ! in front of the current element.





Like the code below:

        for (var i = 0; i < numbers.length; i++) {

            if (!numbers[i])
                continue;

            else
                console.log(numbers[i]);
        }

It will give you the same result as the undefined check, but this one will also weed out the elements that assigned null values.

You can also use the for/in loop for sparse arrays.  It will automatically check for elements with valid values and only deals with those.

For instance you can write the loop as

        for (var i in numbers) {

                console.log(numbers[i]);
        }

And it will same output, so it's up to you which method you want o use.














Friday, January 12, 2018

When you define an object as an Array in JavaScript you get the benefits of inheriting some useful methods with it.  Some of the common methods are those that allows you to add and delete elements from an array.  The .push() method adds an element at the end of the array, the unshift() method adds an element at the beginning of the array.  The delete keyword deletes an element at the specified index.

Let say you have an the following array:

var numbers = [3,4];

If you output the array in the browser console you will see that the array has two elements with the number 3 occupying index 0 and the number 4 occupying index 1.














Friday, January 5, 2018

In the previous post we created arrays of different types, in this post we are going to read the values from our arrays.

Let's work with the following arrays
  1. var numbers = [1,2,3,4];
  2. var stringArray = new Array("USA", "Canada","China");
  3. var objectArray = [{firstName: "Jane", lastName:"Johnson", weight:"115lbs"},{firstName: "Jack", lastName:"Johnson", weight:"200lbs"}];
Let's start with getting a value from an array:

To get the second value of an array you would write the following code by using the :

console.log(numbers[1]);
console.log(stringArray[1]);
console.log(objectArray[1]);












Friday, December 29, 2017

Arrays in JavaScripts are a collection of values stored in what are called elements.  Each element is represented by a numeric index that is zero based, meaning the first element of an array starts at index zero.  JavaScript arrays are dynamic and can contain many types of objects including functions.  The useful thing about arrays is that they are a specialized object that contains a variety of built-in methods that are useful in the manipulation of the array.

First let's create an empty array, there are several ways to do this:


  1. var empty = [ ];
  2. var empty = new Array();
  3. var empty = new Array(0);

The first example creates an empty array using the [ ] syntax, the second example creates an empty array by instantiating a new Array object with it's default constructor, then the third example creates an array with the Array constructor passing in the element argument of zero.  If you output the array with console.log(empty) they would all be the same output, an array with zero elements








Now let's create arrays with different types of data:

  1. var numbers = [1,2,3,4];
  2. var stringArray = new Array("USA", "Canada","China");
  3. var objectArray = {firstName: "Jack", lastName:"Johnson", weight:"200lbs"};
The first example is an array of numbers, the second array is an array of strings, and the the third array is an array of object.  If we use the console.log method to output the arrays we will find that the first two arrays has a prototype object of Array, but the last array has a prototype object of Object


        console.log(numbers);
        console.log(stringArray);
        console.log(objectArray);





















If you look at the last array objectArray you will noticed that it's not an array at all its actually an object because it is using the prototype Object.  That's because it is declared as an object with just the { } braces.  To make it into an array you just need to surround it with the [ ] brackets. Like the example below:

var objectArray = [{firstName: "Jack", lastName:"Johnson", weight:"200lbs"}];

Now it's an array of objects










Now let's do something that only JavaScript can do very easily. Let's create a mix array of the three above examples.  Let's call it mixedArray, like the code below:

var mixedArray = [numbers, stringArray, objectArray];

If we output it in the console with console.log(mixedArray) we would see the we get all three arrays in mixedArray.  This is what is called an array of arrays or associative arrays.


,

Friday, December 22, 2017

Every JavaScript object has a toString() and a toLocaleString() method defined with it.  It is a string representation of the object. 

For example if we define a date object like the following:

 var date = new Date();

and we output the console.log(date.toString()) method without any extra code we would get the current date and time automatically







By default the toString() method outputs the long form of the date and time.  If we want to output a format that is tied to the current locale of the browser.  We can call the toLocaleString() instead. Like the following:

console.log(date.toLocaleString())

and the output will be like the following:







The toString() method works for arrays as well.  Let's say we have an array of countries like the example below:

var countries = new Array("U.S.A","Canada","China");

We can output the toString() method to the console with the following code:

console.log(coutnries.toString());

and you would see the following output.






However, the toLocaleString() method will give you the same result because the method does not perform any special locale functions for you.  It only works for the date.  In order to out the locale representation for the array you need to write your own custom toLocaleString() method for the array.


Friday, December 15, 2017

Most people don't realize JavaScript has object property setters and getters or accessor methods.  When an object has a setter only it is a write only property, when it has a getter only method that it is a read only property.  If a property has both then it is a read/write property.  A perfect example is if you are working with a private property in JavaScript which has the $ prefix in front of it.

Let's say you have an object with a private property $n like the example below:


        var game = {

            $n: "Awesome Game!",

            get name() { return this.$n}
        };

The code above only has a getter name that exposes the private property $n when you console.log you should get value of the $n like the code snippet below

   console.log(game.name);

  As you can see the output is as expected, it prints out the value of $n the private property because we have a getter method name()  things get interesting when we try to assign a value to name.  Its a bit confusing because we access the name method with a dot notation, the same as how we would access a property.

Friday, December 8, 2017

In JavaScript you can delete an object's property with the delete operator.  Let's use the product object again as an example.

Let say you have the following JavaScript code to create a product object.


        var product = new Object();

        product.name = "Chai";
        product.category = "Tea";
        product.country = "India";
        product.badProperty = "Bad Property";
        product.badProperty2 = "Bad Property 2";
        product.supplier = {
            name: "ACME Tea Of India",
            location: "New Delhi"
        };

console.log(product);

If you view the above code in a web browser window you will see the following.












We are going to use the delete operator to delete badProperty and badProperty2.  As with the way we access properties we can delete properties with either the dot notation or the [] operator.  To delete the properties type in the following.

delete product.badProperty;
delete product["badProperty2"];

If you type console.log(product) again the two properties will no longer be there












Friday, December 1, 2017

There are times when you will get an error when you tried to access a property in an object, sometimes you think a property exists in the object but it does not.  Let's use the product object from the previous blog post as an example.


        var product = new Object();

        product.name = "Chai";
        product.category = "Tea";
        product.country = "India";
        product.supplier = {
            name: "ACME Tea Of India",
            location: "New Delhi"
        };

Let's say another developer works on the project and he assumes that since there's a "country" property that there should be a "city" property.  If he tries to access the access the "city" property in the product object he will get an undefined, because the property does not exist.   If he types the following he will get the undefined message.

product.city; or type console.log(product.city)







If the developer still persists and still tries to access property by checking it's length he will get the TypeError:








As you can see these errors are not very descriptive, so the best thing to do is to avoid them all together.  The way to do that is to check to if a property exists before you access it with the example below.

var length = undefined;

if(product)
  if (product.city)
      length = product.city.length;


Now if console.log(length) we will get an undefined if the "city" property does not exist.  It's way better than getting a TypeError exception and it's the expected result because you initialized the length variable to "undefined".  Another alternative is to use the .hasOwnProperty() method or the in
operator to test if the property exists in the product object.

For the .hasOwnProperty()

The code would look something like this

if(product.hasOwnProperty("city")
     length = product.city.length;

With the in operator the code would look something like this.

if("city" in product)
   length = product.city.length;

Monday, November 27, 2017

Since CSS does not live in an island no technology does.  It has to interact with it's neighbor HTML on a regular basis.  In the HTML world there's the block-level elements and then there's the inline-level elements.  Most developers could care less what the meanings of these words mean.  For the designers, it's okay they are just trying to make things look pretty cut them some slack :)

First let's look at block elements:

Block elements are needs to stand on it's own, meaning there's no elements at either sides.  They generate a break on the top of bottom of itself.

Here is an example:

The <h1> and <p> tags are block elements.  Even if you write the code <h1>This is H1<h1><p>This is a paragraph tag!</p> in one line next to each other without any breaks.  The resulting respresentation of those tags in the browser would look like this.


This is H1

This is a paragraph tag!



As you can see even without any line break tag <br/> the elements puts at tag all by itself.

The inline-level elements:

The inline-level elements are the nice kid that shares toys with his friends, while his CEO friend the block elements tries to dominate everything.  If you have to think of it that way you can!  The inline-element works within the context/text etc. and does not generate a line break.

For example if we put a <strong> in the middle of the paragraph tag text it won't generate a line break. with something like this <p>This is a <strong>paragraph</strong> tag!</p>


This is a paragraph tag!


As you can see the <strong> tag in the middle of the sentence did not break up the text into a new line.


Friday, November 24, 2017

Now that we've learned to create objects in all sorts of ways it's time to set and get the object properties that we've created.  In this blog we will go over how to access the object properties either to set them or get them.

First let's create an object that we can work with:

Type in the following code in the between the <script type="text/javascript"></script> tag in an html page.


        var product = new Object();

        product.name = "Chai";
        product.category = "Tea";
        product.country = "India";
        product.supplier = {
            name: "ACME Tea Of India",
            location: "New Delhi"
        };

        console.log(product);
If you run the page with the code above you will see the following in the browser console:

Tuesday, August 1, 2017

In this blog post I am going to show how to connect to your Azure subscription in Visual Studio 2015.  As a developer it's nice to have the Azure subscription integrated into Visual Studio so that you don't have to log into the Azure portal every time you want to interact with Azure.

Follow the steps below to connect to your Azure subscription in Visual Studio:

1.  Open Tools → Connect to Server
2.  On the top of the "Server Explorer" connections list right click on "Azure" and select "Connect to Microsoft Azure Subscription"













3. A login prompt pops up, log into your Azure account














4.  Once logged in, you will be connected to your Azure subscription


Tuesday, July 25, 2017

In this blog post we are going to get the Azure subscription in Powershell using the secure certificate method.

Follow the steps below to get the Azure subscription:

1.  Open Powershell as an Administrator
2. Type Get-AzurePublishSettingsFile once you type the command into the Powershell command line it will pop-up the Azure authentication prompt.  Authenticate into Azure and save the publish file settings into a place that you will remember.



























3. Now type into Powershell the command Import-AzurePublishSettingsFile "path of the publishsettingsfile"




4. Now you are connected to Azure from Powershell

Tuesday, July 18, 2017

Tuesday, July 11, 2017

In this post I will show how to download the automation scripts that Azure provides when you create a new virtual machine in Azure.  This is great for PowerShell scripting or if you want to interact with your VM in Visual Studio.  You don't have to start from scratch.

Here are the steps to get the automation scripts for your VM in Azure:

1. Log into the Azure portal at https://portal.azure.com
2. Click on "Virtual Machines"



















Tuesday, July 4, 2017

Tuesday, June 27, 2017

Tuesday, June 20, 2017

People often get confused when they work with Azure because there are two versions of Azure.  Most people call it the classic mode and the new portal Azure or the more official term is ASM vs ARM.  In this post we will create a CentOS Linux virtual machine in the new Azure portal.

Follow the steps below create a new Azure portal:

1. Go to the URL : https://portal.azure.com
2. Log in with your Azure credentials
3.  Click on "Virtual Machines" make sure it doesn't say classic on the link





















Wednesday, June 14, 2017

Don't have money to buy Winzip?  If you are looking for a good file achiver or extractor look no further than 7-Zip.  It archives and extract most of the file formats and the best part of the value proposition for this great application is that it's free!  And if you act now, you will get it for free!  So hurry while supplies last! It's still free!  Anyways I haven't had any problems with the application.  Even though it's free it's high quality.  So head over to the official website at http://7-zip.org/download.html and download the version for your OS.



Tuesday, June 13, 2017

In this blog post we are going to deploy a Linux virtual machine in Azure.  Most of the steps takes place in the Azure portal.  To get to the Azure portal type in the browser this address https://manage.windowsazure.com

Follow the steps below to create a Linux virtual machine in Azure:

1.  Type into the browser https://manage.windowsazure.com/
2.  Log into Azure with your Azure credentials
3.  On the left hand side of the portal click on the "Virtual Machines" link



















Tuesday, June 6, 2017

In the previous blog post we created an Azure cloud service.  Now we are going to create a private virtual Azure network.  The importance of this is that when you create a virtual machine in Azure you will use this virtual network to connect to your virtual machine.

Follow the steps below to create a virtual network in Azure:

1.  Click on the "Networks" link on the left hand side





















Tuesday, May 30, 2017

The first thing you want to do in Azure is to create a new "Cloud Service" which is a deployment service your resources will be deployed in such as a virtual machine or a web site.

Follow the steps below to create a new Azure "Cloud Service":

1.  Once you are logged into the Azure Portal click on the "Coud Services" on left hand side





















Monday, May 1, 2017

In JavaScript there are two ways to access an object, first by dot notation like this

product.name

or with array notation

product["name"]

They both get the job done.   However with the array syntax [""] you access the object as if it's an array but instead of accessing it by numbers or index you access it by the property names.  That's because JavaScript objects are associative arrays.  They look like other objects in other languages such as C, C++, and Java.  However they behave very differently.

In other languages objects are defined in advance, their properties are methods are fixed.  To add a property or method to the object you have to change the class the object instance is created from.

Friday, April 28, 2017

Object.Create( ) is a static function which can take two arguments.  The first argument is the prototype of the object, while the second argument is the properties of the argument.  A prototype is a second object that is created with every JavaScript object.  It is like a blueprint, or the model that the object is built on.  Think of it as a car prototype.

So let's create an object with Object.Create( ) function:

var person = Object.create({
    name: "Tech Junkie",
    location: "Mars",
    hobbie: "Video Games"
});

console.log(person);

Here is how the object looks like:














Thursday, April 27, 2017

In the previous post we visited how to create an object with an object literal.  In this post we are going to create the same object using the new keyword.  When creating objects using the new keyword it is required that the it is followed by a function call.  The purpose of this function call is the needs a way to call to the constructor of the new object.  A constructor is used to create or initialize the created object.

Here is the code to rewrite our literal object using the new keyword:

var product = new Object();

product.name = "Chai";
product.category= "Tea";
product.country= "India";
product.supplier= {
    name: "ACME Tea Of India",
    location: "New Delhi"
};

product.related = new Array("Earl Grey", "Green Tea", "Dark Tea", "White Tea");
product.display = function () {
    console.log(this);
};

Wednesday, April 26, 2017

The most common ways you see how objects are created in JavaScript is the object literal syntax.  The object literal syntax is the open { } with comma separated name: pair value lists.  The name: part is the name of the property.  The part after : is the property value which can hold a primitive value or another object.  It could even be a function.

Here is an example of an object literal:

var product = {
    name: "Chai",
    Category: "Tea",
    Country: "India",
    supplier: {
        name: "ACME Tea Of India",
        location : "New Delhi"
    },
    related: ["Earl Grey", "Green Tea", "Dark Tea", "White Tea"],
    display: function () {
        console.log(this);
    }
};

Tuesday, April 25, 2017

JavaScript error handling is a lot like other languages where you have the try/catch/finally  statement that you can used.  The basic premise is

try
{
     // try some codes here fingers crossed that nothing bad happens
}
catch(ex)
{
     // oops something bad happened, this is where it gets handled or I tell the user
}
finally
{
    // I don't care what happens I am going to execute and get paid
}

Here is the error handling in action:

Monday, April 24, 2017

The for/in loop is a for loop that is used to iterate through the variables in an object. It can iterate to through that anything that can evaluated on the left side of the assignment expression call the LValues.  Let's use the for/in loop to iterate through an object "person".

Here we created an object called "person" with three properties we are going to use the for/in loop to display the property names as well as the values of those properties

var person = new Object();

person.name = "Tech Junkie";
person.occupation = "Blogger";
person.location = "Mars";

for(var p in person)
console.log(p + ": " + person[p]);

Here is the output:


Friday, April 21, 2017

The do/while loop is similar to the while loop.  The difference is that the first the loop expression is tested after the do statement block is executed at least once.  For example let's use our countdown example again.

If we have the code below the countdown displays the same results as the output.  However, the first iteration is performed without a evaluation of the expression.  It's not until the countdown is 9 that the while part of the loop kicks in.

Thursday, April 20, 2017

The while loop statement in JavaScript simply executes a statement block until a condition is not true anymore the syntax for the while loop is as follow

while (expression is true)
{
     execute these statements
}

The while loop is an iterative loop if the condition is true and the statements are executed, it starts at the top of the loop again and executes until the expression is false.  Therefore, there's a potential for an infinite loop.

Wednesday, April 19, 2017