Create a date object
By default, Date uses the browser’s time zone and display a date as a full text string: Tue Oct 27 2020 22:52:28 GMT-0600 (Mountain Daylight Time)
new Date() new Date(year, month, day, hours, minutes, seconds, milliseconds) new Date(milliseconds) new Date(date string)
new Date() creates a new date object with the current date and time.
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(year, month, day, hours, minutes, seconds, milliseconds) new Date(year, month, day, hours, minutes, seconds) new Date(year, month, day, hours, minutes) new Date(year, month, day, hours) new Date(year, month, day) new Date(year, month) new Date(year)
Create UTC date
Use new Date(string) constructor. String must be in this format YYYY-MM-DDTHH:MM:SSZ. Note the T in the middle and Z at the end.
let date = new Date("2020-08-25T00:00:00Z")
UTC to local Date and Time
Use the toLocaleDateString() method and the toLocaleTimeString() method together. The method toLocaleDateString() returns a transformation of UTC date to local date in this format (month/day/year). The toLocaleTimeString() returns a transformation of UTC time to local time in this format hour:minute:second AM/PM (11:30:59 PM)
In many cases, API servers return dates in UTC and clients translate UTC dates to local dates.
new Date(data.createdAt).toLocaleDateString()+" "+new Date(data.createdAt).toLocaleTimeString()
data.createdAt and data.updatedAt are in this format YYYY-MM-DDTHH:MM:SSZ
An object is a collection of properties , defined as a key-value pair. Each property has a key and a value. The property key can be a string and the property value can be any valid value.
Create an object
You can use {} or the new Object().
let object = {} object.name = "Folau"; object.age = 33; // or let obj = new Object(); obj.name = "Folau"; obj.age = 33;
let user = { "name": "Folau", "age": 33 } console.log("user: ", user);//{"name":"Folau","age":33}
Access field value with dot(.)
let user = { "name": "Folau", "age": 33 } console.log("user name: ", user.name);//Folau
Access field value with []
let user = { "name": "Folau", "age": 33 } console.log("user name: ", user['name']);//Folau
Remove or delete a key value with delete.
let user = { "name": "Folau", "age": 33 } console.log("user: ", user);//{"name":"Folau","age":33} /* * To remove a property, we can use delete operator. */ delete user.age; console.log("user: ", user);{"name":"Folau"}
let user = { "name": "Folau", "age": 33 } console.log("user: ", user);//{"name":"Folau","age":33} let doesUserHaveName = ("name" in user); console.log("name in user: ", doesUserHaveName);//true let doesUserHaveAddress = ("address" in user); console.log("address in user: ", doesUserHaveAddress);//false
let user = { "name": "Folau", "age": 33 } for(let field in user){ console.log("field: ", field, ", value: ", user[field]); } //Output field: name , value: Folau field: age , value: 33
Objects are mutable
let user = { "name": "Folau", "age": 33 } let member = user; member.name = "Lisa"; console.log("user: ", user);//{"name":"Lisa","age":33} console.log("member: ", member);//{"name":"Lisa","age":33}
The object member is not a copy of user. It is user. Both member and user are the same object.
Any changes to member will also change user, because member and user are the same object.
Clone objects
Use object.assign(target, source…). By cloning an object, changes to that object do not reflect on the original object.
let person = { name:"Folau", age: 33, score: { sc: 100 } } console.log("person ", person);//{name: "Folau", age: 33, score: {sc: 100}} person.score.sc = 25; /* * Clone objects */ let lau = Object.assign({}, person); console.log("lau", lau);//{name: "Folau", age: 33, score: {sc: 25}}
Object.assign does not copy nested objects.
copyObject(obj){ let jsonString = JSON.stringify(obj); return JSON.parse(jsonString); }
Classes are a template for creating objects. They encapsulate data with code to work on that data. You first need to declare your class and then access it, otherwise code like the following will throw a ReferenceError
.
/* * Classes are a template for creating objects. They encapsulate data with code to work on that data * Reference - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes */ class User{ //private fields are declared with # #name; #dob; #type; static USER_TYPE = "USER_TYPE"; static ADMIN_TYPE = "ADMIN_TYPE"; /* * The constructor method is a special method: * It has to have the exact name "constructor" * It is executed automatically when a new object is created * It is used to initialize object properties * It if you do not define a constructor method, JavaScript will add an empty constructor method. */ constructor(name, dob, type) { this.name = name; this.dob = dob; if(type==undefined){ this.type = User.USER_TYPE; }else{ this.type = type; } } getAge(date){ return date.getFullYear() - this.dob.getFullYear(); } getDob(){ return this.dob; } static getAgeDifference(user1, user2){ return user1.getDob().getFullYear() - user2.getDob().getFullYear(); } } let folau = new User("Folau",new Date(1986, 12, 03)); console.log("Folau: ", folau); console.log("Folau age: ", folau.getAge(new Date())); let lisa = new User("Lisa",new Date(1987, 04, 12)); console.log("Lisa: ", lisa); let ageDifference = User.getAgeDifference(folau, lisa); console.log("ageDifference: ", ageDifference);
Private instance fields and methods are declared with # names (pronounced “hash names“), which are identifiers prefixed with #
. The #
is a part of the name itself. It is used for declaration and accessing as well.
#name; #dob; #type;
The static keyword defines static methods and variabls for classes.
Static methods and variables are called directly on the class(using the Class name) – without creating an instance/object of the class.
static USER_TYPE = "USER_TYPE"; static ADMIN_TYPE = "ADMIN_TYPE"; static getAgeDifference(user1, user2){ return user1.getDob().getFullYear() - user2.getDob().getFullYear(); }
The extends keyword is used to create a child class of another class (parent). The child class inherits all the methods from another class. Inheritance is useful for code reusability: reuse properties and methods of an existing class when you create a new class.
Note: From the example above; The super() method refers to the parent class. By calling the super() method in the constructor method, we call the parent’s constructor method and gets access to the parent’s properties and methods.
class Member extends User{ id; constructor(id, name, dob, type) { super(name, dob, type); this.id = id; } getId(){ return this.id; } getNext5yearAge(){ let dob = super.getDob(); let today = new Date(); return (today.getFullYear() - dob.getFullYear()) + 5;; } } let laulau = new Member(100, "Laulau",new Date(1986, 12, 03)); console.log("laulau: ", laulau); /* dob: Sat Jan 03 1987 00:00:00 GMT-0700 (Mountain Standard Time) {} id: 100 name: "Laulau" type: "USER_TYPE" */ laulau.id = 250; console.log("laulau id: ", laulau.getId());// 250 console.log("laulau age: ", laulau.getAge(new Date()));// 33 console.log("laulau age in 5 years: ", laulau.getNext5yearAge());// 38
Call super class constructor using super(…);
constructor(id, name, dob, type) { super(name, dob, type); this.id = id; }
Call super class method using super.methodName();
getNext5yearAge(){ let dob = super.getDob(); let today = new Date(); return (today.getFullYear() - dob.getFullYear()) + 5;; }
A function is a block of code designed to perform a certain task. A function is run when it’s invoked or called by an action. functions are very important because they are written once and can be executed multiple times. They save you a lot of development time in that you don’t have to repeat writing the code in the function in multiple places where you need it.
Syntax
function add(num1, num2){ let sum = num1 + num2; return sum; }
Parameters
Function definitions do not specify data types for parameters. Functions do not perform type checking on the passed arguments. Functions do not check the number of arguments received. Parameters that are not objects are passed by value. Parameters that are objects are passed by reference which means, changes to them will reflect every where.
let user = { "name":"Folau" } function changeToRandomName(user){ user.name = "Lisa"; console.log("user:",user); } console.log("user:",user);//{name: "Folau"} changeToRandomName(user);//{name: "Lisa"} console.log("user:",user);//{name: "Lisa"}
Default Values
If a parameter is not provided, then its value becomes undefined. You can set a default value to be used in case a parament is not passed.
/* * Function Default values */ function hello(name, greeting = "Hello there! "){ return greeting+name; } /* * Note that functions can take 0 or more parameters. */ let greetingFolau = hello("Folau"); console.log(greetingFolau); // pass undefined instead null when intended to use default values. let greetingLisa = hello("Lisa", undefined); console.log(greetingLisa); let greetingKinga = hello("Kinga", "Hi "); console.log(greetingKinga);
Output
Hello there! Folau Hello there! Lisa Hi Kinga
Of course you can also check if parameters are undefined and set them to desired values
function sayHi(name, greeting){ // if(greeting==undefined){ // greeting = "Hello there! "; // } // undefined check with ?? greeting = greeting ?? "Hi there! "; return greeting+name; }
Function as a parameter
The function as a parameter will be executed every time the main function is called.
function sayHi(name, greeting){ // if(greeting==undefined){ // greeting = "Hello there! "; // } // undefined check with ?? greeting = greeting ?? "Hi there! "; return greeting+name; } let greetingLau = sayHi("Folau"); console.log(greetingLau); let greetingFusi = sayHi("Fusi", hello("Fusi ")); console.log(greetingFusi); //Hello there! Fusi Fusi
The arguments object
The arguments object contains an array of the arguments passed into the function. The arguments object behaves like an array though it is not an instance of the Array type.
let maxNum = findMax(1, 123, 500, 115, 44, 88); console.log("maxNum: ",maxNum);//500 function findMax() { var i; var max = -Infinity; for (i = 0; i < arguments.length; i++) { if (arguments[i] > max) { max = arguments[i]; } } return max; }
Anonymous functions
An Anonymous function is a function without a name. An Anonymous function cannot be called before its declaration.
//saveData();//Uncaught ReferenceError: Cannot access 'saveData' before initialization let saveData = function(){ console.log("saving data to database"); } saveData(); /* * Functions that run immediately */ let name = "Lisa"; let age = 30; (function() { console.log("name: "+name+",age: "+age); })(name);// parameters are passed from outside variables. let multiply = (function(a,b){ return a * b; })(10, 2); // multiply here holds the result of the multiplication not an instance of the function console.log(multiply);//20
Functions that run immediately(without being invoked)
let name = "Lisa"; let age = 30; (function() { console.log("name: "+name+",age: "+age); })(name, age);// parameters are passed from outside variables.
Arrow functions
An arrow function is a shorter way of declaring an anonymous function.
let updateData = (name) => { console.log("updating name in database."); } updateData();//updating name in database.