class Student(){
String name;
int age;
Student(name){
this.name = name;
}
Student(name, age){
this.name = name;
this.age = age;
}
}
No. Since function overloading is not present we can have only Single constructor.
// normal way
function Student(name) {
this.name = name
this.age = 24
}
// if params are not fixed
function Student(name, age) {
if (age === undefined) {
age = 24
}
this.name = name
this.age = age
}
catName('kitty') // cat name is kitty
function catName(name){
console.log('cat name is', name)
}
function Person(firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
const member = new Person('Lydia', 'Hallie')
console.log(member.getFullName()) // will throw error
Person.prototype.getFullName = function () {
return `${this.firstName} ${this.lastName}`
}
console.log(member.getFullName()) // will run fine now
(from question 11)https://github.com/lydiahallie/javascript-questions#11-whats-the-output
const array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2); // [2, 8, 18, 32]
functional. requires a callback
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Arrayhttps://github.com/denysdovhan/wtfjs#true-is-false
- Mutable:
- to add: unshift, push
- to remove: shift, pop
- to remove from b/w: splice(startIndex, deleteCount)
- Immutable:
- to add: concat
- to remove: slice(start,end)
- copy: spread
const mario = {
lives: 3,
oneUp: () => {
this.lives++; // this will not update lives
}
}
this
When not to use arrow functionsQuestion that provoked this thought
5 << 2 // 101 << 2 // 010100 // 16+4 //20
5 >> 2 // 101 >> 2 // 01 // 2
5 ^ 3 // 101 ^ 011 // 0110 // 6
5 & 3 // 101 & 011 // 001 // 1 // always smaller or equal number
5 | 3 // 101 | 011 // 111 // 7 // always bigger or equal number
0 ^ 0 // 0
1 ^ 1 // 0
Related to lambda
// Class syntax
class Person {
constructor(first, last) {
this.first = first
this.last = last
// we can put getFullName here
// but then it'll be present on all object, wasting space
// this.getFullName = function() {
// return `${this.first} ${this.last}`
// }
}
getFullName() {
return `${this.first} ${this.last}`
}
}
//Equivalent function syntax
function Person(first, last) {
this.first = first
this.last = last
// we can put getFullName here
// but then it'll be present o all object, wasting space
}
Person.prototype.getFullName = function () {
return `${this.first} ${this.last}`
}
let Person = function(pName){
let name = pName
this.getName = function(){
return name;
}
}
let person = new Person("Sanyam")
person.getName() // "Sanyam"
// old
function Bird(){
this.name = 'donald'
}
b = new Bird()
b.name // "donald", can be modified also
// better + secure
function Bird(){
let name = 'donald'
this.getName = function(){
return name
}
}
b = new Bird()
b.name // undefined
let duck = new Bird()
let beagle = new Dog()
console.log(duck.constructor === Bird)
console.log(beagle.constructor === Dog)
var superProto = {
name:'sanyam'
}
superProto.constructor // Object(){}
function that create new object
function Animal(){
this.name = "goofy"
this.numLegs = 2
}
currying function means, converting N parameter function to N functions with 1 parameter
const add = x => y => z => x+y+z
- undefined
- null
- boolean
- Number
- String
- BigInt
- Symbol
- Object //anything made with new operator
- Function
for(let i in object) // key
for(let i of object) // Error. Object is not iterable
for(let i in array) // index
for(let i of array) // item
1, 2, 3, 8, 10, 11, 12, 14, 15 (Link)https://github.com/lydiahallie/javascript-questions#11-whats-the-output
function Bird(name) {
this.name = name;
this.numLegs = 2;
}
let canary = new Bird("Tweety");
canary.hasOwnProperty('name') //true
'age' in canary //true or false
//based on whether it is present in prototype chain
//or not
function Bird(name) {
this.name = name; //own property
}
Bird.prototype.numLegs = 2; // prototype property
b = new Bird()
b.hasOwnProperty('name') // true
b.hasOwnProperty('numLegs') // false
'name' in b // true
'numLegs' in b // true
const hashmap = new Map()
hashmap.set('sanyam', 30)
hashmap.get('sanyam') // 30
hashmap.has('sanyam') // true
hashmap.size // 1
for (const [key, value] of hashmap) {
console.log('key,value', key, value)
}
hashmap.get('anisha') // undefined
hashmap.delete('sanyam')
const set = new Set()
set.add('sanyam')
set.has('sanyam') // true
set.size // 1
set.delete('sanyam')
const a = [1, 2, 1, 2]
const unique = new Set(a) //{1,2}
// let animal = new Animal() // has some disadvantage, therefore not used
// 1. Create Instance of parent
let Animal = function(){}
Animal.prototype.eat = function(){
return 'nom nom'
}
// 2. Set prototype of child to be instance of parent & update constructor
let Bird = function(){}
Bird.prototype = Object.create(Animal.prototype)
Bird.prototype.constructor = Bird
// 3. add own methods
Bird.prototype.fly = function(){
return 'i can fly'
}
// 4. Override parent method
Bird.prototype.eat = function(){
return 'eating nicely'
}
class Animal{
eat(){
return 'nom nom'
}
}
class Bird extends Animal{
fly(){
return 'I can fly!'
}
// override
eat(){
return 'burp burp'
}
}
let flyMixin = function(obj){
obj.fly = function(){
console.log('i am flying')
}
}
flyMixin(bird)
flyMixin(airplane)
let a = new Animal()
a instanceof Object //true
a instanceof Animal //true
a instanceof People //false
Dog.prototype.isPrototypeOf(beagle) // with constructor function, use prototype
beagle.isPrototypeOf(goofy) // can directly used with object
object.prototype.prototype
var superProto = {
// some super properties
}
var subProto = Object.create(superProto);
subProto.someProp = 5;
var sub = Object.create(subProto);
console.log(superProto.isPrototypeOf(sub)); // **true**
console.log(sub instanceof superProto); // TypeError
console.log(sub instanceof superProto.constructor) // true
function memorizer(fun) {
let cache = {}
return function (n) {
if (cache[n] !== undefined) {
return cache[n]
}
let result = fun(n)
cache[n] = result
return result
}
}
const addOne = memorizer((num: number) => num + 1)
this
refers to the new empty object we create. However, if you don't add new
, this refers to the global object!function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const sarah = Person('Sarah', 'Smith');
console.log(sarah); // undefined, since Person didn't return anything
console.log(this.firstName); //'Sarah', sicne firstName is now defined on global/window object
const person = {
isHuman: false,
printIntroduction: function () {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`)
},
}
const me = Object.create(person)
me.name = 'Matthew' // "name" is a property set on "me", but not on "person"
me.isHuman = true // inherited properties can be overwritten
me.printIntroduction()
// expected output: "My name is Matthew. Am I human? true"
ConstructorName.prototype.propertyName = value
// instead of adding each property manually, we can overwrite it with new object
Dog.prototype = {
numLegs:4,
eat:function(){
console.log('eat eat eat')
},
describe:function(){
console.log('my name is'+this.name)
}
}
but problem with above is that constructor property is lost, therefore we redefine it
// instead of adding each property manually, we can overwrite it with new object
Dog.prototype = {
constructor: Dog,
numLegs:4,
eat:function(){
console.log('eat eat eat')
},
describe:function(){
console.log('my name is'+this.name)
}
}
const index = 'Some text'.search(regex)
returns int-> -1 or i>=0
const matches = 'Some text'.match(regex)
returns null or {index:3, input:'Some text'}
const next = 'Some text'.replace(regex,'hi mom')
const regex = /bob/g -> match bob
const regex = /bob|alice/g -> match bob or alice
const regex = /(bob|alice) Jones/g -> match bob jones or alice jones
const regex = /colou?r/g -> matches color, colour ?-> 0 or 1
const regex = /color*/ -> matches color, colorrr *-> 0 or multiple
const regex = /color+/ -> matches color, colorrr +-> 1 or multiple
const regex = /color{2,3}/ -> matches colorr, colorrr, but not color {min, mix}
\ -> escape special character
\d -> digit
\w -> word character
\D -> not digit
\W -> not word character
[A-Z] -> b/w a-z
[^A-Z]-> not b/w a-z
/sanyam/gi
new RegExp('sanyam','gi')
slice(start, end) -> [start,end)
let arrayIntegers = [1, 2, 3, 4];
let arrayIntegers1 = arrayIntegers.slice(0, 2); // returns [1,2]
let arrayIntegers3 = arrayIntegers.slice(2); //returns [3,4]
const months = ['March', 'Jan', 'Feb', 'Dec']
months.sort() // ["Dec", "Feb", "Jan", "March"]
const nums = [1, 30, 4, 21, 100000]
nums.sort() // [1, 100000, 21, 30, 4]
We can see, Numbers are not sorted!
nums.sort((first, second) => first - second)
dates.sort((first, second) => new Date(first) - new Date(second))
strings.sort((first, second))=>{
if(first<second){
// natural order is ascending order. here we do not want to change anything so return -1
return -1
}
return 1
})
functional. requires a callback to sort
let a = [1, 2, 3]
console.log(a) //[1,2,3]
console.log(...a) //1 2 3
let b = 'sanyam'
console.log(b) //sanyam
console.log(...b) //s a n y a m
let c = { name: 'sanyam' }
let d = { age: 20 }
console.log({ ...c, ...d }) //{'name':'sanyam':'age':20}
console.log(...c) // Error: non-callable iterator
function sum(x, y, z) {
return x + y + z
}
const numbers = [1, 2, 3]
console.log(sum(...numbers))
// expected output: 6
console.log(sum.apply(null, numbers))
// expected output: 6