-
Notifications
You must be signed in to change notification settings - Fork 0
IV Javascript
- Classes
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello ${this.name}`);
}
}
class Student extends Person {
constructor(name, level) {
super(name);
this.level = level;
}
greet() {
console.log(`Hello ${this.name} from ${this.level}`);
}
}
const o1 = new Person("Ramesh");
const o2 = new Student("Sandesh", "10th");
const o3 = new Student("Suresh", "13th");
o3.greet = () => console.log('I am Special!!!');
o1.greet();
o2.greet();
o3.greet();
- Templates (the char => ` )
// evaluating
const html = `<div>${Math.random()}</div>`;
// multiple lines
const html = `
<div>
${Math.random()}
</div>`;
- Arrow functions
// sample
const square = (a) => {
return a * a;
};
// shot hand
const square = (a) => a * a;
const square = a => a * a; // if only one parameter
- Arrow Functions :: Output ?
this.id = 'exports';
const testerObj = {
func1: function() {
console.log('func1', this);
},
func2: () => {
console.log('func2', this);
},
func3: () => console.log('func3', this)
}
testerObj.func1(); // shows testerObj info
testerObj.func2(); // shows exports/window info
testerObj.func3(); // shows exports/window info
- Dynamic property
const mystery = 'answer';
const PI = Math.PI;
const obj = {
p1: 10,
PI,
[mystery]: 42
}
console.log(obj.PI);
console.log(obj.mystery);
console.log(obj.answer);
- Dynamic Property from class : Destructuring
const PI = Math.PI;
const E = Math.E;
const SQRT2 = Math.SQRT2;
// short code
const { PI, E, SQRT2 } = Math;
// another example
// basically takes readFile property/method from 'fs' module and assigns it to locally created variable named readFile
const { readFile } = require('fs');
// another example - destructuring and taking what exactly is required
const circleArea = ({ radius }, { precision = 2 } = {}) => {
//var result = (radius * radius).ToFixed(2);
var result = (radius * radius).toFixed(precision);
console.log(result);
}
const circle = { radius: 5, diameter: 10, thickness: 1 };
circleArea(circle, { precision: 0 });
circleArea({ radius:15, height:100 });
circleArea({ radius:3 }, { precision: 1});
// { precision = 2 } => Default value
// { precision = 2 } => Optional
// skip if not required
const [first, , , fourth] = [10, 20, 30, 40];
console.log(first);
console.log(fourth);
// rest of items
var[first, ...restOfItems] = [10, 20, 30];
console.log(first);
console.log(restOfItems);
// shallow copies
var newA = [...restOfItems];
console.log(newA);
// how is it different ???
var newB = restOfItems;
console.log(newB);
-
Difference b/w Object.freeze() and Object.seal()
-
Output ?
// scalars
const answer = 42;
const greeting = 'Hello';
// immutable - so cannot change the content
// arrays & objects
var a = [2, 4, 6] ;
const numbers = a;
const person = {
firstName: 'Hello',
lastName: 'World'
}
// the reference is constant. but the content can be changed
try{
console.log('Test 1');
answer = 15;
console.log(answer);
} catch { }
try{
console.log('Test 2');
greeting = 'ok';
console.log(greeting);
} catch { }
try{
console.log('Test 3');
a = [ 4,2];
console.log(numbers);
} catch { }
try{
console.log('Test 3.1');
numbers[0] = 56;
console.log(numbers);
} catch { }
try{
console.log('Test 4');
person= { age: 50 }
console.log(person);
} catch { }
try{
console.log('Test 5');
person.firstName = 'kota'
console.log(person);
} catch { }
try{
console.log('Test 5.1');
Object.freeze(person); // works for only 1 level children
person.firstName = 'kota'
console.log(person);
} catch { }
- Output ?
{
// block scope
{
// nested block scope
var a = 10;
let b = 10;
const c = 10;
}
}
if(true) {
// block scope
}
for (var i =1; i <= 10; i ++){
// block scope
}
for (let j =1; j <= 10; j ++){
// block scope
}
function sum(a, b) {
// function scope
var k = a + b;
}
console.log(k); // error: Uncaught ReferenceError: k is not defined
console.log(i); // 11
console.log(j); // error: Uncaught ReferenceError: j is not defined
console.log(a); // 10
console.log(b); // error: Uncaught ReferenceError: b is not defined
console.log(c); // error: Uncaught ReferenceError: c is not defined
- Output ?
const timerId = setTimeout (
() => console.log('No wati time'),
0
);
clearTimeout(timerId);
// no logs - since the thread executes this and the timeout gets cancelled before getting triggered
- Output ?
setTimeout(
() => console.log('Hello after 0.5 seconds!'),
500
);
for(let i = 0; i < 1e10; i++) {
// Some logic
}
// Logs after execution of the for loop regardless of timeout specified
- Call a function every 2 second. Retry it only for 5 times
let i =0;
const timerId = setInterval (
() => {
i++;
if(i == 5){
console.log('clearing after 5 retries');
clearInterval(timerId);
}
var result = LoadData();
console.log(result);
if(result == 'success'){
console.log('clearing since it is a success');
clearInterval(timerId);
}
},
500
);
const LoadData = () => {
// ajax call
return 'failure';
}
- Challenge 1
Print "Hello World" forever. Starting with a delay of 1 second but then incrementing the delay by 1 second each time. The second time will have a delay of 2 seconds The third time will have a delay of 3 seconds.
Include the delay in the printed message
Hello World. 1
Hello World. 2
Hello World. 3
...
Constraints: You can only use const (no let or var)
const timer = 1000;
function Print(timer){
setTimeout(
() =>{
console.log('Hello World. ', timer/1000);
Print(timer + 1000);
},
timer
);
}
Print(timer);
- Challenge 2
Just like Challenge 1 but this time with repeated delay values. Print Hello World 5 times with a delay of 100 ms. Then Print it again 5 more times with a delay of 200 ms. Then print it again 5 more times with a delay of 300 ms. And so on until the program is killed.
Include the delay in the printed message:
Hello World. 100
Hello World. 100
Hello World. 100
Hello World. 100
Hello World. 100
Hello World. 200
Hello World. 200
Hello World. 200
...
var timer = 1000;
var counter = 0;
function Print(timer){
var looper = setInterval(
() =>{
console.log('Hello World. ', timer/1000);
counter++;
if(counter == 5){
clearInterval(looper);
counter = 1;
timer = timer + 1000;
Print(timer);
}
},
timer
);
}
Print(timer);