Most important JavaScript Interview Questions To Prepare

Table of Contents

In this Page we have collected and explained Most important Javascript Interview Questions and Answers for begineers, freshers as well as experienced.

JavaScript is a scripting language created by Brendan Eich in 1995. It is a web development language used by almost all websites to make dynamic web pages. Javascript can directly use with the HTML of web pages and it executes when the webpage loads on the browser.

Previously Javascript was used for the client side only now it is used widely for both client-side and server-side development.

Some latest javascript library for client-side is Rect.js, vueJs, Next.js, and the Server side popular library is Next.js.

We can develop mobile apps, Web apps, web servers, real-time applications, online streaming applications, games, etc using Javascript.

Javascript interview questions

Q1). What is JSON? Tell its operations.

Ans:

JSON stands for Javascript Object Annotation and is a text file with an extension of .json. It is used to transmit data across a network between servers and web applications. It is an alternate of XML. 

Key and Value is two primary parts of JSON. the key is always a string enclosed in quotation marks and the value can be a string, number, boolean expression, array, or object.

Eg: 

    โ€œkeyโ€:โ€valueโ€

Parsing: Parsing means converting a string to a native object. Data received from the web server is always a string. And after parsing String data using JSON.parse(), data becomes a JavaScript object.

For Eg:

const obj = JSON.parse('{"name":"Javascript", "age":50, "city":"California"}');

Stringification: Stringification means converting a native object to a string. Data that have to send over the web server should be in string format. So using JSON.stringify() we convert 

JavaScript object into a string to send over to the server.

For Eg: 

const obj = {name: "Javascript", age: 50, city: "California"};

const myJSON = JSON.stringify(obj);

Q2). List of some data types present in javascript?

Ans:

JavaScript has typeof operator  To know the type of a variable.

Primitive types

1). String โ€“ String is a series of characters and it can be written with quotes. We can use a single or a double quote to represent a string.

Example :

var str1 = "Hello"; or

var str2 = 'Javascript'; 

2). Number โ€“ Number represents a number with or without decimals.

Example :

var num1 = 2; //without decimal

var num2 = 2.8; //with decimal

3). BigInt – This is used to store the larger numbers. This number will be above the limitation of the Number data type.

Example :

var bigInteger = 234567890123456789012345678901234567890;

4). Boolean โ€“ Boolean can have two values true or false that represent a logical entity. It is used to perform conditional-based checks.   

Example :

var num1 = 1;

var num2 = 2;

var num3 = 2;

(num2 == num3) // returns true

(num1 == num2) //returns false

5). Undefined โ€“ Undefined means a variable is declared but not assigned with any value. Example :

var x; // value of x is undefined

6). Null – Null means there is no value assigned to a variable.

Example :

var num = null;

7). Symbol – In the ES6 version of javascript this Symbol data type was introduced. It is used to store unique and anonymous values.

Example :

var symbol1 = Symbol('symbol');

Non-primitive types

1). Object: It is an instance through which we can access members.

const person = {

  firstName: "JavaScript",

  age: 20

};

console.log(person.age);

2). Array:

It is used to store the group of elements.

const name = ["pawan", "priya", "pramod"];

console.log(name);

Q3). What is slice() method in Javascript?

Ans:  slice() is a javascript method that returns the selected elements from an array as a new array object. It selects the elements from the given starts up to the given ends where the given end is not included in the result. 

If we use slice() method, our original array remains the same and unchanged, it returns the subset as a new array.

Example of slice method:

let arr = [1, 2, 3, 4, 5, 6, 7];

let arr1 = arr.slice(0, 2);
// Output will be [1,2]

let arr2 = arr.slice(1, 5);
// Output will be [2,3,4,5] 

let arr3 = arr.slice(4);
// Output will be [5]

Q5). What is splice() method in Javascript?

Ans:

In Javascript, splice() method is used to add or remove the array items. It returns the removed item of an array.

The Syntax of the splice method is 

array.splice(index, howmany, item1, ….., itemX

index : a position to add/remove items 

howmany : number of items to remove. It is optional.

item1, ….., itemX : New item to add. It is optional.

Splice method performs the operations on the original array and modify the original array and returns the deleted array.

Example of splice() method :

let arr1 = [1, 2, 3, 4, 5, 6, 7];
let arr2 = [1, 2, 3, 4, 5, 6, 7];
let arr3 = [1, 2, 3, 4, 5, 6, 7];
let arrOutput1 = arr1.splice(0, 2);
// Output will be [1, 2]; original array: [3, 4, 5, 6, 7]
let arrOutput2 = arr2.splice(3);
// Output will be [4, 5, 6, 7]; original array: [1, 2, 3]
let arrOutput3 = arr3.splice(3, 1, "a", "b", "c");
// Output will be [4]; original array: [1, 2, 3, "a", "b", "c", 5, 6, 7]

Q5). What is the difference between slice and splice?

Ans:

Some of the differences between slice and splice methods are: 

  • Slice method doesn’t modify the original array whereas Splice Modifies the original array.
  • Slice method returns the subset of the original array but the Splice method returns the deleted element only as output.
  • Slice method is used to pick the elements from the array to return whereas Splice is used to insert or delete elements to/from an array.

Q6). What is the difference between == and === operators.

Ans:

Both operators == and === are used to compare two values in JavaScript, But there is some difference between them.

== operator in JavaScript is used for comparing two values, but ignores the datatype of the variable Whereas === operator also compares two values, but it checks the datatype of values.

For Example:

console.log(8 == "8");

console.log(2 === "2");

Output:

true

false

For Example:

console.log(0 == false);

console.log(0 === false);

Output:

true

false

Q7). List some of the databases supported by Hibernate.

Ans :

Some list of databases supported by Hibernate are :

  • MySQL
  • PostgreSQL
  • Oracle
  • Microsoft SQL Server Database
  • Sybase SQL Server
  • HSQL Database Engine
  • DB2/NT
  • Informix Dynamic Server
  • FrontBase

Q8) What is a Session in Hibernate?

Ans:

  • Session is a lightweight object that is created on demand. Session provides the physical connectivity between the applications and the database.
  • Whenever we want to access any data or perform any operations on the database, a session is established. And once the operation is completed session is destroyed.
  • Persistence objects are saved and retrieved by the Session object.
  • Session offers operations like create, read, and delete for instances of mapped entity classes.

Q9) What is a SessionFactory?

Ans:

  • SessionFactory is a factory of session objects that keeps all DB-related property details that are pulled from either hibernate.cfg.xml or hibernate.properties files. 
  • SessionFactory is a heavyweight and threadsafe object that is created when the application starts. As the SessionFactory object is threadsafe it can be used by multiple threads in an application.
  • SessionFactory implementation is created per database in an application. If there is multiple databases in a table then we have to SessionFactory for each database.

Q10) Is SessionFactory a thread-safe object?

Ans:

Yes, SessionFactory is thread safe object and it can be used by all the threads in an application.

Q11) Tell some technologies that are supported by Hibernate.

Ans:

Some technologies that are supported by Hibernate are

  • XDoclet Spring
  •  Maven
  •  Eclipse Plug-ins
  • J2EE

Q12) How is SQL query created in Hibernate?

Ans:

To work with SQL query in Hibernate, we will be using Session.createSQLQuery(String query). This will create an SQLQuery object and execute it.

Suppose you want to read all the Student data from Student Table in Database, We can use the below code

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.getCurrentSession();
Transaction transaction = session.beginTransaction();
SQLQuery query = session.createSQLQuery(โ€œselect stu_name, stu_roll from Studentโ€);
List<Object[]> rows = query.list();
for(Object[] row : rows){
Student stu = new Student();
stu.setName(row[0].toString());
stu.setRoll(row[1].toString());
System.out.println(stu);
}

Q13). what is lazy loading in hibernate?

Ans:

Lazy loading in hibernate means donโ€™t load the child data when the parent date is loading/fetching.

For example, Suppose we have two tables Customer and OrderDetail . A Customer can have multiple orders which is maintained in the OrderDetail table. Now when we load the Customer details then only customer information should be load no Order detail should load.

Q14) What is HQL?

Ans:

HQL stands for Hibernate Query Language, is an object-oriented query language. It works with persistent objects and their properties whereas SQL works with tables and columns.

HQL queries are translated by Hibernate into conventional SQL queries, which in turns perform action on the database.

Q15). Difference between SessionFactory.getCurrentSession() and SessionFactory.openSession() methods?

Ans:

  • openSession() need to flush and close session objects explicitly but getCurrentSession() needs not to flush and close session objects explicitly, it is taken care by Hibernate internally.
  • openSession() wonโ€™t require any configuration but getCurrentSession() method requries additional configure in hibernate.cfg.xml file.
  • openSession() is slower than getCurrentSession() in single threaded environment.

Q16). Difference between first-level cache and second-level cache?

Ans:

  • First-level cache always Associates with the Session object whereas the Second-level cache always associates with the Session Factory object.
  • The first-level cache is a session-level cache but Second level cache is a session factory-level cache.
  • First level cache is enabled by default but the second-level cache is not default.
  • First level cache is available only within a session but Second level cache is available across all session.

Q17). Dfference between session.save() and session.persist() method.

Ans:

  • session.save() return type is Serializable object whereas session.persist() method return type is void type.
  • save() is supported by only hibernate whereas persist() is supported by JPA as well.
  • save() method works outside the Transaction boundaries or without the transactions whereas persist() wonโ€™t work without the Transactions.

Q18). Differentiate between save() and saveOrUpdate() methods in hibernate session.

Ans: 

Save()
  • save() method is used to save the data in the database. If there is similar data available in the table for eg: inserting an id that is already available, It will through exception. It will only save the fresh new data. 
  • Save() returns a Serializable object from which we can get the id and can cast it into Integer.
SaveOrUpdate()
  • SaveOrUpdate() method is a combination of the save and update method. It first performs a save operation in the database if the record is new. If the record is already present in the database then it will update the database. 
  • SaveOrUpdate() wonโ€™t return anything because its return type is void.

Q19). Differentiate between get() and load() in Hibernate session.

Ans:

  • Both get() and load() methods are used to fetch data for the given identifier in hibernate. 
  • Both methods belong to Hibernate session class. 
  • The Difference is If no row is available in the database or in the session cache for a given identifier Get() method return null, whereas the load() method throws an object not found exception. 
  • get() method is slower in comparison to load() method in hibernate.
  • Use the get() method if you are not sure that data is available, otherwise, if you are sure that data is available then use the load() method.

Q20). What are the states of a persistent entity?

Ans:

4 stages of persistent entity are

  • New (Transient)
  • Persistent (Managed)
  • Detached (Unmanaged) 
  • Removed (deleted)

Q21). What is the One-to-One association in Hibernate?

Ans:

  • One-to-One mapping in Hibernate means One instance of an entity is associated with another instance of the other entity.
  • An example of this one-to-one mapping will be One person can have only one passport, and one passport can be associated with only one person.
  • @OneToOne annotation is used in a One-to-One association to map a source entity to a target entity.

Q22). What is the Many-to-Many association in Hibernate?

Ans:

  • In Many-to-Many associations, in Hibernate multiple instances of an entity can belong to multiple instances of another entity.
  • Annotation @ManyToMany is uses in Many-to-Many associations.
  • For example, A ShoppingCart can have multiple items and A item can belong to multiple shoping cart.

Q23). How do you create an immutable class in hibernate?

Ans:There are two ways to create an immutable class in hibernate:
1). Mark a class as mutable=”false” After marking class will be treated as an immutable class. By default, it is mutable=”true”.
2). You can use @Immutable annotations with the class to mark the class as immutable.

Q24). What are the states of the object in hibernate?

Ans:

In hibernate, An object can have three states: transient, persistent, and detached.

Q25). Explain hibernate mapping file.

Ans:Hibernate framework uses Hibernate mapping file to get the information about the mapping of a POJO class and a database table. Following details contains in mapping information:

  • Information about the mapping of a POJO class name to a database table name.
  • Information about Mapping POJO class properties to database table columns.

Hibernate mapping elements

  • hibernate-mapping: hibernate-mapping is a root element.
  • Class: Mapping of a POJO class to a database table.
  • Id: Primary key or Unique key of the table.
  • generator: Sub element of the id element to automatically generate the id.
  • property: It defines the mapping of a POJO class property to the database table column.

Q26). Difference between setMaxResults() and setFetchSize() of Query.

Ans:

setMaxResults()
  • setMaxResults is similar to LIMIT in SQL. setMaxResults returns the number of rows you are setting.
  • For example, in a table, we have 50 rows. setMaxResults(20) will return only 20 rows as result.
  • criteria.setMaxResults(20);
setFetchSize()
  • setFetchSize is about optimization, Instead of returning all rows at one time, It returns rows in a chunk given in setFetchSize .
  • setFetchSize is NOT implemented by all database drivers.
  • For example in a table, we have 50 rows. setFetchSize(20) will return only 20 rows at a time until reads all rows from a table.
  • criteria. setFetchSize(20);

Q27). Difference between sorted and ordered collection in Hibernate?

Ans:

  • Sorted collection in hibernate means sorting the collection by utilizing the features provided by the Java collections framework.
  • This sorting happens in JVM memory so If your collection is not large then it is an efficient way to sort otherwise it will throw an Out of Memory error.
  • Order collection is also used to sort a collection by specifying the order-by clause in the query.
  • It is a Good Choice If your collection is very large. It is fast compared to the sorted collection.

Q28). Difference between the transient, persistent, and detached state in Hibernate?

Ans: 

transient

A new instance of a persistent class that is not associated with a Session, has no representation in the database and no identifier value is considered transient by Hibernate.
Example:

Student student = new Student();
student.setName("Pawan");
// student is in a transient state
Persistent

A persistent instance has a representation in the database, an identifier value, and is associated with a Session. You can make a transient instance persistent by associating it with a Session.

Long id = (Long) session.save(student);
// student is now in a persistent state
Detached

Now, if we close the Hibernate Session, the persistent instance will become a detached instance: it isn’t attached to a Session anymore (but can still be modified and reattached to a new Session later though).

session.close();
//user in detached state

29). Is hibernate prone to SQL injection attacks?

Ans:

  • Hibernate does not provide 100% security to SQL Injection, one can misuse the api. HQL (Hibernates subset of SQL) wonโ€™t have any special that makes it any more or less susceptible.
  • Functions such as createQuery(String query) and createSQLQuery(String query) create a Query object that will be executed when the call to commit() is made. If the query string is written for SQL injection It might hurt the database.

30). Mention some important annotations used for Hibernate mapping.

Ans:

List of some Hibernate annotations are

@Entity
All Entity beans annotated with @Entity

@Entity
public class Student implements Serializable {
...
}

@Table

Specify the database table name where data will be stored.

@Entity
@Table(name = "student")
public class Student implements Serializable {
...
}

@Column
This annotation denotes the column in the table for mapping.

@Entity
@Table(name = " student ")
public class Student implements Serializable {
@Column(name = "name")
private String name;
...
}

@Id
Annotate the id column using @Id.

@Entity
@Table(name = "student")
public class Student implements Serializable {
@Id
@Column(name = "id")
private int id;
...
}

@GeneratedValue
Let the database generate (auto-increment) the id column.

@Entity
@Table(name = " student ")
public class Student implements Serializable {
@Id
@Column(name = "id")
@GeneratedValue
private int id;
...
}

@Version
Control versioning or concurrency using @Version annotation.

@Entity
@Table(name = " student ")
public class Student implements Serializable {
@Version
@Column(name = "version")
private Date version;
...
}

31). What is hibernate caching? Types of Hibernate Caching.

Ans:

Caching is a mechanism to enhance the performance of a system by pooling the object in the cache.

Cache is a buffer memory that resides between the application and the database. It stores recently used data to reduce the number of database hits.

There are mainly two types of caching:

  • First Level Cache: Session object holds the first level cache data.
  • Second Level Cache : SessionFactory object holds the second level cache data.

32). What is Dirty Checking in Hibernate?

Ans:

  • Dirty checking is a feature of Hibernate that avoids time-consuming write actions in database.
  • It modifies or updates fields that need to be changed or updated and keep the remaining fields untouched and unchanged.
  • @DynamicUpdate annotation is used with entity class to access dirty checking. This annotation makes the necessary modifications and changes to the required fields only.
What did you think?

Similar Reads

Hi, Welcome back!
Forgot Password?
Don't have an account?  Register Now