Home Blog Page 9

JavaScript: Solutions to 5 Essential Interview Questions

0
javascript interview questions
JS questions

In today’s world JavaScript versatile & been widely-used as a programming language that plays an important role in modern web development. Being a JavaScript developer, It’s very important to understand the language’s fundamentals and also adept solving real-world problems. In JS job interviews, JavaScript Interview Questions is been often asked from basic syntax to advanced concepts.

In this article, We will dive into 11 JavaScript questions that are commonly asked in interviews. Each question will be explained in detailed with solution, complete with source code examples where required.

If are you getting prepared for you next job interview or simple learning to enhance your JS skill, this article will have practical solution with code example for better understanding.

5 Interview Questions for JavaScript Job preparation

1. Implement a function that serializes a JavaScript value into a JSON string.

In JS we have a In-Built method i.e. JSON.stringify() using which we can easily convert javascript object or value into JSON string.

function serializeToJsonString(value) {
  try {
    const jsonString = JSON.stringify(value);
    return jsonString;
  } catch (error) {
    console.error('Serialization error:', error);
    return null;
  }
}

// Example JS Object:
const data = {
  name: 'John Doe',
  age: 30,
  city: 'Example City'
};

const jsonString = serializeToJsonString(data);
console.log(jsonString);

In Above example we have a function which accept a data object and return a jsonString.


2. Write a JS function which performs a deep copy of a value, and also handles circular references.

Before going in above question let’s understand what is shallow copy and deep copy.

Shallow and Deep copy are concept in JS which is been used while working with object or array in javascipt:

Shallow Copy in JavaScript:

In below source code, I am creating a copy of originalObject using Assignment Operator (=) and then the copyed object shallowCopy is modified…

const originalObject = { a: 1, b: { c: 2 } };

// Shallow Copy using assignment operator
const shallowCopy =  originalObject;

console.log('Original Object: Before', originalObject);
console.log('Shallow Copy: Before', shallowCopy);

// Modifying the Shallow Copy
shallowCopy.b.c = 99;

console.log('Original Object:', originalObject);
console.log('Shallow Copy:', shallowCopy);

In Shallow Copy when you create a new object using originalObject, actually the shallowCopy points to same address to which originalObject is, Now when we modify shallowCopy the modification is made at address level, due to which originalObject will also get altered.

// OUTPUT
Original Object: Before { a: 1, b: { c: 2 } }
Shallow Copy: Before { a: 1, b: { c: 2 } }
__________________________________________
Original Object: { a: 1, b: { c: 99 } }
Shallow Copy: { a: 1, b: { c: 99 } }

Deep Copy in JavaScript:

In below example, JSON.stringify() is used to serialize the original object into a JSON string, and then JSON.parse() is used to parse it back into a new object.

Doing this will create a deep copy, making sure that original data is not modified when copy is modified.

// Original Object
const originalObject = { a: 1, b: { c: 2 } };

// Deep Copy using JSON.stringify() and JSON.parse()
const deepCopy = JSON.parse(JSON.stringify(originalObject));

// Modifying the Deep Copy
deepCopy.b.c = 99;

console.log('Original Object:', originalObject);
console.log('Deep Copy:', deepCopy);

Now, Let’s performs a deep copy of a value, and also handles circular references

Note: We are using NodeJS circular-json library to handle circular references with deep clone.

const CircularJSON = require('circular-json');

function deepCopyWithCircularHandling(obj) {
  try {
    const jsonString = CircularJSON.stringify(obj);
    const copy = CircularJSON.parse(jsonString);
    return copy;
  } catch (error) {
    console.error('Deep copy error:', error);
    return null;
  }
}

// Example usage:
const originalObject = {
  prop1: 'value1',
  prop2: {
    prop3: 'value3'
  }
};

originalObject.circularReference = originalObject;

const copiedObject = deepCopyWithCircularHandling(originalObject);
console.log(copiedObject);

In this example, the circular-json library is used to stringify and parse the object with circular references.


3. Create a Function in JS then accepts any numbers of arguments and returned memorized version

To Implement Memorization of data or we can say it as creating a cache of the data returned by a javascript function can be achieved by using caching technique.
Below Code example uses simple cache object.

function memoize(func) {
  const cache = {};

  return function (...args) {
    const key = JSON.stringify(args);

    if (cache[key]) {
      console.log('Fetching from cache');
      return cache[key];
    } else {
      console.log('Calculating result');
      const result = func(...args);
      cache[key] = result;
      return result;
    }
  };
}

// Example usage:
const sum = memoize((...args) => args.reduce((acc, val) => acc + val, 0));

console.log(sum(1, 2, 3)); // Calculating result
console.log(sum(1, 2, 3)); // Fetching from cache

4. How do you stop a setInterval() function

We can easily stop setInterval() function of javascript, by making use of clearInterval(intervalId) method. The clearInterval method accept a parameter i.e. the ID of setInterval() method by which be can stop further executions of setInterval() func.

var i = 0;
const intervalId = setInterval(()=>{
    
    console.log("i=> ",i)
    i++;
    if(i===5){
        clearInterval(intervalId)
    }
},1000);

The above code will stop execution of setInterval() when i value is 5.


5. How to Merge Two Object in JavaScript

There are many ways to merge or cancat two object into one, i.e. by using spread operator (...) or by uisng Object.assign() method.

The below example to merge two object using spread operator (...).

function mergeObjects(obj1, obj2) {
  return { ...obj1, ...obj2 };
}

// Example usage:
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 4 };

const mergedObject = mergeObjects(obj1, obj2);
console.log(mergedObject); // result: { a: 1, b: 2, c: 4 }

The below example to merge two object using Object.assign() method.

function mergeObjects(obj1, obj2) {
  // Create a new object and use Object.assign to merge obj1 and obj2
  const mergedObject = Object.assign({}, obj1, obj2);
  return mergedObject;
}

// Example usage:
const obj1 = { a: 1, b: 2 };
const obj2 = { b: 3, c: 4 };

const mergedObject = mergeObjects(obj1, obj2);
console.log(mergedObject); // result: { a: 1, b: 3, c: 4 }

JavaScript for…in Loop: Iterating an object

0
for…in object javascript

Hi Guy’s Welcome to Proto Coders Point, In this JS Article let’s under about looking in javascript using for…in loop.

for…in object javascript -How to iterate object in javascript

In Javascript, for…in loop statement is commonly used to iterate object over it’s properties also known a key of an object. This for…in loop is only recommended to used with object not with any array as the behavior might changed during iteration.

Syntax of for…in object loop

for (var key in object) {
    // code to be executed for each property/key
}

for…in loop example to iterate object to access it’s properties

const person = {
  firstName: "Rajat",
  lastName: "Palankar",
  age: 20,
  email: "contact@protocoderspoint.com"
};

for (var key in person) {
  console.log(key + ": " + person[key]);
}

Output

In above code we have an object by name person & I want to iterate it so for that I am using for…in loop to iterate the object over it’s properties.

Each loop it iterate has it’s key property and using that key we can access it’s corresponding value. The output is below:

firstName: Rajat
lastName: Palankar
age: 20
email: contact@protocoderspoint.com

Note: Use for…in loop use only on object, as it misbehave which used with arrays. For iterating an arrays it’s better to use for…of loop or forEach loop.

Similar Articles

convert array into collection

15 useful Javascript Snippets code

What Are DNS Records & What are the kinds of DNS records?

0
DNS Record

Simply typing a website’s address into a browser’s address bar will not bring up the desired page. Without it, we’d all have to commit long, difficult-to-remember IP numbers to memory in favor of more human-friendly domain names.

What are DNS records, and what kinds of DNS records are discussed in more detail below:

What is a DNS record?

Zone files, or DNS records, are stored in authoritative DNS servers and include information about a domain, such as its IP address and how to respond to queries for that domain. These are text files written in DNS syntax and include relevant information. DNS syntax is just a string of characters that serve as instructions for the DNS server. TTL, “time-to-live,” is included in every DNS record and specifies how often the DNS server will update the record.

A DNS record set is similar to a Yelp page for a company. All the pertinent details about a specific business, such as its address, operating hours, types of services it provides, etc., are included in that listing. A minimum number of DNS records must be present on every domain before it can be used to visit a website, and many more can be included for convenience.

What are the kinds of DNS records?

You may find crucial details about a domain or hostname in DNS records. Current domain IP addresses are stored in these entries.

Also, the authoritative DNS server uses text files called zone files to hold DNS records. DNS record files include text interpreted as a string by the DNS server and containing special directives.

Forms of Domain Name System Records

Below are the five most common kinds of DNS records:

  • A record
  • AAAA record
  • CNAME record
  • Nameserver (NS) record
  • Mail exchange (MX) record

Each of the categories, as mentioned earlier, serves a unique purpose. Therefore, let’s take a closer look at the various DNS record types.

1. A Record

DNS records come in various types, but none are more crucial than the A record. When you hear “A record,” you’re attending the phrase “address.” The IP address associated with a specific hostname or domain is displayed in an A record. A record is mainly used for IPv4 address lookup. An A record is required for a web browser to access a website by that domain name. Due to this, we may visit websites online without needing to know their IP addresses.

The A record is also utilized in a black hole list based on the domain name system (DNSBL). In this instance, spam is prevented by modifying the A record to reject messages from specific senders.

2. AAAA Record

Similar to how A records reveal a domain’s IPv4 address, AAAA records indicate the IPv6 address of a host. It’s important to note that this particular DNS record type is unique because it only resolves to IPv6 addresses.  IPv6 is superior to IPv4 because it provides more IP addresses. IPv6 resolves the problem of a lack of available IP addresses.

For DNS resolution, the AAAA record is preferable to the A record since it employs IPv6, which is more secure than IPv4. Also, the possibility for AAAA records is excellent because the Internet is expanding, and we’re running out of IPv4 addresses. Domain names require AAAA records to be resolved to use the more modern IPv6 protocol.

3. CNAME Record

Canonical Name (CNAME) records redirect traffic from one domain to another. However, the alias in a CNAME record does not resolve to a specific IP address. To clarify, the canonical name is the domain name that the alias redirects to.

4. NS record

The primary DNS server for a domain is identified in its nameserver (NS) record. In other words, the NS record indicates to internet programs like web browsers where they may locate a domain’s IP address. Typically, a domain will have many nameservers listed. Those who have purchased web hosting or created an essential website have likely been sent an email containing their nameserver information. Nameservers are the intermediaries between your domain and the server hosting your site. Other domain name server records, such as the A and MX records, are stored on the nameserver.

5. MX Record

A DNS record known as a mail exchange (MX) record specifies an email server that will receive messages addressed to a domain. So, an MX record allows email to be routed to a particular server.

Multiple MX records can exist for the same domain. That paves the way for the availability of emergency email servers.

How to perform the DNS Lookup?

Performing the DNS record lookup is simple and easy. You can use an online tool or perform that using a command.

Windows Command Prompt:

To perform a DNS lookup in Windows using the Command Prompt, you can use the `nslookup` or `ping` command. Here’s how to use both methods:

1. Using nslookup:

   – Open the Command Prompt by searching for “cmd” in the Windows Start menu.

   – Type the following command and replace “example.com” with the domain or hostname you want to look up:

   nslookup example.com

   – Press Enter. This will provide you with DNS information, including the IP addresses associated with the domain.

2. Using ping:

   – You can also use the `ping` command to perform a DNS lookup. Just type:

   ping example.com

   – Press Enter, and it will display the IP address of the domain along with some ping statistics.

Linux/Unix/macOS Terminal:

To perform a DNS lookup in Linux, Unix, or macOS, you can use the `nslookup`, `host`, or `dig` commands. Here’s how to use each of them:

1. Using nslookup:

   – Open your terminal.

   – Type the following command and replace “example.com” with the domain or hostname you want to look up:

   nslookup example.com

   – Press Enter.

2. Using host:

   – Open your terminal.

   – Type the following command and replace “example.com” with the domain or hostname you want to look up:

   host example.com

   – Press Enter.

3. Using dig:

   – The `dig` command provides more detailed DNS information. Open your terminal and type:

   dig example.com

   – Press Enter.

The output of these commands will provide you with DNS information, including the IP addresses associated with the domain. Choose the command that suits your needs and your specific operating system.

Merging Two Maps in Dart – Flutter

0
Merging Two Maps in Dart
How to merge two map in flutter

Hi Guy’s In this Tutorial, Let’s checkout how to merge 2 maps into one in flutter dart.

If you are working with dart programming language you might have come with situation when you want to combine 2 maps objects. For Example let’s say, a Map that stores name of a user, his phone number and email address and there is another map that contain that user house address, his family details etc. In such scenerio merging 2 maps in single map is benefit because all the information about user is one one data itself.

In this dart article, let’s walk through differents ways of join 2 maps in one.

1. Using (…) spread operator

2. Using addAll() method.

3. Using putIfAbsent() method.


Merging 2 Maps Object using spread operator

This is one way by which we can easily join/combine 2 map in one i.e using spread operator (…). By using thi approach two collection of maps are merged into one collection.

Example:

// main.dart

void main() {
  Map<String, int> map1 = {'a': 1, 'b': 2};
  Map<String, int> map2 = {'c': 3, 'd': 4, 'c': 5};

  Map<String, int> mergedMap = {...map1, ...map2};

  print(mergedMap);
}

Output:

{a: 1, b: 2, c: 5, d: 4}

Note: Here if there are duplicate keys present in the maps that you are merging then in such case the value of second map will be overwriten the value of first map. In above example as you can see key c value is 3 and same in map2 key c value is 5 so final result we get is c:5 that is from map2.


Merge 2 maps using addAll() method

Their is another way by which we can merge map in dart that is by using addAll() method, What this function does is it simply copy all the key & value from map 2 to map 1. let’s understand with an example

Example:

void main() {
  Map<String, int> map1 = {'a': 1, 'b': 2,'e':1};
  Map<String, int> map2 = {'c': 3, 'd': 4, 'e': 5};

  // merge map2 into map1
  map1.addAll(map2);

  print(map1);
 
}

Output:

{a: 1, b: 2, e: 5, c: 3, d: 4}

addAll() method copy all the key & value from map 2 and add it into map 1, That means addAll() method will directly modify the first map.


Merge 2 map using putifAbsent() method

As we saw in above ways, The value of a key is modified if same key is present. To solve this problem we can make use of putifAbsent() method. Let’s understand with an example

// main.dart
void main() {
  Map<String, String> map1 = {'firstname': "Rajat", 'lastname': "Palankar"};
  Map<String, String> map2 = {'address': "India", 'firstname': "NameChanged", 'website': "protocoderspoint.com"};

  map2.forEach((key, value) {
    map1.putIfAbsent(key, () => value);
  });
    print(map1);
}

Output:

{firstname: Rajat, lastname: Palankar, address: India, website: protocoderspoint.com}

This approach to join or merge 2 map is useful then you don’t want to keep duplicate data. In above example I am iterating map2 using forEach loop then checking is same key present in map 1, if not then add map 2 key and value in map 1 using putIfAbsent() and ignore it.


Sorting Arrays in Java: How to use Arrays.sort() Method

0
Arrays.sort() Java
sorting in java

Hi Guy’s, Java being the most popular programming language comes with an efficient & versatile sorting technique. In this Article let’s dive into a sorting method i.e. Arrays.sort(), This sorting technique enable the java developer with super power to sort an Array effortlessly and arranging the elements in ascending or descending order as per the requirement.

Arrays.sort() java

Arrays.sort() is robust method using which a developer can sort arrays of primitive data types or an objects.

Syntax

Arrays.sort(arrayList);

Sorting array of object in java

To sort an array of objects, we need a custom comparator or ensure that the array implement the comparable interface.

Arrays.sort(arrayList,Comparator);


Code Example to use Arrays.sort() method

1. Sorting an array of integers

import java.util.Arrays;

public class ArraySortExample {
    public static void main(String[] args) {
        // Sorting an array of integers
        int[] intArray = {5, 2, 9, 1, 5, 6};
        System.out.println("Original integer array: " + Arrays.toString(intArray));
        Arrays.sort(intArray);
        System.out.println("Sorted integer array: " + Arrays.toString(intArray));
    }
}
Original integer array: [5, 2, 9, 1, 5, 6]
Sorted integer array: [1, 2, 5, 5, 6, 9]

2. Sorting Array of strings

import java.util.Arrays;

public class ArraySortExample {
    public static void main(String[] args) {
        // Sorting an array of strings
        String[] stringArray = {"banana", "apple", "cherry", "date", "elderberry"};
        System.out.println("Original string array: " + Arrays.toString(stringArray));
        Arrays.sort(stringArray);
        System.out.println("Sorted string array: " + Arrays.toString(stringArray));
    }
}
Original string array: [banana, apple, cherry, date, elderberry]
Sorted string array: [apple, banana, cherry, date, elderberry]

3. Sorting Array of Object

In below sorting an array of object, I am sorting the object by name.

import java.util.Arrays;

public class ArraySortExample {
    public static void main(String[] args) {
        // Sorting an array of custom objects
        Person[] personArray = {new Person("John", 30), new Person("Alice", 25), new Person("Bob", 35)};
        System.out.println("Original Person array: " + Arrays.toString(personArray));

        Arrays.sort(personArray, (a, b) -> a.getName().compareTo(b.getName()));
        System.out.println("Sorted Person array by name: " + Arrays.toString(personArray));
    }

   // class 
    static class Person {
        private String name;
        private int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public String toString() {
            return "Person{name='" + name + "', age=" + age + "}";
        }
    }
}
Original Person array: [Person{name='John', age=30}, Person{name='Alice', age=25}, Person{name='Bob', age=35}]
Sorted Person array by name: [Person{name='Alice', age=25}, Person{name='Bob', age=35}, Person{name='John', age=30}]

The above code example is to demonstrates how to use ‘Arrays.sort()’ method for aorting datatype like integersm string and a class object in java.

How to convert an object into JSON in Flutter

0
Convert Object to JSON IN flutter DART

Hi Guys, Welcome to Proto Coders Point, In this Flutter dart article we will walk through How to convert an Object i.e. (Class Instance) into an JSON in Flutter dart.

1. Own Code to convert object to JSON without Library

The below example is manual way to convert object into JSON in flutter dart.

Below Steps:

  1. Create a class
  2. The class has a method to convert object into a Map.
  3. Finally convert the Map object to JSON String using JsonEncode() method.

Code

// main.dart
import 'dart:convert';

// Define a class
class User {
  final String userame;
  final int userage;
  final bool isMarried;

  User(this.userame, this.userage, this.isMarried);

  // Define a toJson method to convert User object to JSON
  Map<String, dynamic> toJson() {
    return {
      'name': userame,
      'age': userage,
      "isMarried": isMarried,
    };
  }
}

void main() {
  User user = User('Shubham', 25, true);

  // Convert User object to JSON
  String jsonString = jsonEncode(user.toJson());
  print(jsonString);
}
{"name":"Shubham","age":25,"isMarried":true}

The object code is manual method is flexiable, It is self written code that can convert object into json string and it don’t use any external library or dependencies.


2. Convert Object to JSON using json_serializable package

We will make use of json_serialiable using which we can generate code from JSON serialization & deserialization.

Steps:

1. Install required dependencies:

we need:

To install all the above 3 package run below command:

flutter pub add json_annotation json_serializable build_runner

then run

flutter pub get

2. Now, In Lib directory let’s create a file by name “user.dart” & then create class User & define it with @JsonSerializable() annotation example code below

import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable()
class User {
  String name;
  int age;

  // Use JsonKey to change the name of the field in JSON
  @JsonKey(name: 'is_admin')
  bool isAdmin;

  User(this.name, this.age, this.isAdmin);

  // The generated toJson method
  Map<String, dynamic> toJson() => _$UserToJson(this);

  // The generated fromJson method
  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
}

3. user build_runner to generate JSON Serialization using below command

dart run build_runner build

By running above cmd a new file will get generated by name User.g.dart in the same directory where your class file exist.

generate JSON Serialization

You not need to enter the above code or edit anything in User.g.dart, as the code get automatically ganerated by build_runner.

4. Now simply use the ganeted code function i.e toJson() method that help you convert Object to JSON, if you want you can also use fromJson() to convert JSON data to an Object.

Below Code example

// lib/main.dart
import 'dart:convert' show jsonEncode;
import 'package:flutter/foundation.dart' show kDebugMode;
import 'user.dart';

void main() {
  // Create a user object
  User user = User('Puppy Kute', 25, true);

  // Convert the user object to JSON
  Map<String, dynamic> jsonUser = user.toJson();

  // Print the JSON string
  if (kDebugMode) {
    print(jsonEncode(jsonUser));
    // Prints: {"name":"Puppy Kute","age":25,"is_admin":true}
  }

  // Create a list of user objects
  List<User> users = [
    User('Shubham', 40, false),
    User('Pavan', 50, true),
    User('Rajat', 28, false),
  ];

  // Convert the list of user objects to a JSON string
  List<Map<String, dynamic>> jsonUsers =
      users.map((user) => user.toJson()).toList();

  // Print the JSON string
  if (kDebugMode) {
    print(jsonEncode(jsonUsers));
  }
}
 [{"name":"Shubham","age":40,"is_admin":false},{"name":"Pavan","age":50,"is_admin":true},{"name":"Rajat","age":28,"is_admin":false}]

Conclusion

In this article we learn 2 ways by which we can convert Object to JSON. One is by self written code and another is by using external library’s like JSON_Serializable and build_runner.

Similar Articles

JSON in 2 Minutes

How to read json file in flutter & display a listview

Auto Create Model from JSON File in Flutter

Parse JSON data in flutter