Skip to main content

Gloabt part 4

 1)When you execute synchronous code like console.log("Inside setTimeout callback");, it's executed immediately within the current context and doesn't involve the event loop


2)Major and Minor in package.json?

  • Caret (^):

    • Allows minor and patch version updates.
    • Major version remains fixed.
    • Suitable for projects where you want to automatically get the latest features and bug fixes but avoid major changes that might introduce breaking changes.
  • Tilde (~):

    • Allows only patch updates.
    • Major and minor versions remain fixed.
    • Suitable for projects where you want to receive bug fixes and patches but avoid minor or major changes that might introduce new features or breaking changes.

I hope this clarifies the difference between the caret (^) and tilde (~) operators for specifying version ranges in package.json or when using package managers

3)How to save in dev dependency?

npm install module --save-dev

npm install module -D


4)Package .json and package.lock.json ? Should we commit to git?

package.json and package-lock.json are both important files in a Node.js project:

  1. package.json: This file contains metadata about your project, such as project name, version, dependencies, and scripts. It also lists the dependencies your project needs to run.

  2. package-lock.json: This file is automatically generated by npm to lock down the version of dependencies installed in your project. It ensures that the same versions of dependencies are installed across different environments, preventing unexpected changes due to updates.

You should commit both package.json and package-lock.json to your Git repository. Here's why:

  • Reproducibility: Committing package-lock.json ensures that anyone else who clones your repository will install the exact same versions of dependencies that you used. This helps in ensuring consistent behavior across different environments and prevents issues caused by dependency version mismatches.

  • Dependency Management: package-lock.json acts as a record of the dependency tree at the time of installation. If you or someone else needs to reinstall dependencies or troubleshoot dependency issues, having package-lock.json committed provides a complete picture of the dependency tree.

  • Security: By committing package-lock.json, you're also committing to a specific set of dependencies and their versions. This can help in auditing dependencies for security vulnerabilities and ensuring that security patches are applied consistently.

In summary, both package.json and package-lock.json are important for managing dependencies in a Node.js project, and it's best practice to commit both files to your Git repository to ensure reproducibility, consistent dependency management, and security.



5)Contents of package.json and package.lock.json? Sure, let's discuss the contents of both package.json and package-lock.json files: 1. package.json: The package.json file is a metadata file for your project and is typically located at the root of your project directory. It contains various pieces of information about your project, including its name, version, description, entry points, dependencies, scripts, and more. Below are the main sections found in a package.json file: name: The name of your project. version: The version of your project. description: A brief description of your project. main: The entry point of your application (e.g., the main JavaScript file). scripts: A set of scripts that can be executed using npm/yarn commands. dependencies: The list of packages that your project depends on for runtime. devDependencies: The list of packages that your project depends on for development purposes. engines: Specifies the version of Node.js required by your project. repository: Information about the source code repository of your project. license: The license under which your project is distributed. An example of a package.json file: json Copy code { "name": "my-project", "version": "1.0.0", "description": "A sample project", "main": "index.js", "scripts": { "start": "node index.js", "test": "mocha" }, "dependencies": { "express": "^4.17.1" }, "devDependencies": { "mocha": "^8.3.2" }, "engines": { "node": ">=12" }, "repository": { "type": "git", "url": "https://github.com/username/my-project.git" }, "license": "MIT" }

he package-lock.json file is automatically generated by npm to provide deterministic dependency resolution. It contains a complete record of the exact versions of all dependencies and their transitive dependencies installed in your project. This ensures that the same versions of dependencies are installed across different environments and by different developers.

The package-lock.json file includes information such as:

  • The name and version of each installed package.
  • The resolved version of each package.
  • Dependency tree structure.
  • Integrity checksums for packages to ensure their contents haven't changed since installation.
6)Promise function:

function getT(input) {
    return new Promise((resolve, reject) => {
       resolve(input);
    });
}

getT(1).then((i) => {
    console.log(i);
});

7)Hositing: In Node.js, as in JavaScript in general, hoisting is a mechanism where variable and function declarations are moved to the top of their containing scope during the compilation phase. This means that regardless of where variables and functions are declared in the code, they are accessible anywhere within their containing scope. Let's look at an example to illustrate hoisting in Node.js: console.log(myVar); // undefined var myVar = 10; console.log(myVar); // 10 hello(); // "Hello, world!" function hello() { console.log("Hello, world!");
}

8)Shallow and deep copy? Ways to do in JS

ans: In JavaScript, when dealing with objects and arrays, it's essential to understand the concepts of shallow copy and deep copy: Shallow Copy: A shallow copy creates a new object or array and copies the references of the original elements. This means that if the original object contains nested objects or arrays, only the references to those nested objects or arrays are copied, not the objects or arrays themselves. Ways to perform shallow copy: Using Object.assign(): javascript Copy code const shallowCopy = Object.assign({}, originalObject); Using the spread operator (...): javascript Copy code const shallowCopy = { ...originalObject }; Using Array.slice() (for arrays): javascript Copy code const shallowCopy = originalArray.slice(); Deep Copy: A deep copy creates a completely new object or array and recursively copies all nested objects or arrays. This means that every object and array within the original object or array is duplicated in memory. Ways to perform deep copy: Using JSON.parse() and JSON.stringify(): javascript Copy code const deepCopy = JSON.parse(JSON.stringify(originalObject)); Note: This method works well for simple objects and arrays but has limitations with objects containing functions, undefined values, or circular references. Using libraries: Libraries like Lodash provide methods for deep copying objects and arrays, such as _.cloneDeep(). Using custom recursive functions: javascript Copy code function deepCopy(obj) { if (typeof obj !== 'object' || obj === null) { return obj; // Base case: return primitives and null as is } const copy = Array.isArray(obj) ? [] : {}; for (let key in obj) { copy[key] = deepCopy(obj[key]); } return copy; } const deepCopy = deepCopy(originalObject); This method recursively iterates through the original object and copies each nested object or array. Choosing between shallow copy and deep copy: Use shallow copy when you only need to copy the top-level structure and are sure that nested objects or arrays won't be modified. Use deep copy when you need to ensure that all nested objects or arrays are completely independent and won't be affected by modifications to the original object or array. However, be aware that deep copying can be more computationally expensive and may not be suitable for large or complex objects.
9)Data types in js:
In JavaScript, there are several data types, including primitive data types and non-primitive data types:

1. Primitive Data Types:
Primitive data types are immutable and represent single values. They are not objects and do not have methods or properties.

Boolean: Represents a logical value, true or false.
Number: Represents numeric values, including integers and floating-point numbers.
String: Represents textual data enclosed within single ('') or double ("") quotes.
Undefined: Represents a variable that has been declared but not assigned a value.
Null: Represents the intentional absence of any value.
Symbol: Represents a unique identifier that's used as property keys in objects.
Example:

javascript
Copy code
let boolVar = true;
let numVar = 10;
let strVar = "Hello, world!";
let undefVar;
let nullVar = null;
let symVar = Symbol("description");

2. Non-Primitive Data Types (Reference Types):
Non-primitive data types are mutable and store references to values. They are objects and have properties and methods.

Object: Represents a collection of key-value pairs, where keys are strings (or symbols) and values can be of any data type, including other objects.
Example:

javascript
Copy code
let objVar = { key1: "value1", key2: 20, key3: true };
Arrays, Dates, Regular Expressions, and Functions are also objects, although they have their own specific behavior and characteristics.

Array: Represents a list-like collection of elements.
javascript
Copy code
let arrVar = [1, 2, 3, 4];
Date: Represents a date and time.
javascript
Copy code
let dateVar = new Date();
RegExp: Represents a regular expression pattern.
javascript
Copy code
let regexVar = /pattern/;
Function: Represents a block of reusable code.
javascript
Copy code
function funcVar() {
    // Function body
}
Note:
JavaScript is a dynamically-typed language, meaning you do not need to specify the data type of a variable explicitly.
Variables in JavaScript can hold values of any type, and their types can change dynamically as values are assigned to them.
You can use the typeof operator to determine the data type of a variable at runtime.
Understanding data types is essential for writing efficient and bug-free JavaScript code.

10)Function Constructor vs Object Constructor: In JavaScript, both function constructors and object constructors are used to create objects, but they serve different purposes: Function Constructor: The function constructor is used to create functions dynamically at runtime by passing a string containing the function body as an argument to the Function constructor. It's rarely used for creating objects directly, but rather for defining functions programmatically. Example of creating a function using the function constructor: javascript Copy code var addFunction = new Function('a', 'b', 'return a + b;');

Object Constructor: The object constructor is used to create new instances of objects based on a predefined constructor function. You define a constructor function using the function keyword and use the new keyword to instantiate objects from it. Example of creating objects using the object constructor pattern: javascript Copy code // Constructor function function Person(name, age) { this.name = name; this.age = age; } // Creating instances using the constructor function var person1 = new Person('Alice', 30); var person2 = new Person('Bob', 25); In this example, Person is a constructor function that defines the structure of a Person object with name and age properties. You use the new keyword to create new instances of Person, initializing them with specific values. Differences: Purpose: Function constructor is primarily used for dynamically creating functions, while object constructor is used for creating new instances of objects.
Syntax: Function constructor syntax involves using the new Function() syntax with a string containing the function body, while object constructor syntax involves defining a constructor function using the function keyword and using the new keyword to instantiate objects.
Usage: Function constructors are less commonly used compared to object constructors, as functions are usually defined using function declarations or expressions. Object constructors, on the other hand, are a fundamental part of object-oriented programming in JavaScript. In summary, function constructors are used for dynamically creating functions, while object constructors are used for creating new instances of objects based on predefined constructor functions. Each serves a different purpose in JavaScript programming.

11)Different ways to create object in js? JavaScript, there are several ways to create objects. Each method has its own advantages and use cases. Here are the most common ways to create objects in JavaScript: 1. Object Literal: The simplest way to create an object is using the object literal syntax {}. You define properties and methods directly inside the curly braces. javascript Copy code const person = { name: 'John', age: 30, greet() { console.log(`Hello, my name is ${this.name}`); } }; 2. Constructor Function: You can define a constructor function using the function keyword. Constructor functions are used to create objects with the new keyword. Inside the constructor function, properties and methods are defined using the this keyword. javascript Copy code function Person(name, age) { this.name = name; this.age = age; this.greet = function() { console.log(`Hello, my name is ${this.name}`); }; } const person = new Person('John', 30); 3. Object.create(): The Object.create() method creates a new object with the specified prototype object and properties. It allows you to create objects with a specific prototype without using constructor functions. javascript Copy code const personProto = { greet() { console.log(`Hello, my name is ${this.name}`); } }; const person = Object.create(personProto); person.name = 'John'; person.age = 30; 4. Class Syntax (ES6): With ES6, you can use the class syntax to define classes, which are syntactical sugar over constructor functions. Classes encapsulate data for creating objects with methods to operate on that data. javascript Copy code class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log(`Hello, my name is ${this.name}`); } } const person = new Person('John', 30); 5. Factory Functions: Factory functions are functions that return objects. They are useful when you need to create multiple similar objects without using constructor functions. javascript Copy code function createPerson(name, age) { return { name: name, age: age, greet() { console.log(`Hello, my name is ${this.name}`); } }; } const person = createPerson('John', 30); These are the most common ways to create objects in JavaScript. Each method has its own advantag

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...

Node.js: Bundling your Node.js application to single executable for Windows.

In this article, we will see how to bundle Node.js application to a single executable for Windows. What's the need? Well recently, I had taken a work where I needed to convert pdf's(Of similar format) to excel sheet. So I was reading the pdf's from a folder in desktop and I was storing the output excel sheet into a separate folder on the desktop. I used Node.js for the program. Now the client wanted it to install the program on 25 windows machine and his budget was really low. So it was also not possible for me to install node.js for 25 machines and then install the required dependency for each one. One of the solution: While I was searching for an easy solution I found this amazing npm module pkg . This module can make your node.js app work like plug and play type. No need to install Node.js on the client machine or any other dependency.  It helps to make a commercial or trial version of your node.js application without exposing the source code. I found ...

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', 'Pyt...