Skip to main content

Globant part 1

 1)call,apply,bind example?

Ans:

a. call Method:

The call method is used to call a function with a given this value and arguments provided individually.


Javascript code:

function greet(name) {

  console.log(`Hello, ${name}! I am ${this.role}.`);

}


const person = {

  role: 'developer'

};


greet.call(person, 'Alice');

// Output: Hello, Alice! I am developer.

In this example, call invokes the greet function with person as the this value and passes 'Alice' as an argument.


b. apply Method:

The apply method is similar to call, but it accepts arguments as an array.


Javascript code:

function introduce(language1, language2) {

  console.log(`I can code in ${language1} and ${language2}. I am ${this.name}.`);

}


const coder = {

  name: 'Bob'

};


introduce.apply(coder, ['JavaScript', 'Python']);

// Output: I can code in JavaScript and Python. I am Bob.

Here, apply is used to invoke introduce with coder as this and an array ['JavaScript', 'Python'] as arguments.


c. bind Method:

The bind method creates a new function that, when called, has its this keyword set to a specified value, with a given sequence of arguments preceding any provided when the new function is called.


Javascript code:

function saySomething(message) {

  console.log(`${this.name} says: ${message}`);

}


const dog = {

  name: 'Buddy'

};


const dogTalk = saySomething.bind(dog);


dogTalk('Woof woof!');

// Output: Buddy says: Woof woof!

In this example, bind creates a new function dogTalk where this is bound to dog. When dogTalk is called with 'Woof woof!', it logs the message with Buddy as the name.


These methods (call, apply, and bind) are often used in JavaScript for manipulating this context and passing arguments to functions in different ways.


2)Rest vs spread?

The rest operator and the spread operator are both introduced in ES6 (ECMAScript 2015) and are represented by three dots (...). While they may look similar, they serve different purposes.

The rest operator and the spread operator are both introduced in ES6 (ECMAScript 2015) and are represented by three dots (...). While they may look similar, they serve different purposes.

Rest Operator (...)
The rest operator is used to gather elements (often parameters) into an array.

Javascript code:
function sum(...numbers) {
  return numbers.reduce((total, num) => total + num, 0);
}

console.log(sum(1, 2, 3, 4, 5)); // Output: 15
In this example, the rest parameter ...numbers gathers all arguments passed to the sum function into an array called numbers.

Spread Operator (...)
The spread operator, on the other hand, is used to spread elements from an array or an iterable object (like a string or array) into individual elements.
Javascript code:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const mergedArray = [...arr1, ...arr2];
console.log(mergedArray); // Output: [1, 2, 3, 4, 5, 6]
In this example, the spread operator ...arr1 spreads the elements of arr1, and ...arr2 spreads the elements of arr2. These elements are then combined into a new array mergedArray.

Spread Operator with Objects
Yes, the spread operator also works with objects, but it does a shallow copy. If you spread two objects with the same keys, the latter one will overwrite the former one.
Javascript code:
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };

const mergedObject = { ...obj1, ...obj2 };
console.log(mergedObject); // Output: { a: 1, b: 3, c: 4 }
In this example, ...obj1 spreads the properties of obj1, and ...obj2 spreads the properties of obj2. The property b from obj2 overwrites the property b from obj1 in the merged object.

If you try to spread objects with duplicate keys, the last key-value pair encountered will override any earlier ones.

javascript
Copy code
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, a: 4 };

const mergedObject = { ...obj1, ...obj2 };
console.log(mergedObject); // Output: { a: 4, b: 3 }
In this case, obj2's property a overwrites obj1's property a, and obj2's property b overwrites obj1's property b.


3)Program
var s="abcdef"
var b="cmnem" output =['c','e'] Write a program

1 st approch:

const s = "abcdef";
const b = "cmnem";

// Convert strings to arrays
const sArray = s.split('');
const bArray = b.split('');

// Filter characters that appear in both arrays
const output = sArray.filter(char => bArray.includes(char));

console.log(output); // Output: ['c', 'e']

2nd: Approch:
var s = "abcdef";
var b = "cmnem";

// Convert strings to arrays
var sArray = s.split('');
var bArray = b.split('');

// Filter characters that appear in both arrays
var output = [];
for (var i = 0; i < sArray.length; i++) {
    if (bArray.includes(sArray[i])) {
        output.push(sArray[i]);
    }
}

console.log(output); // Output: ['c', 'e']


4)Object.create vs assign:
  • Object.create() creates a new object with the specified prototype, while Object.assign() copies properties from source objects to a target object.
  • Object.create() allows you to create an object with a specific prototype, which can be useful for prototypal inheritance.

  • Object.assign() is commonly used for shallow copying properties from one or more source objects to a target object.
  • Object.assign() modifies the target object directly, whereas Object.create() creates a new object.

In summary, Object.create() is used to create a new object with a specified prototype, whereas Object.assign() is used to copy properties from source objects to a target object. They serve different purposes and are used in different scenarios.

4)Oops 4 pillars?:

  1. Certainly! Let's illustrate each of the Four Pillars of Object-Oriented Programming (OOP) using JavaScript. a. Encapsulation: Encapsulation involves bundling data and methods into a single unit (class) and controlling access to them. In JavaScript, we can achieve encapsulation using classes and access modifiers. javascript Copy code class Car { #speed; // Private field constructor(speed) { this.#speed = speed; } getSpeed() { return this.#speed; } accelerate(increase) { this.#speed += increase; } } const myCar = new Car(50); console.log(myCar.getSpeed()); // Output: 50 myCar.accelerate(20); console.log(myCar.getSpeed()); // Output: 70 In this example, Car class encapsulates the speed property and methods for getting and accelerating the car's speed. The speed property is encapsulated using a private field (#speed). b. Inheritance: Inheritance allows a class (subclass) to inherit properties and methods from another class (superclass) and extend or override them as needed. javascript Copy code class Animal { speak() { console.log('The animal makes a sound'); } } class Dog extends Animal { speak() { console.log('The dog barks'); } } const dog = new Dog(); dog.speak(); // Output: The dog barks In this example, Dog class inherits the speak() method from the Animal class and overrides it with its own implementation. c. Polymorphism: Polymorphism allows objects to take different forms or exhibit different behaviors based on their context. In JavaScript, we can achieve polymorphism through method overriding. javascript Copy code class Shape { draw() { console.log('Drawing a shape'); } } class Circle extends Shape { draw() { console.log('Drawing a circle'); } } class Square extends Shape { draw() { console.log('Drawing a square'); } } const shapes = [new Circle(), new Square()]; shapes.forEach(shape => shape.draw()); // Output: Drawing a circle // Drawing a square In this example, Circle and Square classes override the draw() method inherited from the Shape class, exhibiting polymorphic behavior when called. d. Abstraction: Abstraction involves hiding the implementation details of an object and exposing only the essential features. In JavaScript, abstraction can be achieved through interfaces or by providing simplified APIs. javascript Copy code class RemoteControl { #device; constructor(device) { this.#device = device; } turnOn() { this.#device.power = true; } turnOff() { this.#device.power = false; } } const tv = { power: false, channel: 1, volume: 50 }; const remote = new RemoteControl(tv); remote.turnOn(); console.log(tv.power); // Output: true In this example, RemoteControl class abstracts the functionality of turning a device on and off, hiding the details of how the device is controlled. The implementation details of the device (tv) are abstracted away from the user.




e)polymorphism in js and not ts using prototype:

In JavaScript, polymorphism allows objects of different classes to be treated as objects of a common superclass. This means that different classes can have methods with the same name, and you can call these methods on objects of these different classes, but the behavior will vary based on the specific implementation in each class. This is achieved through method overriding.

/ Superclass
function Animal(name) {
  this.name = name;
}

// Method in the superclass
Animal.prototype.makeSound = function() {
  return 'Generic animal sound';
};

// Subclass 1
function Dog(name) {
  Animal.call(this, name);
}

// Inheriting from the superclass
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

// Overriding the method in the subclass
Dog.prototype.makeSound = function() {
  return 'Woof woof!';
};

// Subclass 2
function Cat(name) {
  Animal.call(this, name);
}

// Inheriting from the superclass
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;

// Overriding the method in the subclass
Cat.prototype.makeSound = function() {
  return 'Meow!';
};

// Create instances of the subclasses
const myDog = new Dog('Buddy');
const myCat = new Cat('Whiskers');

// Call the common method on different objects
console.log(myDog.makeSound()); // Output: Woof woof!
console.log(myCat.makeSound()); // Output: Meow!
In this example:

We have a superclass Animal with a method makeSound.
We then have two subclasses Dog and Cat, both inheriting from Animal.
Each subclass overrides the makeSound method with its own implementation.
We create instances of both Dog and Cat.
When we call makeSound on these instances, we get different results based on the specific implementation in each subclass. This is polymorphism in action: the same method name (makeSound) being used on different objects, but producing different behaviors based on the object's class.










Comments

Popular posts from this blog

Node.js: Extract text from image using Tesseract.

In this article, we will see how to extract text from images using Tesseract . So let's start with this use-case, Suppose you have 300 screenshot images in your mobile which has an email attribute that you need for some reason like growing your network or for email marketing. To get an email from all these images manually into CSV or excel will take a lot of time. So now we will check how to automate this thing. First, you need to install Tesseract OCR( An optical character recognition engine ) pre-built binary package for a particular OS. I have tested it for Windows 10. For Windows 10, you can install  it from here. For other OS you make check  this link. So once you install Tesseract from windows setup, you also need to set path variable probably, 'C:\Program Files\Tesseract-OCR' to access it from any location. Then you need to install textract library from npm. To read the path of these 300 images we can select all images and can rename it to som...

CSS INTERVIEW QUESTIONS SET 2

  You make also like this CSS interview question set 1. Let's begin with set 2, 5)What is the difference between opacity 0 vs display none vs visibility hidden? Property           | occupies space | consumes clicks | +--------------------+----------------+-----------------+ | opacity: 0         |        yes      |        yes       | +--------------------+----------------+-----------------+ | visibility: hidden |        yes       |        no        | +--------------------+----------------+-----------------+ | display: none      |        no       |        no        | When we say it consumes click, that means it also consumes other pointer-events like onmousedown,onmousemove, etc. In e...