// constructor function

// arrow function does not work with constructor function as we need ( this value )
// constructor function starts with Capital letter (may be with small but to tell this is 
// constructor function so start with Capital letter)

const Person = function(firstName,birthYear){
    // instance properties (because it is going to be available on every instance (object))
    this.firstName = firstName
    this.birthYear = birthYear

    // never do this inside constructor function (do not define methods inside constructor function)
    // this.calcAge = function(){
    //     console.log(2037-this.birthYear)
    // }

}

const jonas = new Person('Jonas',1991)
console.log(jonas)

// what new keyword does
// 1. new {} is created
// 2. function is called, this ={}
// 3. {} linked to protoype
// 4. function automatically return {}

const matilda = new Person('matilda',2017)
const jack = "sasds"
console.log(jack instanceof Person)

// each and every function (including constructor function) have property prototype
// all the object built on that constructor function is going to get all methods and properties define on
// that constructor prototype

// adavntage is this that we have to just create it once
// this is defined to which is calling it
Person.prototype.calcAge = function (){
    console.log(2037-this.birthYear)
}

jonas.calcAge()

function normal(){
    console.log("normal function")
}
// console.log(normal,Person)
console.log(normal.prototype,Person.prototype)
// .__proto__ of instances have value the same value stored in Person.protype
// so the .constrcutor return to the constructor function 
console.log(matilda.__proto__.constructor===Person," this gives us true value ") 
console.log(matilda.__proto__ === Person.prototype)

// here Person.prototype is not the protoype of Person but it is going to be protoype for the instances that is going to be created 
// on that constructor function

console.log(Person.prototype.isPrototypeOf(jonas))    // true
console.log(Person.prototype.isPrototypeOf(matilda)) // true
console.log(Person.prototype.isPrototypeOf(Person)) // this will give us false

Person.prototype.species = "Homo Sapiens"

// .__proto__: Person.prototype is added internally when new is called
// matilda.__proto__.__proto__ , is of object type

// this refers to back to constructor object
// console.log(Person.prototype.constructor)

// const arr = [3,5,6,7,8]
// console.log(arr.__proto__)
// console.log(arr.__proto__ === Array.prototype) // this will give us a true value

// add a function to Array protype
// Array.prototype.unique = function(){
//     return [...new Set(this)]
// }

// console.log(arr.unique())


// Class Decelaration

class PersonCl{
    constructor(firstName,birthYear){
        this.firstName = firstName
        this.birthYear = birthYear
    }
    // instance method
    // method will be added to .protoype property 
    calcAge(){
        console.log(2037-this.birthYear)
    }
    get latest(){
        return this.movements.slice(-1).pop()
    }

    get firstName(){
        return this._firstName
    }

    set firstName(name){
        console.log(name)
        if (name.includes('$')){
            this._firstName = name
        }
        else console.log(`${name} is not a full name`)
    }

    set latest(mov){
        this.movements.push(mov)
    }
    // creating a static method
    static hey(){
        console.log("hello there",this)
    }
}

// this is a static method a object can not call it because it is not defined in the prototype
PersonCl.hey = function(){
    console.log("hello there",this)
}
PersonCl.hey()

const jessica = new PersonCl('jessica',1996)

// jessica.hey() will give an error
// jessica.calcAge()
console.log(jessica.__proto__ === PersonCl.prototype) // gives true value

// 1. classes are not hoisted
// 2. Classes are first-class citizes
// 3. Classes are executed in strict mode


const account = {
    owner:'jonas',
    movements :[200,530,120,300],

    get latest(){
        return this.movements.slice(-1).pop()
    },

    set latest(mov){
        this.movements.push(mov)
    }
}
console.log(account.latest)
account.latest = 50
console.log(account.movements)


// Inheritance between Classes : constructor functions


const Human = function(firstName,birthYear){
    this.firstName = firstName
    this.birthYear = birthYear

}

Human.prototype.calcAge = function (){
    console.log(2037-this.birthYear)
}

// adding a protype to Student 
const Student = function(firstName,birthYear,course){
    // this.firstName = firstName,
    // this.birthYear = birthYear,
    Human.call(this,firstName,birthYear)
    this.course = course
}

// this will not add  protoype
// Student.prototype = Human.prototype

Student.prototype = Object.create(Human.prototype)

Student.prototype.introduce =function (){
    console.log(`my name is ${this.firstName} and studying ${this.course}`)
} 
const mike = new Student('Mike',2000,"ca")
mike.calcAge()
// console.log(mike.calcAge())

console.log(mike instanceof Student) // true
console.log(mike instanceof Person)  // true
console.log(mike instanceof Object)  // true
// here constructor value is set to Human when we set Student.protoype to Object.create(Human.prototype)  ( so we are
//  changing it to Student)
Student.prototype.constructor = Student;
console.log(mike)
console.log(mike.__proto__)
console.log(mike.__proto__.__proto__) // this will contain the value of the inherited one

// if there are two methods with same name in parent and child class then it is going to take the first one from protoype chain
// which is child class


// class functionality with ES6 Classes

class Inheritance{
    constructor(fullName,birthYear){
        this.birthYear = birthYear
        this.fullName = fullName
    }

    introduce(){
        console.log(`hello i am ${this.fullName} and age is ${this.birthYear}`)
    }
}

class Called extends Inheritance{
    constructor(fullName,birthYear,course){
        // always need to be done first because (may be -- it creates this keyword) if Parent is to be called
        super(fullName,birthYear)
        this.course = course
        // we can also add properties like this
        this.movements = []
        console.log("this is going to run when we constructor run ")
    }
    calcAge = function (){
        console.log(2037-this.birthYear)
    }
}

let marth = new Called("marth",34,"btech")
console.log(marth)
marth.calcAge()
marth.introduce()


// like this chaining also works in js
// def hello(x):
//   print("hello")
//   return x
  
// a = hello
// b = a(hello)(hello)(hello) 

Javascript Online Compiler

Write, Run & Share Javascript code online using OneCompiler's JS online compiler for free. It's one of the robust, feature-rich online compilers for Javascript language. Getting started with the OneCompiler's Javascript editor is easy and fast. The editor shows sample boilerplate code when you choose language as Javascript and start coding.

About Javascript

Javascript(JS) is a object-oriented programming language which adhere to ECMA Script Standards. Javascript is required to design the behaviour of the web pages.

Key Features

  • Open-source
  • Just-in-time compiled language
  • Embedded along with HTML and makes web pages alive
  • Originally named as LiveScript.
  • Executable in both browser and server which has Javascript engines like V8(chrome), SpiderMonkey(Firefox) etc.

Syntax help

STDIN Example

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line){
    console.log("Hello, " + line);
});

variable declaration

KeywordDescriptionScope
varVar is used to declare variables(old way of declaring variables)Function or global scope
letlet is also used to declare variables(new way)Global or block Scope
constconst is used to declare const values. Once the value is assigned, it can not be modifiedGlobal or block Scope

Backtick Strings

Interpolation

let greetings = `Hello ${name}`

Multi line Strings

const msg = `
hello
world!
`

Arrays

An array is a collection of items or values.

Syntax:

let arrayName = [value1, value2,..etc];
// or
let arrayName = new Array("value1","value2",..etc);

Example:

let mobiles = ["iPhone", "Samsung", "Pixel"];

// accessing an array
console.log(mobiles[0]);

// changing an array element
mobiles[3] = "Nokia";

Arrow functions

Arrow Functions helps developers to write code in concise way, it’s introduced in ES6.
Arrow functions can be written in multiple ways. Below are couple of ways to use arrow function but it can be written in many other ways as well.

Syntax:

() => expression

Example:

const numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const squaresOfEvenNumbers = numbers.filter(ele => ele % 2 == 0)
                                    .map(ele => ele ** 2);
console.log(squaresOfEvenNumbers);

De-structuring

Arrays

let [firstName, lastName] = ['Foo', 'Bar']

Objects

let {firstName, lastName} = {
  firstName: 'Foo',
  lastName: 'Bar'
}

rest(...) operator

 const {
    title,
    firstName,
    lastName,
    ...rest
  } = record;

Spread(...) operator

//Object spread
const post = {
  ...options,
  type: "new"
}
//array spread
const users = [
  ...adminUsers,
  ...normalUsers
]

Functions

function greetings({ name = 'Foo' } = {}) { //Defaulting name to Foo
  console.log(`Hello ${name}!`);
}
 
greet() // Hello Foo
greet({ name: 'Bar' }) // Hi Bar

Loops

1. If:

IF is used to execute a block of code based on a condition.

Syntax

if(condition){
    // code
}

2. If-Else:

Else part is used to execute the block of code when the condition fails.

Syntax

if(condition){
    // code
} else {
    // code
}

3. Switch:

Switch is used to replace nested If-Else statements.

Syntax

switch(condition){
    case 'value1' :
        //code
        [break;]
    case 'value2' :
        //code
        [break;]
    .......
    default :
        //code
        [break;]
}

4. For

For loop is used to iterate a set of statements based on a condition.

for(Initialization; Condition; Increment/decrement){  
//code  
} 

5. While

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while (condition) {  
  // code 
}  

6. Do-While

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {  
  // code 
} while (condition); 

Classes

ES6 introduced classes along with OOPS concepts in JS. Class is similar to a function which you can think like kind of template which will get called when ever you initialize class.

Syntax:

class className {
  constructor() { ... } //Mandatory Class method
  method1() { ... }
  method2() { ... }
  ...
}

Example:

class Mobile {
  constructor(model) {
    this.name = model;
  }
}

mbl = new Mobile("iPhone");