Javascript Tutorial

Our Own Score

In this single question and answer post we are going to quickly go through the basic of Javascript programming language so you will have a basic concept understanding about Javascript after reading this post. Javascript is the most important web based programming language nowadays and if you are a web developer then Javascript is a must learn programming language together with Python and Php for creating online web application, blog and website.

What is Javascript

Javascript is a scripting language which runs on all web browsers include Firefox, Edge, Chrome, Safari and Opera. Javascript can either run offline or online as long as you got a browser (any browser) to host it.

Does Javacript needs to be compiled before running

Yes, all high level programing language will need to be compiled before running on a platform except the machine language which consists of 0 and 1. But you do not need to worry about the compilation issue because your web browser will take care of that for you which saves the developer lots of time because if you are writing a c++, Java or Python program then you will need to use an IDE such as Eclipse, CodeBlocks or the command line to recompiled the code by yourself each and every time you edit your code.

Show me the method to run Javascript on the web browser

I will use Firefox to show you the method of running a Javascript program in a web browser but you can use any web browser to achieve the same outcome. Before we run the Javascript program we do need to create a few files and write a few lines of code, so lets get started!

First create the hello.js file and insert the below code.

alert("Hello World!");

Next lets create an html5 file and named it df.html

<!doctype html>
	<head>
		<meta charset="utf-8">
		<title>JS Demo</title>
	</head>
	<body>
		<script src="hello.js"></script> //We will link the javascript file in this webpage
	</body>
</html>

Now make sure both files are in the same folder then right click on the df.html file to open it in the Firefox web browser, you should see the below screen.

hello

Congratulation, you have just created your first Javascript program and run it on Firefox!

Do we need to insert semicolon at the end of a Javascript statement

You can but you do not need to because now all the major web browsers will accept the Javascript statement without the semicolon, which looks kind of like Python statement.

Is Javascript simple

Yes it is very simple and easy to learn, for example we can create a random float and shows it in an alert box with only two lines of code.

var random_v = Math.random();
alert(random_v);

The Math.random method from javascript is very useful when it comes to creating a random number with javascript.

js random
js random

Show me some loops in Javascript

The Javascript do while loop will run all the statements within the do while code block until the condition of the do while loop has been met. Here is an example in which the do while loop will run six times and shows the alert box six times before the loop terminates.

var i = 0;
do {
	alert("Hello World!");
	i++;
}while(i <= 5)

No matter in what condition the above loop will at least run one time before it terminates. If you need to check the condition before the loop starts then I would suggest using the while loop or the for loop instead.

Javascript for loop has the following syntax.

for (statement 1; statement 2; statement 3) {
        the code block
}

Statement number 1 is where we will initiate a value before the loop starts. Statement 2 defines the condition for running the loop. Statement 3 is where we increase the initial value. In below example we will show the alert function 10 times with the for loop.

for (var i=0; i<10; i++)
{
   alert("Hi");
}

Suppose you have created a javascript array and need to loop through all the elements within that array then we can use the for loop to loop through each element within that array as follow.

var array1 = ["hello", "this", "world"];
for(var i=0; i<array1.length; i++)
	alert(array1[i]);

The above program will loop through the javascript’s array with the for loop and shows the alert box in every pass of the loop.

The javascript for…in loop will be used to loop through the object’s keys. In each iteration, a key from the object is assigned to the key value in below example and the for…in loop continues till all the keys of the object have been iterated!

for (var key in object){
   // statement goes here
}

In below example we will create a javascript object and then iterate through it with the for…in loop.

We will talk little bit about the Javascript object in this part and further talk about it in the coming part bit by bit. Javascript object has a key and value pair where the key is like the name of a property. Here is one of the method we use to create an object

var person = {
		
		name : "Johny",
		job	: "Programmer",
		salary : 3000
		
};

Take notice that if the property is a string then we need the open and close ” for the property of that object, also we need to insert comma for each key value pair in that object.

Next we use the for…in loop to loop through the key and value pair of that object and then print out it’s vaues on the console.

/**
 * Loop thorugh an object with key and value pair
 */

var person = {
		
		name : "Johny",
		job	: "Programmer",
		salary : 3000
		
};


for (let key in person){
	console.log(person[key]);
}

Here is the outcome

Johny
Programmer
3000

In this next example we will use the for of loop introduces in ES6 to loop through an array as well as the contents within the generator function. In the first example, an array goes into the for of loop and the total of all the elements of that array has been calculated.

let monthlyincome = [1000, 2000, 3000];

let total = 0;

for(let income of monthlyincome)
	total += income
	
console.log(total) // output 6000

Next we continue to loop and add up the contents within the generator function’s income2 by passing income3 into the for of loop.

function* income2() {
	yield 1000; // the yield keyword is needed to return the value.
	yield 3000;
}

function* income3() {
	yield* income2();
}

for(let income of income3())
	total += income
	
console.log(total) // output 10000

Next we add up the array elements within the generator function’s income4() with the for of loop.

 
function* income4() {
	yield* [20000, 30000]
}

for(let income of income4())
	total += income
	
console.log(total) // output 60000

As you can see we can use the for of loop to iterate through the value of an iterable object which makes it a lot more simple than using the next method of the generator function.

Finally we will loop through the elements within an array, add them up and multiply by a factor then return the new value.

let array1 = [1000, 3000]
let array2 = [2000, 5000]
let array3 = [...array1,...array2]
let sum = 0

let total_ = (arry, factor=6) => {
	for(let arr of arry)
		sum += arr
	return factor*(sum)
}

let summation = total_( array3 )

console.log(summation) //66000

Javascript for…of Loop makes thing really simple for the web developer to write a loop since it has been introduced in the ECMAScript6.

Next lets look at the while loop.

while (true)
{
   alert("hey");
}

The above while loop will run forever until the computer is running out of resources thus forced the browser to shut down.

Now lets look at Javascript condition tag

Here is how the javascript’s if else condition statement looks like.

if (condition)
{
     //run this code if condition is true
}
else
{
     //else run this code if the first condition is not true
}

Here is an example of how to use the if else statement.

if (age < 12)
{
  alert("small boy");
}
else if (age < 50)
{
  alert("young man");
}
else
{
  alert("old man");
}

As you can see from the example above if the first condition is true then the code within the first if block will run and the rest of the if blocks will be skipped. Else if the second condition is true then the second code block will run instead and finally the third code block will run if both the first and second if else statements are false. The third else block also known as the default block!

The javascript with keyword

When we use the Javascript with keyword together with a javascript object then the object specified as an argument to with becomes the default object for the block that follows and thus we do not need to use that object name again when we refer to the properties of that object because the ‘with’ keyword is used like a kind of shorthand for referencing an object’s properties or methods within that block!

Let us look at an example of the with keyword, first we will create a main object.

var person = {
		name : "Johny",
		occupation : "Programmer",
		salary : 2000
};

Next we will create a new object from the above blueprint.

var worker = Object.create(person); // create a new worker object

At last we will use the with keyword to include the object and print it’s property on the console.

with(worker) {
	console.log(name);
	console.log(occupation);
	console.log(salary);
}

The outcome is as follow

Johny
Programmer
2000

As you can see the with keyword will make the object become default within a block and thus we can then use it’s property or method without need to call the name of that object again.

JavaScript switch statement

The javascript switch statement is used to perform different action based on condition. Below is an example of the switch statement.

switch(n)
{
    case 1:
      	//run code block 1
      	break;
    case 2:
      	//run code block 2
      	break;
    case 3:
	//run code block 3
      	break;
    default:
	//if n is different from case 1, 2 and 3 then run the code under the default case
}

The break keyword is very important because if we do not use the break keyword then the code will continue on the next case automatically. If the n value is not in any of the 1, 2 or 3 case then the statement under the default case will be called. One more thing we need to know here is that the switch statement does not take value other than number so make sure you only pass in the number.

Detect the browser keydown event with javascript

We use the document’s onkeydown listener to listen to the keydown event in our web browser and then saved that keycode to an array.

let keyPressList = [] // declare empty array
//record keyevents
document.onkeydown = function(e){
  e = e?e:window.event;
  keyPressList[e.keyCode] = true;
};

You have mentioned array a lot in the previous part lets show me some array

Array in Javascript is just like a house which has many rooms and each room has a tenant, unlike Java or C++ Javascript array is very loose which means you actually can combine a number with a word within a single array and the web browser will not complain about that. But unless you want to create a product which consists of name, cost and type you will normally do not want to mix all those things together.

To declare an empty array you will write this statement.

let price = []

If you want to concatenate two arrays together then you can use the concat method of an array to do so. Below script will join up the two arrays and returns a new array consists of the combination elements from the two.

var apple = ["apple", "pie"];
var pen = ["pen", "pencil!"];
var applepen = apple.concat(pen);

The following JavaScript program will take a string of integers, convert it to an array, then iterate through each element in the array and gets the total number of all elements in the array except the current number, for example if an array consisting of [1,2,3,4,5,6], then the first loop will get ( 2 + 3 + 4 + 5 + 6 ), the second will return ( 1 + 3 + 4 + 5 + 6 ) and so on. Then we find the minimum and maximum total values ​​and return them as a string.

function miniMaxSum(numberstring) {
	
	let numberlist = numberstring.split(" ");
	let numberarray = [];
	for(let i = 0; i < numberlist.length; i ++) {
		numberlist[i] = parseInt(numberlist[i]);
	} 
	
	let total = numberlist.reduce(getSum);
	let individuaktotal = 0;
	
	for(let i = 0; i < numberlist.length; i ++) {
		individuaktota = total - numberlist[i];
		numberarray.push(individuaktota);
	} 
	
	let min = Math.min(...numberarray);
	let max = Math.max(...numberarray);
	
	return min + " " + max;
}

function getSum(total, num) {
	return total + num;
}

So if we run the above code

console.log(miniMaxSum("1 2 3 4 5"))

We will get a return of “10 14”.

In ES6, it is very easy to assign the elements inside an array to any variable with the array destructuring assignment.

(function() {
	
let sum = [2,6,8];
let a,b,c;

[a, b, c] = sum;

console.log(a+b+c); //output 16

})();

As you can see the variable a,b and c get the value from the sum’s array.

In this another example, we will use the Array.map and Array.reduce methods to create an interesting program in javascript.

First, let create a program with the Array.reduce method, multiplying one element in the array with the next element in the same array.

let multiply = [1, 2, 3, 4, 5]

function multiplication(a, b) {
	return a * b;
}

console.log(multiply.reduce(multiplication)); // 1 * 2 * 3 * 4 * 5

The reduce method will introduce a function as a callback function, as you can see from the first run of the program, the value a will be 1, the value b will be 2. The second time, when the multiplication function gets called again, the value a will become 2, which is the return value of a * b, and the value b will become 3, which is the next value after the value 2 in the array.

Suppose we include an extra parameter in the reduce function, such as 1.5, then the first time it is called, its value will be 1.5 instead of the first value of the array element.

console.log(multiply.reduce(multiplication, 1.5)); // 1.5 * 1 * 2 * 3 * 4 * 5

Next we will combine the array’s map and reduce methods to create another interesting program. First, we will double the value of each element in the old array and return a new array, then we can use it’s reduce function to multiply all of it’s elements as before!

function doubler(x) {
	return x * 2;
}

console.log((vals = multiply.map(doubler)).reduce(multiplication, 1.5)); // 1.5 * 2 * 4 * 6 * 8 * 10

For simplicity, we don’t even need the vals variable and call the reduce method directly.

console.log((multiply.map(doubler)).reduce(multiplication, 1.5)); // 1.5 * 2 * 4 * 6 * 8 * 10

Below ECMA Script6 will push the values in array2 into array1.

let array1 = [1, 2, 5];
let array2 = [7];
array1.push(...array2);

array1 now becomes [ 1, 2, 5, 7 ]

Next use the Array.from method in the ECMAscript 6 to create an array from an array-like or iterable object.

The first example will create an array from a Set which contains the hello world string and a window object and then use the alert method of the window object to show that string on the browser.

var s = new Set(["hello world", window]); 
var sayHi = Array.from(s);
sayHi[1].alert(sayHi[0]);

The second example will receive a string object and turns it into an array.

var s = "hello world"
var sayHi = Array.from(s);
alert(sayHi);

Here is another Array.from method example, we will create an employees array object, loop through it while calculating the year end bonus for each of the employee object within that array object and then returning a new array with Javascript Array.from() method.

First off, lets create a new Person object with a method which will then be used to calculate the bonus.

var Person = new Object(); 

Person.income = income;

function income(salary, bonus) {
	return salary * bonus;
};

As you can see the income method of the Person object will receive two parameters, salary and bonus which will then be used to calculate the bonus.

Next we will create an employees array which contains three employee objects.

var employees = [{name : "John", salary : 2000, bonus : 1.6}, {name : "Sandy", salary : 3000, bonus : 1.5}, {name : "James", salary : 3000, bonus : 2.0}];

Finally we will create a brand new array which contains name and total bonus of each employees with the Array.from() method.

let arryofemployee = Array.from(employees, function(employeeobj) {
	return employeeobj.name + "'s year end bonus is " + this.income(employeeobj.salary, employeeobj.bonus);
}, Person);

Now lets loop though that new object and print the outcome on the console.

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

This is what we get.

John's year end bonus is 3200
Sandy's year end bonus is 4500
James's year end bonus is 6000

Array.from was added to the ECMA-262 standard in the 6th edition of ECMA so you can now use it in the major web browser such as Firefox, Chrome and Opera.

In this next example we will find the index of an array element with the Array.findIndex method which will return an index of an element within that array, the index of an array starts with 0.

let re = /\w+\s\w+/g; //search for the words with space in between

let arr = ["Hello", "Hello World", "Hello!"];

let outcome = arr.findIndex(function(value, index, array) {
	if(value.match(re)) {
		return true;
	}
}, re);

console.log(outcome);

The outcome is 1.

We can also use the ECMASCRIPT 6 Array.find() method to search for a string element which matches the Regular Expression pattern as shown below!

First create a regular expression which matches the string with space in between words.

let re = /\w+\s\w+/g;

Next is that array we are going to search for.

let arr = ["Hello", "Hello World", "Hello!"];

Finally is the Array.find method which will return the string we are searching for.

let outcome = arr.find(function(value, index, array) {
	if(value.match(re)) { 
		return true;
	}
}, re);

console.log(outcome);

Take note that the String.match method will return an array if it manages to find the string within that array but when it is within the if block the entire expression becomes true.

Here is the string we are looking for.

Hello World

In this next example we will multiply each element of an array with a value to demonstrate the use of the ECMAScript 6 Reflect.apply method.

First, lets create the function where the multiplication process will be done.

function multiplication(a) {
	let mutiply_array = [];
	this.value.forEach(function(element) {
		 mutiply_array.push(a * element);
	});
	return mutiply_array;
};

Next we will use the Reflect.apply method to call the above multiplication function and multiply each element within an array specifies in the second parameter and with the value within the array specifies in the third parameter of the Reflect.apply method.

let multiply_apply = Reflect.apply(multiplication, {value:[1,2,3,4,5]}, [3]); // multiply element by 3

console.log( multiply_apply );

The outcome is a brand new array returns by the Reflect.apply method.

[ 3, 6, 9, 12, 15 ]

As you can see all the elements within the old array has been multiplied by 3!

Too much for array it makes me feel really dizzy now lets look at the Javascript function

Javascript function is often used to carry out multiple tasks ranging from showing alert box to changing the inner html value of a webpage. Below code will create a function which will multiply two numbers passed into it and showing the result trough the alert box!

function multiply(a, b)
{
var factor = a * b;
alert(factor);
}

In order to use the above javascript multiply function all we need to do is to pass two numbers into that function and it will carry out it’s job accordingly.

multiply(3, 4);

As you can see function is actually a code block which helps us to group a set of code together. Function can have return type as well and function can either receive a parameter or without parameter. You start a function with the function keyword like so follows by the name of the function and then the open { and close }.

function hello() {
   //statement goes here.
}

Now lets look at another two functions example.

The first function will receive two variables and then return the sum of those variables which then will be printed out on the console.

/**
 * Function which return the sum of two variables
 */

function sum(a, b) {
	return a+b;
}

console.log(sum(1,2)); // the outcome is 3

The next function will not return anything but just prints the outcome.

/**
 * Function which prints the sum of two variables
 */

function sum(a, b) {
	console.log(a+b);
}

sum(4, 5); // the outcome is 9

In this next example we are going to create a function which removes those words that appear after a tag until we have reached a new line “\n”, we can pass in as many tags as possible and those words after that tag will get removed accordingly.

Here is the function.

function solution(input, markers){
	
	let partialStr = []
	let newstr = ''
	
	for(let i = 0; i < markers.length; i++) { if(i > 0) {
			newstr = input.slice(input.indexOf("\n"), input.indexOf(markers[i])).replace(/(\s+$)/g,'', "")
			partialStr.push(newstr)
		}
			
		else {
			newstr = input.slice(0, input.indexOf(markers[i])).replace(/(\s+$)/g,'') //remove empty space at the end
			partialStr.push(newstr)
		}
	
	}
	
	newstr = ''
	
	for(let j = 0; j < partialStr.length; j++) {
		//newStr += partialStr[j].replace(/(\n)/g, '\\n')
		newstr += partialStr[j]
	} 
	
	return newstr
	
  
}

So if we call the function with two parameters, a string and an array of tags like so

console.log(solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]))

we will get below phrase in return

apples, pears
grapes
bananas

The words appears in a new line because of the new line “\n” marker which appears within those words.

In this next example we will create a special function for the Javascript’s Array object which will sort all the elements in an array in the ascending order. Javascript array does provides an ascending sort method but it will only sort the characters but not the numbers. If you sort the below array with it’s sort method then you will get a strange outcome.

var numbers = [8, 94, 1, 10, 3];
console.log(numbers.sort()); // output [ 1, 10, 3, 8, 94 ]

What the above sort method of the Array object does is just to convert the number into string and then compares them with each other which will result in the above strange outcome.

So we will use this sort method instead.

var numbers = [8, 94, 1, 10, 3];
console.log(numbers.sort((a, b) => a - b)); // output [1, 3, 8, 10, 94]

Function will be the most frequently used statement in javascript so make sure you have mastered it thoroughly!

Show me the javascript prototype

Every object in javascript has the prototype properties that we can attach a new function or value to it. Below javascript program will show two alert boxes once you have loaded the webpage.

function helloWorld() {
	alert("Hello World!")
}

helloWorld.prototype.helloAgain = function(name) {
					alert("Hello " + name);
				}
								
var helloTwice = new helloWorld();

helloTwice.helloAgain("John");

First we create a function named helloWorld then we added another function (which will show the name of a person) to the helloWorld’s prototype. Next we create an object which owns all the properties of helloWorld then pass the name of a person into the helloAgain function which will then be used by that helloAgain function. The “Hello World!” alert will show first follows by the second alert in the helloAgain function after we have loaded the script.

hello world

hello john

JavaScript Object Example

Javascript object consists of properties that are an association between a name (or key) and a value (which can either be a number, boolean or a method).

The universal javascript objects such as Strings, Arrays, Dates and etc are ready to be used in our program, for example we can create a new Date object to get the current year with below statements.

var date = new Date();
var year = date.getFullYear();

Lets look at another example of the date object which can be used to display date and time.

We can either create a date object with the empty Date() constructor as shown before or another three overload versions of the Date constructors as listed below.

var todate = new Date(milliseconds);  
var todate = new Date(dateString);  
var todate = new Date(year, month, day, hour, minutes, seconds, milliseconds)  

After we have created the date object we can then use it’s method to get month, time, date or year.

var today = new Date(); // create a new date object

console.log(today.getFullYear()); // return 2018

console.log(today.getMonth()); // return month in the numerical value, for example January is 0

console.log(today.getDate()); // return today date

console.log(today.getDay()); // return day in the numerical value, for example, Saturday is 6

console.log(today.getHours()); // return hours

console.log(today.getMinutes()); // return minutes

console.log(today.getMilliseconds()); // return milliseconds

console.log(today.getSeconds()); // return seconds

console.log(today.getTime()); // returns the number of milliseconds between midnight of the January 1, 1970 and the specified date

If we are using one of the optional constructor to create a date object then we can set the year, month as well as date and time. For example,

var todate = new Date("January 1, 2019"); // take in a date string object as it's parameter

Date object is very useful for us to display date and time on our website. That is it for the javascript date object, let move on to the next example.

We will now create a custom made object and then call it’s method or return it’s value anytime we need to.

var Webserver = {

    brand : "xyz",
    loadtime : 0.5,
    price : 1.99,
    info : function() {

    	return this.brand + " loading time is " + this.loadtime + " sec, " + "and monthly price is " + this.price + " usd.";

    } 

};

//When we want to refer to that object within that object itself we will use the reserve keyword 'this'. 

alert(Webserver.info());

We can change the value of the above object as well to any value we like after we have created the object.

Webserver.price = 0.99;

Besides that, we can also create an empty object and then create the object’s properties later on.

var boy = new Object();
boy.haircolor = "Black";
boy.eyecolor = "brown";
boy.age = 10;

Another method to create a new javascript object is through creating the object template. Most javascript game developer nowadays likes to use object template to create a new object. What is an object template? Object template is just like a blueprint which we can later use to mass produce as many objects as we want from it. For example, we can create an object template of an enemy in our game.

var noobMonkey = {
	health: 100,
	shields: 50,
	strength: 100,
	strike: function() {
		// do something here
	}
};

Then we can create a new object based on this template like this…

var firstNoobMonkey = Object.create(noobMonkey);

We can even assign different property value to a different object like this…

firstNoobMonkey.strength = 50;

We can also go further to create a new property for a particular enemy at the time of it’s creation…

firstNoobMonkey.x = 30;
firstNoobMonkey.y = 30;

Template is always very useful when it comes to create a game object because of it’s “Build once and use it everywhere concept”.

Function can also be treated as an object. In this next example we will create a Javascript object from a User-Defined Function. Lets create the user-defined function first,

function person(name, salary, occupation) {
		this.name = name;
		this.occupation = occupation;
		this.salary = salary;
		this.working = working;
};

We use the this keyword in the above function to refer to the property of that function and also take note that the working property is actually a function by itself which we will declare here.

function working(company) {
	return this.company = company; // assign the company name to the property with the same property's name 
                                       // within the person function then return that property.
}

Next create a new person object with the object.create method. Take note that we need to use the new keyword when creating a new person object from the User-Defined Function. The new operator is used to create an instance of an object.

var worker = Object.create(new person("Johnny", 2000, "Programmer"));

Finally print out each property of that object within the with keyword block.

with(worker) {
	console.log(name);
	console.log(occupation);
	console.log(salary);
	console.log(working("ABC")); // calling the working function to return the name of the working company
}

The outcome is as follow

Johnny
Programmer
2000
ABC

We can easily copy all the properties of many objects into a single object using the Object.assign method introduced in ECMAScripts 6. The following example creates three objects and assigns the properties of the other two objects to the job object.

let obj1 = {
		name : "John",
		occupation : "programmer",
		salary : 3000
}

let obj2 = {
		company : "xyz",
		__proto__ : {bonus : 1.6, position : "manager"}
}

let job = {};

Object.assign(job, obj1, obj2);

console.log(job.name + " works as a " + job.occupation + " in " + job.company + " company with monthly salary of " + job.salary + " and bonus of " + job.salary * job.bonus + " in the " + job.position + " level");

The result is as follows…

John works as a programmer in xyz company with monthly salary of 3000 and bonus of NaN in the undefined level

The object attribute name can be either a string or a symbol. As you can see from above, the Object.assign method does not assign the object’s prototype property to another object, so when the job object wants To access the bonus property it will get “undefined”!

The javascript set object has been introduced in ECMAScripts 6 and just like the array it allows us to add in element or removing element from it. In below example we are going to create a set and do the adding and removing element process. First of all, lets create an instance of the set and the sum variable which we will then use to sum up all the elements within the set later on.

let counting = new Set();
let sum = 0;

Next we will add numbers into the set plus sum up all those numbers within that set.

for(let i = 0; i < 10; i++) {
	counting.add(i);
}

counting.forEach(function (number) {
	sum += number;
});

console.log(sum); // output 45

Now we will delete a random number (from 0 to 9) within that set and then get the sum again!

let number_delete = 0;

counting.delete(number_delete = Math.floor(Math.random() * 10))

sum = 0;

counting.forEach(function (number) {
	sum += number;
});

console.log("Delete number " + number_delete); // output Delete number 2
console.log(sum); // output 43

The different of set and array is that set only collect unique value while an array will allow duplicate value within that array.

In this next example we will retrieve the value of the __proto__ property of an object with the Reflect.getPrototypeOf method so we can access it later on. This method is the same as the Object.getPrototypeOf method and both have been introduced in the ECMAScript6.

var obj1 = {
		__proto__ : {
			name : "Johnny",
			salary : 3000,
			job : "programmer"
		}
};

var obj2 = Reflect.getPrototypeOf(obj1);

console.log(obj2.name + " is a " + obj2.job + " with monthly salary of " + obj2.salary);

The outcome is as follow:

Johnny is a programmer with monthly salary of 3000.

At last, do you know that String is also an object? And yes you can use the ready made String object method as well.

Next we look at Javascript class

Just like Java, Javascript has a class and we can use it just like we use the class in Java.

In this simple program we will create a javascript’s class which can be extended by it’s subclass that will use the super class method to calculate the sum of all numbers within the generator function of the subclass.

First of all let create the main Summation class.

class Summation {
	
	constructor() {
		this._sum_ = 0 // initiate the _sum_ value to 0
	}
	
	set sum(number) {
		this._sum_ += number; // perform calculation here
	}
	
	get sum() {
		return this._sum_; // get the value of the summation result
	}
}

Next we will create the subclass which will then call the function of it’s main class.

class Adding extends Summation {
	
	* generator_function() {
		yield 1000;
		yield 2000;
		yield 3000;
		yield 4000;
		yield 5000;
		yield 6000;
	}
	
	// loop through the generator function and adding all the numbers within it
	calculate_total() {
		for(let number of this.generator_function()) {
			super.sum = number;
		}
	}
	
	print_total() {
		console.log("The total is " + super.sum);
	}
}

Finally create the new instance of the Adding class then run the calculate_total function and print the total.

let add = new Adding();
add.print_total(add.calculate_total()); // The total is 21000

When we call the method of the super class we will need to use the super keyword as shown above.

In this next example we’ll create a JavaScript class that divides an array into an odd and even array with no duplicate numbers.

First let’s create a class for the empty method, which we will fill in later.

class EvenOdd {
	
	constructor(arry) {
		this.even_array = [];
		this.odd_array = [];
		this.arry = arry; // assign the raw array to this.arry 
	}
	
	// break this.arry into two group, even and odd array
	createoddevenarray() {
	}
	
	// push the number into array only if it is unique
	static insertNumber(arr, number) {
	}
	
	printArray() {
	}
	
}

What this class does here is to call the createoddevenarray method, then call the insertNumber method in the forEach method of the raw number array, and use the number in the original array as the first argument, and the odd or even array as the second argument ( Depending on whether the first argument is odd or even) to the insertNumber method. The insertNumber method will first ensure that the number is unique and then push it into an odd or even array. Finally, the createoddevenarray method will sort the elements in the odd and even arrays in ascending order. Let us now fill in the content of these two methods.

// break this.arry into two group, even and odd array
	createoddevenarray() {
		let even_array = this.even_array;
		let odd_array = this.odd_array;
		this.arry.forEach(function(number) {
			if(number % 2 == 0)
				EvenOdd.insertNumber(even_array, number);
			else
				EvenOdd.insertNumber(odd_array, number);
		});
		
		// sort the array elements into ascending order
		even_array.sort((a, b) => a - b)
		odd_array.sort((a, b) => a - b)
	}
	
	// push the number into array only if it is unuque
	static insertNumber(arr, number) {
		
		let found = arr.find(function(value, index, array) {
			 if(value == this)
				 return true;
		}, number);
		
		if(found == undefined) {
			arr.push(number);
		}
	}

Note that if we want to call the insertNumber method inside an object, then we must insert the static keyword in front of the method.

Finally, the printArray method will output odd and even arrays.

printArray() {
		console.log("odd number array is")
		console.log(this.odd_array)
		console.log("even number array is")
		console.log(this.even_array)
	}

Now let’s create an instance of the class, then split the single array into odd and even arrays and print them out on the console.

let arry = [6, 8, 40, 30, 21, 39, 8] // raw array with non unique, odd and even numbers
let even_odd_array = new EvenOdd(arry);

even_odd_array.createoddevenarray();
even_odd_array.printArray();

The result is as follows…

Odd array is
[ 21, 39 ]
Even array is
[ 6, 8, 30, 40 ]

You can further modify the above classes and convert them to the classes you need. For example, you can sort the numeric types, sort the strings, and modify the class methods slightly.

Javascript Getter method

Below javascript code will use the javascript getter syntax to show an alert box with random float value.

var random_v = Math.random();
var obj = {
	get hello() {
		return random_v;
	}
}
alert(obj.hello);

Javascript call method

Javascript’s call method looks really complicated but actually it is not as difficult as you think it is. Let takes a look at one example of how to use the javascript’s call method to show an alert box with greeting message!

Below example will show a greeting message after the web page has been loaded.

$(document).ready(function() {

function hello() {
  var hello = ['Good morning ', this.name, this.sayHello].join(' ');
  alert(hello);
}

var obj = {
  name: 'MR Noob', 
  sayHello: ', how are you today?'
};

hello.call(obj); 

});

The call method above takes one argument, which is the object that will be used in the alert method in hello function. As you can see the keyword this in the hello function will be replaced by the object after the call. That is basically what will happen when we passed an object into a call method of another object.

Let takes a look at another example, this time we will call the Computer function within the Laptop function and pass in the brand and price to the call method of the Computer function. What the below does is to show an alert box with the values we have passed in as well as using the origin property of the Laptop computer in the alert box.

jQuery(document).ready(function() {

	function Computer(brand, price) {
		
		var product_brand_price = ['I bought ', brand, ' which is made in ', this.origin, ' with $', price, '!'].join(' ');
		alert(product_brand_price);

	}

	function Laptop(brand, price) {
		this.origin = 'USA';
		Computer.call(this, brand, price);
	}

	var myPc = new Laptop("Dell", 3000);
});
Javascript call method
Javascript call method

There is one thing you need to take note of which is if you use the this keyword to represent the Computer object within the Computer object then this will no longer refer to the Laptop object anymore and thus if you call this.origin within that alert box then it will return an empty value because this will now represent the Computer object instead of the Laptop object and the Computer object does not have the origin property.

Javascript map demo

In this simple Javascript map demo example we are going to create a map object and then populate it with the key and value pair. This map object is just like the dictionary object in python, it takes in a key and a value pair where the key can then be used to access the value. The value can be anything, a variable, a function or an object. Below javascript program will create two objects, the person and his salary, then keeps both of them within a map object where those two objects can then be accessed through their related key later on.

let salary = {
		getSalary : function() {
						return this.salary;
			
		},
		setSalary : function(salary) {
						this.salary = salary;
					}
}

let person = {
		getName : function() {
						return this.name;
			
		},
		setName : function(name) {
				this.name = name;
		}
}

let map = new Map();

map.set("person", person);
map.set("salary", salary);

map.get("person").setName("John");
map.get("salary").setSalary(3000);

console.log(map.get("person").getName() + " monthly salary is " + map.get("salary").getSalary());

map.get("person").setName("Jimmy");
map.get("salary").setSalary(4000);

console.log(map.get("person").getName() + " monthly salary is " + map.get("salary").getSalary());

The program above returns the below outcome…

John monthly salary is 3000
Jimmy monthly salary is 4000

The variable such as name will be created for us when we set it’s value for the first time!

Create a generator with the generator function

Generator function is a new function introduces in ECMAScript6. The generator function will return many values one by one and in this example we will create a generator function and then get the generator object which can then be used to return those values within the generator function.

function* generator_function() {
	yield 1; // the function uses yield keyword to store it's values.
	yield 2;
	yield 3;
}

let generator = generator_function();

console.log(generator.next().value);
console.log(generator.next().value);
console.log(generator.next().value);
console.log(generator.next().done);

The outcome is as follow:

1
2
3
true

Take note that if there is no more value lefts to return then the function will return undefined and if you are at the last value you can check the done property of that generator object to see whether is it true (no more value to return) or false.

Javascript destructuring assignment in action

The destructuring assignment has been introduced in ECMAScripts 6 and has now been supported by all the major browsers. Basically what this assignment does is to assign the value on the right hand side to the value which has the same name or property name on the left hand side. For example, we can assign the value of a property within an object to the property value within an object with the same property name on the left hand side as follow.

let {value : x} = {value : 30}

console.log(x) // output 30

This is indeed very convenient and saves us lot of unnecessary lines of code. Besides object, we can also use destructuring assignment on the array as well, below is a full example which uses the destructuring assignment on both the array and object to print out the details of a worker and then calculate his salary and bonus.

let personal = {
		jobTitle({name = 'Bob', age = 33, job = 'software engineer'} = {}, [salary, bonus] = [2000, 1.3]) {
			console.log(name + " is " + age + " and works as a " + job);
			console.log("Monthly income is " + salary + " and bonus is " + bonus * salary + " USD.");
		}
}

let income = [3000, 1.6];

personal.jobTitle({}, income); // if pass in empty object, the default object will be used

personal.jobTitle({name : 'Jonny', age : 20, job : 'web developer'}); // if pass in empty array, the default array will be used instead

The outcome is as follow…

Bob is 33 and works as a software engineer
Monthly income is 3000 and bonus is 4800 USD.
Jonny is 20 and works as a web developer
Monthly income is 2000 and bonus is 2600 USD.

Take note that we use the equal sign within the jobTitle function to assign the default value to both the object and the array object which will be used if undefined, empty (or no parameter) has been passed into the function.

Avoid extra stack creation with Tail call function

With the below method we will be able to remove the stack creation of the inner function and use the stack of the outer function instead!

"use strict"

function _mul(a, b) {
   return (a * b);
}

function multiply(a, b) {
   return _mul(a, b);
}

It seems like you are not talking about String class which is very important in Javascript

After all the writing we have finally reached the end of this article, since I have mentioned String before but not touch on it that much, let me write one SearchString class program to show you what are those String methods we can use in our program to search for word within a string as well as repeats a string several times with this program. The comments in the program will explain the entire contents of this program, just remember one thing, the search index position starts from zero.

class SearchString {
	
	constructor(string) {
		this.string = string
	}
	
	repeated(index) {
		console.log(this.string.repeat(index))
	}
	
	contain(string) {
		console.log(this.string.includes(string))
	}
	
	startWith(string, index) {
		console.log(this.string.startsWith(string, index)) // provide the index where to start the search
	}
	
	endWith(string, index) {
		console.log(this.string.endsWith(string, index)) // the index should be one position above the end string which you want to search for
	}
}

let search = new SearchString("Hello World!")

search.contain(".") // return false

search.startWith("llo", 2) // return true

search.endWith("o", 12) // return false

search.repeated(3) // Hello World!Hello World!Hello World!

The above string method has been introduced in ECMAScripts 6 and now is widely supported by all major web browsers!

Alright, that is about it for this article, if you like it then don’t forget to rate this article to show your warm appreciation, thank you very much!

Our Reader Score
[Total: 1 Average: 5]
Our Own Score
0

Leave a Reply

avatar
  Subscribe  
Notify of