Day 15 Of #30DaysOfJavScript

Day 15 Of #30DaysOfJavScript

Introduction

Hey folks, I hope that you must have read my Day 14 Article on #30DaysOfJs. In case, if you haven't then make sure you give it a read by clicking here.

Classes

Programming in JavaScript is done through object-oriented design. In JavaScript, everything has properties and methods, just like an object. To create an object, we create a class. A class is a "blueprint" for building objects, similar to an object constructor. To create an object, we must instantiate a class. On the other hand, the object represents the class, while the class specifies the attributes and behavior of the object.

Once a class is created, it can be used to create objects at any time. Class instantiation is the process of creating an object from a class.

We learned how to create an object literal in the section on objects. The literal object is a singleton. We must write it if we wish to obtain a similar object.

  • Defining Classes- To define a class in JavaScript we need a keyword called 'class'.

For Example-

// Syntax
class ClassName {
    //  Code
}
  • Class Instantiation- This means creating an object inside a class.

For Example-

class Person {
  // Code
}
const person = new Person()
console.log(person)
  • Class Constructor- This is used for creating a blueprint of our object. It is defined using the constructor keyword. In the parenthesis within the function, we pass the properties of object as parameters. 'this' keyword is used for attaching the constructor parameters with the class.

For Example-

class Person {
  constructor(firstName, lastName) {
    console.log(this) 
    this.firstName = firstName
    this.lastName = lastName
  }
}

const person = new Person()

console.log(person)
  • Default Values With Constructor- These properties may have a default value like other regular functions.

For Example-

class Person {
  constructor(
    firstName = 'Shivank',
    lastName = 'Kapur',
    age = 19,
    country = 'India',
    city = 'New Delhi'
  ) {
    this.firstName = firstName
    this.lastName = lastName
    this.age = age
    this.country = country
    this.city = city
  }
}

const person1 = new Person() // Takes the default values
const person2 = new Person('Jason', 'Doe', 24, 'America', 'Chicago')

console.log(person1)
console.log(person2)

// Output -->
// Person {firstName: "Shivank", lastName: "Kapur", age: 19, country: "India", city: "New Delhi"}
// Person {firstName: "Jason", lastName: "Doe", age: 24, country: "America", city: "Chicago"}
  • Class Methods- It is a builtin function which allows us to create a blueprint for the object.

For Example-

class Person {
  constructor(firstName, lastName, age, country, city) {
    this.firstName = firstName
    this.lastName = lastName
    this.age = age
    this.country = country
    this.city = city
  }
  getFullName() {
    const fullName = this.firstName + ' ' + this.lastName
    return fullName
  }
}

const person1 = new Person('Shivank', 'Kapur', 19, 'India', 'New Delhi')
const person2 = new Person('Jason', 'Doe', 24, 'America', 'Chicago')

console.log(person1.getFullName())
console.log(person2.getFullName())
  • Properties With Initial Value- Creating a class for some properties that we may have as initial value.

For Example-

class Person {
  constructor(firstName, lastName, age, country, city) {
    this.firstName = firstName
    this.lastName = lastName
    this.age = age
    this.country = country
    this.city = city
    this.score = 0
    this.skills = []
  }
  getFullName() {
    const fullName = this.firstName + ' ' + this.lastName
    return fullName
  }
}

const person1 = new Person('Shivank', 'Kapur', 19, 'India', 'New Delhi')
const person2 = new Person('Jason', 'Doe', 24, 'America', 'Chicago')

console.log(person1.score)
console.log(person2.score)

console.log(person1.skills)
console.log(person2.skills)

// Output -->
// 0
// 0
// []
// []
  • getter- This allows us to access value from the object. We write the get method using the 'get' keyword followed by a function. Therefore, instead of accessing the values directly from the object we use getter to get the value.

For Example-

class Person {
  constructor(firstName, lastName, age, country, city) {
    this.firstName = firstName
    this.lastName = lastName
    this.age = age
    this.country = country
    this.city = city
    this.score = 0
    this.skills = []
  }
  getFullName() {
    const fullName = this.firstName + ' ' + this.lastName
    return fullName
  }
  get getScore() {
    return this.score
  }
  get getSkills() {
    return this.skills
  }
}

const person1 = new Person('Shivank', 'Kapur', 19, 'India', 'New Delhi')
const person2 = new Person('Jason', 'Doe', 24, 'America', 'Chicago')

console.log(person1.getScore) 
console.log(person2.getScore)

console.log(person1.getSkills)
console.log(person2.getSkills)
  • setter- The setter method allows us to modify the values of certain properties.

For Example-

class Person {
  constructor(firstName, lastName, age, country, city) {
    this.firstName = firstName
    this.lastName = lastName
    this.age = age
    this.country = country
    this.city = city
    this.score = 0
    this.skills = []
  }
  getFullName() {
    const fullName = this.firstName + ' ' + this.lastName
    return fullName
  }
  get getScore() {
    return this.score
  }
  get getSkills() {
    return this.skills
  }
  set setScore(score) {
    this.score += score
  }
  set setSkill(skill) {
    this.skills.push(skill)
  }
}

const person1 = new Person('Shivank', 'Kapur', 19, 'India', 'New Delhi')
const person2 = new Person('Jason', 'Doe', 24, 'America', 'Chicago')

person1.setScore = 1
person1.setSkill = 'HTML'
person1.setSkill = 'CSS'
person1.setSkill = 'JavaScript'

person2.setScore = 1
person2.setSkill = 'Programming'
person2.setSkill = 'Developer Relations'
person2.setSkill = 'Management'

console.log(person1.score)
console.log(person2.score)

console.log(person1.skills)
console.log(person2.skills)

// Output -->
// 1
// 1
// ["HTML", "CSS", "JavaScript"]
// ["Programming", "Developer Relations", "Management"]
  • Static Method- This defines the static method for a class. They are not called on the instances of the class instead they are called on the class itself.

For Example-

class Person {
  constructor(firstName, lastName, age, country, city) {
    this.firstName = firstName
    this.lastName = lastName
    this.age = age
    this.country = country
    this.city = city
    this.score = 0
    this.skills = []
  }
  getFullName() {
    const fullName = this.firstName + ' ' + this.lastName
    return fullName
  }
  get getScore() {
    return this.score
  }
  get getSkills() {
    return this.skills
  }
  set setScore(score) {
    this.score += score
  }
  set setSkill(skill) {
    this.skills.push(skill)
  }
  getPersonInfo() {
    let fullName = this.getFullName()
    let skills =
      this.skills.length > 0 &&
      this.skills.slice(0, this.skills.length - 1).join(', ') +
        ` and ${this.skills[this.skills.length - 1]}`

    let formattedSkills = skills ? `He knows ${skills}` : ''

    let info = `${fullName} is ${this.age}. He lives ${this.city}, ${this.country}. ${formattedSkills}`
    return info
  }
  static favoriteSkill() {
    const skills = ['HTML', 'CSS', 'JS', 'React', 'Python', 'Node']
    const index = Math.floor(Math.random() * skills.length)
    return skills[index]
  }
  static showDateTime() {
    let now = new Date()
    let year = now.getFullYear()
    let month = now.getMonth() + 1
    let date = now.getDate()
    let hours = now.getHours()
    let minutes = now.getMinutes()
    if (hours < 10) {
      hours = '0' + hours
    }
    if (minutes < 10) {
      minutes = '0' + minutes
    }

    let dateMonthYear = date + '.' + month + '.' + year
    let time = hours + ':' + minutes
    let fullTime = dateMonthYear + ' ' + time
    return fullTime
  }
}

console.log(Person.favoriteSkill())
console.log(Person.showDateTime())

Inheritance

Using inheritance, we can access all the properties and methods of the parent class. Therefore, helping in the reduction of code.

// Syntax
class ChildClassName extends {
 // Code
}

For Example- Creating a student class from another parent class.

class Student extends Person {
  saySomething() {
    console.log('Student class is the child of the Person class.')
  }
}

const s1 = new Student('Shivank', 'Kapur', 'India', 19, 'India')
console.log(s1)
console.log(s1.saySomething())
console.log(s1.getFullName())
console.log(s1.getPersonInfo())

I hope that you must have found this article quite helpful. If yes, then do give a read to some of my other articles!

Who knows you might become a great programmer 🤔!