Categories
JavaScript Tutorials

Functions that return Functions

As mentioned earlier, a function always returns a value, and if it doesn’t do it explicitly with return, then it does so implicitly by returning undefined.

A function can return only one value and this value could just as easily be another function.

function a() {
  alert('A!');
  return function(){
    alert('B!');
  };
}

In this example the function a() does its job (says A!) and returns another function that does something else (says B!). You can assign the return value to a variable and then use this variable as a normal function:

var newFunc = a();
newFunc();

Here the first line will alert A! and the second will alert B!.

If you want to execute the returned function immediately, without assigning it to a new variable, you can simply use another set of parentheses. The end result will be the same.

a()();
Categories
JavaScript Tutorials

Inner (Private) Functions

Bearing in mind that a function is just like any other value, there’s nothing that stops you from defining a function inside another function.

function a(param) {
  function b(theinput) {
    return theinput * 2;
  };
  return 'The result is ' + b(param);
};

Using the function literal notation, this can also be written as:

var a = function(param) {
  var b = function(theinput) {
    return theinput * 2;
  };
  return 'The result is ' + b(param);
};

When you call the global function a(), it will internally call the local function b(). Since b() is local, it’s not accessible outside a(), so we can say it’s a private function.

a(2)
//"The result is 4"
a(8)
//"The result is 16"
b(2)
//b is not defined

The benefit of using private functions are as follows:

  • You keep the global namespace clean (smaller chance of naming collisions).
  • Privacy—you expose only the functions you decide to the “outside world”, keeping to yourself functionality that is not meant to be consumed by the rest of the application.
Categories
JavaScript Tutorials

Self-invoking Functions

So far we have discussed using anonymous functions as callbacks. Let’s see another application of an anonymous function—calling this function right after it was defined. Here’s an example:

(function(){
  alert('boo');
})();

The syntax may look a little scary at first, but it’s actually easy—you simply place an anonymous function definition inside parentheses followed by another set of parentheses. The second set basically says “execute now” and is also the place to put any parameters that your anonymous function might accept.

(function(name){
  alert('Hello ' + name + '!');
})('dude')

One good reason for using self-invoking anonymous functions is to have some work done without creating global variables. A drawback, of course, is that you cannot execute the same function twice (unless you put it inside a loop or another function). This makes the anonymous self-invoking functions best suited for one-off or initialization tasks.

Categories
JavaScript Tutorials

Invocation Expressions

An invocation expression is JavaScript’s syntax for calling (or executing) a function or method. It starts with a function expression that identifies the function to be called. The function expression is followed by an open parenthesis, a comma-separated list of zero or more argument expressions, and a close parenthesis. 

Some examples:

f(0) // f is the function expression; 0 is the argument expression.
Math.max(x,y,z) // Math.max is the function; x, y and z are the arguments.
a.sort() // a.sort is the function; there are no arguments.
Categories
JavaScript Tutorials

Function Definition Expressions

A function definition expression defines a JavaScript function, and the value of such an expression is the newly defined function. In a sense, a function definition expression is a “function literal” in the same way that an object initializer is an “object literal”. A function definition expression typically consists of the keyword function followed by a comma-separated list of zero or more identifiers (the parameter names) in parentheses and a block of JavaScript code (the function body) in curly braces. For example:

// This function returns the square of the value passed to it.
var square = function(x) { return x * x; }
Categories
JavaScript Tutorials

Object and Array initializers

Object and array initializers are expressions whose value is a newly created object or array. These initializer expressions are sometimes called “object literals” and “array literals.” Unlike true literals, however, they are not primary expressions, because they include a number of subexpressions that specify property and element values. Array initializers have a slightly simpler syntax, and we’ll begin with those. An array initializer is a comma-separated list of expressions contained within square brackets. The value of an array initializer is a newly created array. The elements of this new array are initialized to the values of the comma-separated expressions:

[] // An empty array: no expressions inside brackets means no elements
[1+2,3+4] // A 2-element array. First element is 3, second is 7

Object initializer expressions are like array initializer expressions, but the square brackets are replaced by curly brackets, and each subexpression is prefixed with a property name and a colon:

var p = { x:2.3, y:-1.2 }; // An object with 2 properties

var q = {}; // An empty object with no properties
q.x = 2.3; q.y = -1.2; // Now q has the same properties as p
Categories
JavaScript Tutorials

The RegExp Object

Regular expressions provide a powerful way to search and manipulate text. If you’re familiar with SQL, you can think of regular expressions as being somewhat similar to SQL: you use SQL to find and update data inside a database, and you use regular expressions to find and update data inside a piece of text. Different languages have different implementations (think “dialects”) of the regular expressions syntax. JavaScript uses the Perl 5 syntax. Instead of saying “regular expression”, people often shorten it to “regex” or “regexp”. A regular expression consists of:

  • A pattern you use to match text
  • Zero or more modifiers (also called flags) that provide more instructions on how the pattern should be applied

The pattern can be as simple as literal text to be matched verbatim, but that is rare and in such cases you’re better off using indexOf(). Most of the times, the pattern is more complex and could be difficult to understand. Mastering regular expressions patterns is a large topic, which won’t be discussed in details here; instead, you’ll see what JavaScript provides in terms of syntax, objects and methods in order to support the use of regular expressions. JavaScript provides the RegExp() constructor which allows you to create regular expression objects.

var re = new RegExp("j.*t");

There is also the more convenient regexp literal:

var re = /j.*t/;

In the example above, j.*t is the regular expression pattern. It means, “Match any string that starts with j, ends with t and has zero or more characters in between”. The asterisk * means “zero or more of the preceding”; the dot (.) means “any character”. The pattern needs to be placed in quotation marks when used in a RegExp() constructor.

Properties of the RegExp Objects

The regular expression objects have the following properties:

  • global: If this property is false, which is the default, the search stops when the first match is found. Set this to true if you want all matches.
  • ignoreCase: Case sensitive match or not, defaults to false.
  • multiline: Search matches that may span over more than one line, defaults to false.
  • lastIndex: The position at which to start the search, defaults to 0.
  • source: Contains the regexp pattern.

None of these properties, except for lastIndex, can be changed once the object has created.

The first three parameters represent the regex modifiers. If you create a regex object using the constructor, you can pass any combination of the following characters as a second parameter:

  • “g” for global
  • “i” for ignoreCase
  • “m” for multiline

These letters can be in any order. If a letter is passed, the corresponding modifier is set to true. In the following example, all modifiers are set to true:

var re = new RegExp('j.*t', 'gmi');

Let’s verify:

re.global;
//true

Once set, the modifier cannot be changed:

re.global = false;
re.global
//true

To set any modifiers using the regex literal, you add them after the closing slash.

var re = /j.*t/ig;
re.global
//true

Methods of the RegExp Objects

The regex objects provide two methods you can use to find matches: test() and exec(). They both accept a string parameter. test() returns a boolean (true when there’s a match, false otherwise), while exec() returns an array of matched strings. Obviously exec() is doing more work, so use test() unless you really need to do something with the matches. People often use regular expressions for validation purposes, in this case test() would probably be enough.

//No match, because of the capital J:
var re = /j.*t/;
re.test("Javascript");
//false

//Case insensitive test gives a positive result:var re = /j.*t/i;
re.test("Javascript");
//true

The same test using exec() returns an array and you can access the first element as shown below:

var re = /j.*t/i;
re.exec("Javascript")[0]
//"Javascript"

String Methods that Accept Regular Expressions as Parameters

Previously in this chapter we talked about the String object and how you can use the methods indexOf() and lastIndexOf() to search within text. Using these methods you can only specify literal string patterns to search. A more powerful solution would be to use regular expressions to find text. String objects offer you this ability.

The string objects provide the following methods that accept regular expression objects as parameters:

  • match() returns an array of matches
  • search() returns the position of the first match
  • replace() allows you to substitute matched text with another string
  • split() also accepts a regexp when splitting a string into array elements

search() and match()

Let’s see some examples of using the methods search() and match(). First, you create a string object.

var s = new String('HelloJavaScriptWorld');

Using match() you get an array containing only the first match:

s.match(/a/);
//["a"]

Using the g modifier, you perform a global search, so the result array contains two elements:

s.match(/a/g);
/*['a', 'a']*/

Case insensitive match:

s.match(/j.*a/i);
//["Java"]

The search() method gives you the position of the matching string:

s.search(/j.*a/i);
//5

replace()

replace() allows you to replace the matched text with some other string. The following example removes all capital letters (it replaces them with blank strings):

s.replace(/[A-Z]/g, '');
//"elloavacriptorld"

If you omit the g modifier, you’re only going to replace the first match:

s.replace(/[A-Z]/, '');
//"elloJavaScriptWorld"
Categories
JavaScript Tutorials

The Date Object

Date() is a constructor function that creates date objects. 

You can create a new object by passing:

  • Nothing (defaults to today’s date)
  • A date-like string
  • Separate values for day, month, time, and so on
  • A timestamp

An object instantiated with today’s date/time:

new Date()
//Fri Mar 04 2022 16:55:52 GMT+0530 (India Standard Time)

(As with all objects, the console displays the result of the toString() method, so this long string “Fri Mar 04….” is what you get when you call toString() on a date object.)

Here are some examples of using strings to initialize a date object. It’s interesting how many different formats you can use to specify the date.

new Date('2009 11 12')
//Thu Nov 12 2009 00:00:00 GMT+0530 (India Standard Time)
new Date('1 1 2012')
//Sun Jan 01 2012 00:00:00 GMT+0530 (India Standard Time)
new Date('1 mar 2012 5:30')
//Thu Mar 01 2012 05:30:00 GMT+0530 (India Standard Time)

It is good that JavaScript can figure out a date from different strings, but this is not really a reliable way of defining a precise date. The better way is to pass numeric values to the Date() constructor representing:

  • Year
  • Month: 0 (January) to 11 (December)
  • Day: 1 to 31
  • Hour: 0 to 23
  • Minutes: 0 to 59
  • Seconds: 0 to 59
  • Milliseconds: 0 to 999

Let’s see some examples.

//Passing all the parameters:
new Date(2008, 0, 1, 17, 05, 03, 120)
//Tue Jan 01 2008 17:03 GMT+0530 (India Standard Time)

//Passing date and hour:
new Date(2008, 0, 1, 17)
//Tue Jan 01 2008 17:00:00 GMT+0530 (India Standard Time)

Methods to Work with Date Objects

Once you’ve created a date object, there are lots of methods you can call on that object. Most of the methods can be divided into set() and get() methods. For example getMonth(), setMonth(), getHours(), setHours(), and so on. Let’s see some examples.

//Creating a date object:
var d = new Date();
d.toString();
//"Wed Jan 09 2008 00:26:39 GMT+0530 (India Standard Time)"

//Setting the month to March (months start from 0):
d.setMonth(2);
1205051199562
d.toString();
//"Fri Mar 04 2022 16:55:52 GMT+0530 (India Standard Time)"

//Getting the month:
d.getMonth();
//2

In addition to all the methods of the date instances, there are also two methods that are properties of the Date() function/object. These do not need a date instance; they work just like Math’s methods. In class-based languages, such methods would be called “static” because they don’t require an instance.

//Date.parse() takes a string and returns a timestamp
Date.parse('Jan 1, 2008')
//1199174400000

//Date.UTC() takes all parameters for year, month, day, and so on, and produces a timestamp in Universal time.
Date.UTC(2008, 0, 1)
//1199145600000

Examples

Print the current date in ‘date/month/year’ format using the Date object.

var mydate = new Date();
var date = mydate.getDate();
var month = mydate.getMonth()+1;
var year = mydate.getFullYear();
console.log(date+"/"+month+"/"+year);

Create a digital clock that shows hours, minutes, seconds and milliseconds.

<h1 id='d1'></h1>
<script>            
	setInterval(function(){
		var d = new Date();
		var clocktime = document.getElementById('d1');
		clocktime.innerHTML = d.getHours()+":"+d.getMinutes()+":"+d.getSeconds()+":"+d.getMilliseconds();
	},100);
</script>

Write a program to take the DOB of a person as input and print the current age of the person in the console.

<html>
    <input type="date" onchange="getAge(event)" id="d1">
    <script>
        function getAge(e){
            var dob = new Date(e.target.value)
            var today = new Date();
            var currentAge = (today.getTime()-dob.getTime())/(1000*60*60*24*365);
            console.log(currentAge);
        }
    </script>
</html>

Write a program to create a check-in/check-out system for employees that can show the time duration the employee was in.

<script>
	var times = [];
	var totalTime = 0;
	function checkin(){
		times.push(Date.now());
		console.log(times);
	}
	function checkout(){
		totalTime=0;
		times.push(Date.now());
		for(let i=0;i<=times.length-1;i=i+2){
			totalTime = totalTime+(times[i+1]-times[i])
		}
		document.getElementById('tt').innerHTML = totalTime/1000+"seconds"
		console.log(times);
	}
	var d1 = new Date();
	var cdate = d1.getDate();
	var cmonth = d1.getMonth();
	var cyear = d1.getFullYear();
	var el = document.getElementById('d1');
	el.innerHTML = cdate+"/"+cmonth+"/"+cyear;
	setInterval(function(){
		var d1 = new Date();
		var chours = d1.getHours();
		var cminutes = d1.getMinutes();
		var csec = d1.getSeconds();
		var el2 = document.getElementById("d2");
		el2.innerHTML = (chours<10?'0'+chours:chours)+":"+(cminutes<10?'0'+cminutes:cminutes)+":"+(csec<10?'0'+csec:csec);
	},1000)
</script>
Categories
JavaScript Tutorials

Reduction Methods

JavaScript also introduced two reduction methods for arrays: reduce() and reduceRight(). Both methods iterate over all items in the array and build up a value that is ultimately returned.

The reduce() method does this starting at the first item and traveling toward the last, whereas reduceRight() starts at the last and travels toward the first. Both methods accept two arguments: a function to call on each item and an optional initial value upon which the reduction is based. The function passed into reduce() or reduceRight() accepts

four arguments: the previous value, the current value, the item’s index, and the array object. Any value returned from the function is automatically passed in as the first argument for the next item. The first iteration occurs on the second item in the array, so the first argument is the first item in the array and the second argument is the second item in the array.

You can use the reduce() method to perform operations such as adding all numbers in an array. Here’s an example:

var values = [1,2,3,4,5];
var sum = values.reduce(function(prev, cur, index, array){
return prev + cur;
});
alert(sum); //15

The first time the callback function is executed, prev is 1 and cur is 2. The second time, prev is 3 (the result of adding 1 and 2), and cur is 3 (the third item in the array). This sequence continues until all items have been visited and the result is returned. The reduceRight() method works in the same way, just in the opposite direction. Consider the following example:

var values = [1,2,3,4,5];
var sum = values.reduceRight(function(prev, cur, index, array){
return prev + cur;
});
alert(sum); //15

Examples

Take an array of numbers and print the sum of all the numbers using reduce method.

var ar = [12,33,66,24,56,34,21];

var total = ar.reduce(function(a,b){           
	return a+b;
});
console.log(total);

Take an array of numbers and find out the maximum number in the array using the reduce method.

var ar = [1,22,13,14,5,16,7,8];

var max = ar.reduce(function(a,b){
  if(a<b){
	return b;
  }
  else{
	return a;
  }
});
console.log(max);

Take an array of objects containing name and salary of a few people and find out the average salary using the reduce method.

var employees = [
	{
		name:'Hari',
		sal:40000
	},
	{
		name:'Ravi',
		sal:45000
	},
	{
		name:'Kishore',
		sal:60000
	},
	{
		name:'Madan',
		sal:52000
	}
];

var totalSalary= employees.reduce(function(a,b){
	if(a instanceof Object){
		return a.sal+b.sal
	}
	else{
		return a+b.sal;
	}
});
console.log("Avg Salary::",totalSalary/employees.length);
Categories
JavaScript Tutorials

Conversion Methods

As mentioned previously, all objects have toLocaleString(), toString(), and valueOf() methods. The toString() and valueOf() methods return the same value when called on an array.

The result is a comma-separated string that contains the string equivalents of each value in the array, which is to say that each item has its toString() method called to create the final string. Take a look at this example:

var colors = ["red", "blue", "green"]; //creates an array with three strings
alert(colors.toString()); //red,blue,green
alert(colors.valueOf()); //red,blue,green
alert(colors); //red,blue,green

In this code, the toString() and valueOf() methods are first called explicitly to return the string representation of the array, which combines the strings, separating them by commas. The last line passes the array directly into alert(). Because alert() expects a string, it calls toString() behind the scenes to get the same result as when toString() is called directly.

The toLocaleString() method may end up returning the same value as toString() and valueOf(), but not always. When toLocaleString() is called on an array, it creates a comma delimited

string of the array values. The only difference between this and the two other methods is that toLocaleString() calls each item’s toLocaleString() instead of toString() to get its string value. Consider the following example:

var person1 = {
  toLocaleString : function () {
    return 'Nikolaos';
  },
  toString : function() {
    return 'Nicholas';
  }
};
var person2 = {
  toLocaleString : function () {
    return 'Grigorios';
  },
  toString : function() {
    return 'Greg';
  }
};
var people = [person1, person2];
alert(people.toString()); //Nicholas,Greg
alert(people.toLocaleString()); //Nikolaos,Grigorios

Here, two objects are defined, person1 and person2. Each object defines both a toString() method and a toLocaleString() method that return different values. An array, people, is created

to contain both objects. When passed into alert(), the output is “Nicholas,Greg”, because the toString() method is called on each item in the array (the same as when toString() is

called explicitly on the next line). When toLocaleString() is called on the array, the result is “Nikolaos,Grigorios”, because this calls toLocaleString() on each array item. The inherited methods toLocaleString(), toString(), and valueOf() each return the array items as a comma-separated string. It’s possible to construct a string with a different separator using

the join() method. The join() method accepts one argument, which is the string separator to use, and returns a string containing all items. Consider this example:

var colors = ['red', 'green', 'blue'];
alert(colors.join(',')); //red,green,blue
alert(colors.join('||')); //red||green||blue

Here, the join() method is used on the colors array to duplicate the output of toString(). By passing in a comma, the result is a comma-separated list of values. On the last line, double pipes are passed in, resulting in the string “red||green||blue”. If no value or undefined is passed into the join() method, then a comma is used as the separator. Internet Explorer 7 and earlier incorrectly use the string “undefined” as the separator.