Built in objects in javascript

Global Objects In browser, window is the global object. All variables and functions defined inside script become members of the window object in browser. In Nodejs environment, variables in the script are scoped to module only. Built in Objects There are several built in objects as mentioned below.
  • Date - used to work with dates
  • RegEx - used to work with regular expressions
  • Math - This object provides mathematical functions
  • Error object
  • JSON object
  • Set and Weakset
  • Map and Weakmap

Date object

Date is a function and as you know, functions are first class objects in JavaScript. This means that we can call Date function. e.g. Date() - returns the current date and time.

console.log(Date());
let currDate = new Date();
console.log("Day number in a month -> " + currDate.getDate());
console.log("Day number in a week -> " + currDate.getDay());
console.log("Current Month number -> " + currDate.getMonth());
console.log("Current Year -> " + currDate.getFullYear());
console.log("Current time -> " + currDate.getTime());
console.log("Current Hour time -> " + currDate.getHours());
console.log("Current Minutes time -> " + currDate.getMinutes());
console.log("Current Seconds time -> " + currDate.getSeconds());
console.log("Current Milliseconds time -> " + currDate.getMilliseconds());

let d1 = new Date("8-mar-2022"); //dd-mmm-yyyy
console.log("Date from string -> ", d1);

d1 = new Date("08-03-2022"); //mm-dd-yyyy
console.log("Date from string -> ", d1);

d1 = new Date("2022-03-08"); //yyyy-mm-ddTHH:MM:SSZ - ISO format
console.log("Date from string -> ", d1);

d1 = new Date("2022-03-08T00:00:00+10:00"); //yyyy-mm-ddTHH:MM:SSZ - ISO format
console.log("Date from string -> ", d1);

// Get current date
d1 = new Date();
console.log("Date now -> ", d1);

//convert string to date
let sec = Date.parse("March 8, 2022");
d1 = new Date(sec);
console.log("Date after parsing -> ", d1);

sec = Date.parse("12/3/2022"); //mm/dd/yyyy
d1 = new Date(sec);
console.log("Date after parsing -> ", d1);

//calculate elapsed time
let start = Date.now();
let end = Date.now();
let elapsed = end - start; // elapsed time in
console.log("elapse time ", elapsed);

Regex object

Regular expressions can be created in 2 ways. 1. /regular-expression/modifiers 2. new regEx() Regular expressions using literal expressions Below example illustrates how to use regular expressions in JavaScript. In this example - we are searching for any letter from a to e.

     
     var data = "Trump hits record";
     var regExp = /([abcde])/g
     var match;
     while (match = regExp.exec(data))
     {
     console.log("Match ", match[1], "found at", match.index);
     }
We can have below types of modifiers.
  • "g" modifier is used when you want to match the pattern at global level (all matches).
  • "i" modifier is used if you want to match the pattern in case insensitive manner.
  • "m" modifier is used when you want to match the pattern on multiple lines.
Regular expression object has below methods.
  • test() - This method returns true if the pattern is found in the string, otherwise it returns false.
  • exec() - This method returns the first match in the string. If match is not found, it returns null.
When you use constructor for regular expression, you will have to escape "\" character.

Math object

Mathematical operations can be done using Math class.

//To get the absolute value, you can use below line of code.
console.log("Absolute value of a -> " + Math.abs(a))

//To get the ceiling of a number, you can use below line of code
console.log("Ceiling value of a -> " +Math.ceil(a))

//To get the floor of a number, you can use below line of code
console.log("Floor value of a -> " +Math.floor(a))

//To get the square root of a number, you can use below line of code.
console.log("Square root value of a -> " +Math.sqrt(625))
 
//To find the maximum of 2 numbers, you can use below line of code.
console.log("max between a and b -> " +Math.max(a,b))

//To find the minimum of 2 numbers, you can use below line of code.
console.log("Min value between a and b -> " +Math.min(a,b))

//To get the power of a number, you can use below line of code.
console.log("a raised to power b -> " + Math.pow(a,b))

//To get the random number between 0 and 1, you can use below method random()
console.log("Random number between 0 and 1 -> " + Math.random())
 
//To round the number, you can use below line of code. Note that round method returns the integer.
console.log("Round value of a -> " + Math.round(a))

//exp method returns the value of e^a
console.log("Exponent of a -> " + Math.exp(a))

//To get the log of a to base e, you can use below line of code.
console.log("Log of a " + Math.log(a))

//Math class also provides Trigonometric methods as mentioned below.
//Math.sin(a), Math.cos(a), Math.tan(a), Math.acos(a)


Error object

Error object is thrown when any error occurs in JavaScript. Error object has 2 properties.
  • name
  • message
There can be below types of errors in JavaScript.
  • ReferenceError
  • SyntaxError
  • TypeError
  • RangeError
  • EvalError
  • URIError
Example on Error Object is given below. In below example, since we have not defined x earlier in the code, error will be thrown. In catch block, we can handle that error.

try {
       console.log("Checking exception" + x);
}
catch(error) {
       console.log("Error message -> " + error.message);
}
finally{
        console.log("Finally block is always executed no matter error is thrown or not in try block!!");
}

//Throwing custom error
//Below example illustrates how to throw custom error in JavaScript.
try{
      var balance=0;
     if (balance==0)
       {
          throw new Error("balance is 0")
        }
}catch(err){
         console.log("Error thrown -> " + err.message)
}

JSON object

JSON stands for JavaScript object notation. JSON can be converted into JavaScript object and vice versa.
  • JSON to JS object - You can use JSON.parse method to convert JSON string into JS Object
  • JS object to JSON - You can use JSON.stringify method to convert the JS object into JSON string

JSON vs JS object differences

JavaScript object and JSON are very similar but there are some major differences between them.
  • In JSON, properties and string values are put in double quotes
  • In JSON, only strings can be used for property names
  • JavaScript object can have functions as property values but in JSON, we do not have such thing.

var carJSON = '{ "cars" : [' +
'{ "name":"i30" , "manufacturer":"Huyndai" },' +
'{ "name":"A8" , "lastName":"Audi" } ]}';

var jsonObject = JSON.parse(carJSON)
console.log ("first car name -> " + jsonObject.cars[0].name)

Set and WeakSet

Set is unique collection of objects. Difference between Set and WeakSet is that in WeakSet, garbage collection may happen when object stored in set gets out of scope. Sets can store primitive as well as non primitive values. Weakset stores only objects. WeakSet does not have size property and methods like keys, values, clear,entries etc.

let set = new Set();

let a = [11, 22, 33, 44];
let user = { name: "sagar" };
let car = { name: "Tesla" };
set.add(a);
set.add(user);
set.add(user);
set.add(car);
set.add(car);

console.log(set.size);

for (let o of set) {
  console.log(o);
}
/*
Output ->
3
[ 11, 22, 33, 44 ]
{ name: 'sagar' }
{ name: 'Tesla' }

*/

//to get unique values from array
//Array.from(new Set(arr));

Map and WeakMap

Map is collection of objects as key and values. Difference between Map and WeakMap is that in WeakMap, garbage collection may happen when object stored in map gets out of scope.

//map
let map = new Map();
map.set("Name", "Sagar");
map.set(10, "Tendulkar");
map.set(true, "Raining");
console.log(map);
/*
Output ->
Map(3) { 'Name' => 'Sagar', 10 => 'Tendulkar', true => 'Raining' }
*/

Web development and Automation testing

solutions delivered!!