0% found this document useful (0 votes)
9 views

Javascript Questions and Answers

This document provides a comprehensive overview of JavaScript, covering fundamental concepts such as variable declaration, data types, functions, asynchronous programming, and DOM manipulation. It explains key differences between various JavaScript features, including operators, hoisting, and event loops, while also detailing methods for working with arrays and objects. Additionally, it introduces ES6 features and common array methods, along with best practices for avoiding callback hell and managing asynchronous code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Javascript Questions and Answers

This document provides a comprehensive overview of JavaScript, covering fundamental concepts such as variable declaration, data types, functions, asynchronous programming, and DOM manipulation. It explains key differences between various JavaScript features, including operators, hoisting, and event loops, while also detailing methods for working with arrays and objects. Additionally, it introduces ES6 features and common array methods, along with best practices for avoiding callback hell and managing asynchronous code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 84

JAVASCRIPT QUESTIONS AND ANSWERS

1.What is JavaScript?

●​ JavaScript is a widely used programming language which is used to add


interactivity and dynamic nature to webpages.
●​ JavaScript can improve websites user experience from displaying content
updates, maps, animations, scrolling videos etc…
●​ With the introduction of NodeJS, JavaScript can also be used for server-side
development.

2.Is JavaScript single-threaded or multi-threaded?

●​ JavaScript is a single-threaded language which means it executes one task at


a time in a single sequence, so each operation blocks the execution until it
completes.
●​ However, JavaScript also supports Asynchronous programming through the
use of callbacks, promises and async/await syntax. These operations allow
JavaScript to perform tasks without blocking the main execution thread.
●​ Ex: fetch data, running animations, etc…

3.How do you declare variables in JavaScript?

●​ Variables can be declared using var, let, or const keywords.

4.What is the difference between var, let and const?

●​ var, let, and const are all used for variable declaration in JavaScript, but they
have some differences in terms of scope, hoisting, and reassignment.
●​ VAR: Variables declared by var are available throughout the function / Global
scope and var variables can be hoisted. var allows redeclaration and
reassignment of variables within the same scope.
●​ LET: Variables declared by let are only available inside the block scope and
they can’t be hoisted. let allows reassignment of variables, but not
redeclaration.
●​ CONST: Variables declared with const are block-scoped like let. Unlike var
and let, variables declared with const must be initialised during declaration,
and their value cannot be changed later.

var Example :

let example:

const example :

5. What are the data types in JavaScript?

●​ In JavaScript data types are divided into two parts Primitive Datatypes and
Non-primitive Datatypes.
●​ Primitive Datatypes: Number, String, Boolean, Null, Undefined, Symbol.
●​ Non-Primitive Datatypes: Object, Array.

6. What is the difference between primitive and non-primitive datatypes?

●​ Primitive datatypes are Immutable and non-primitive datatypes are mutable.


●​ Primitive datatypes only access a single value and non-primitive datatypes
can store multiple values.

7. What is the difference between Null and Undefined?

●​ Null is used to represent an intentional absence of a value or we can say Null


is an assignment value. It can be assigned to a variable as a representation of
no value.
●​ Undefined indicates a variable that has been declared but not assigned a
value.

8. What is the difference between == and === in JavaScript?

●​ Both == and === are used to compare the values. == will only check if the
values are equal but === checks the value and also the type of data.
9.What is a Function in JavaScript?

●​ A function in JavaScript is a block of code that performs a specific task.


●​ It is a way to group a set of instructions together and execute them as a single unit.

10. How do you create functions in JavaScript?

●​ Functions can be created using the function keyword followed by the function
name and a set of parentheses that contain the parameters.
●​ Ex:

11.What are the different types of functions in Javascript?

●​ There are several types of functions in Javascript , each one has a different
purpose. Here are some commonly used functions :

●​ Named Functions: These are functions with a specific name defined using the
function keyword. They can be called by their name.
●​ Ex:
●​ Arrow Functions: Introduced in ES6, arrow functions provide a more concise
syntax compared to traditional functions.
●​ Ex:

●​ Anonymous Functions: These are functions without a name. They are often
used as callbacks or assigned to variables.
●​ Ex:

●​ Immediately Invoked Function Expressions (IIFE): These are functions that


are executed immediately after they are defined. They are typically used to
create a local scope.
●​ Ex:

●​ Callback Function: A callback function is a function which is passed as an


argument into another function.
●​ Ex:
●​ Higher-Order Functions: A higher-order function is a function which takes one
or more functions as its arguments.
●​ Ex:

12. What are arrow functions in JavaScript?

●​ Arrow functions are a shorthand syntax for writing anonymous functions,


which is introduced in ES6.
●​ Arrow function defines using arrow syntax and it does not have its own
arguments.
●​ Ex:
13.What are Operators in Javascript?

●​ The Operators are special symbols or keywords that are used to perform
operations on operands, such as arithmetic calculations, logical comparisons, or
value assignments.

14.What are the different types Operators in Javascript?

●​ There are several types of operators in JavaScript. Here are some main types of
operators :

●​ Arithmetic Operators : Used for arithmetic operations such as addition,


subtraction, multiplication, division, and modulus.
Ex:

●​ Assignment Operators : Used to assign values to variables.


●​ Ex:

●​ Logical Operators: Used to perform logical operations and return a boolean


result.
●​ Ex:
●​ Comparison Operators: Used to compare two values and return a boolean
result.
●​ Ex:

●​ Conditional (Ternary) Operators: A shorthand (short syntax) for an if-else


statement.
●​ Ex:
●​ Unary Operator: Operate on a single operand.
●​ Ex:

●​ Type Operator: the typeof operator is used to find out the type of a variable or
an expression.
●​ Ex:

●​ Bitwise Operator: Bitwise operators in JavaScript perform operations on binary


representations of numbers.
15.What is the difference between Operators and Operand?

●​ An operator is the 'function' or a symbol that performs the operation, whereas the
operand is the input to that function.
●​ Ex: c = a + b; Here, '+' is the operator known as the addition operator, and 'a' and
'b' are operands.

16. Explain hoisting in JavaScript?

●​ Hoisting is a JavaScript behaviour where variables and function declarations


are moved to the top of their scope. Hoisting allows functions and variables to
be used before they are declared.
●​ It only works when we declare the variable using var.
17. Explain Event loop in JavaScript?

●​ Event loop is a key concept in JavaScript that handles asynchronous


operations. It is responsible for managing the execution of code in a
non-blocking manner.
●​ When callstack is empty, if there are any tasks in the call back queue event
loop pushes the task into the call stack for execution. If the callstack is not
empty, it waits until callstack is empty then pushes the next task for execution.
18. Difference between Synchronous and Asynchronous operations?

●​ Synchronous code will block further execution of the remaining code until it
finishes the current one.
●​ Synchronous code executes only one task at a time in a sequence.

●​ Asynchronous operations are run independently allowing the program to


continue in a non-blocking manner or without blocking the main execution
thread.

19. What are the ways to write Asynchronous code?

●​ There are mainly three ways in which we can code asynchronism in


JavaScript:
●​ Callback functions,
●​ Promises,
●​ async-await.

20. What is a callback function?

●​ If you pass a function inside another function as an argument, that function is


called a callback function. These callbacks are mainly used in asynchronous
operations.
21. What is a callback hell?

●​ Callback hell refers to a situation in asynchronous operations where the code


becomes to read and maintain due to the excessive nesting of callback
functions.
●​ Callback hell is also called as Pyramid of Doom because it has a pyramid like
structure.
22. How to avoid callback hell?

●​ To avoid callback hell we use promises , async/await or modularize the code


into smaller functions.

23. What is a Higher-order function?

●​ If a function takes one or more functions as its arguments and returns a


function as its result is called a higher-order function.
●​ In below code applyOperation is higher order function

24. What are promises in JavaScript?

●​ Promises are a way to handle asynchronous operations more elegantly.


●​ Promises have 3 states: Fulfilled, Pending and Rejected.
●​ The ‘. then’ method is used to handle the fulfilment and ‘catch’ method is used
to handle the rejection.
25.How many arguments hold promises?

●​ Two arguments hold promises:


●​ myResolve() -- if the promise is resolved.
●​ myReject() -- if the promise is rejected.

26. What are async/await in JavaScript?

●​ Async/await is a JavaScript feature that allows you to write asynchronous


code that looks and behaves like synchronous code.
●​ The async keyword is used to define an asynchronous function. An
asynchronous function is a function that returns a promise. The await
keyword is used to wait for a promise to resolve before executing the next line
of code.
27. What are the different ways to define objects in JavaScript?

●​ There are several ways to define objects in JavaScript. Here are some
common methods:

Simple way using { } :

Object.create method:
“new” keyword :

28.What is ES6?

●​ ES6, also known as ECMAScript 2015.


●​ Here are some new features introduced in ES6:
●​ Arrow functions, let and const, destructuring, spread syntax, Default
Parameters.

29.What are some array methods added in ES6?

●​ ES6 added array methods like find(), findIndex(), includes(), entries(), keys(),
values(), and from().

30. What is the difference between setTimeout() and setInterval()?

●​ setTimeout() executes a function after a specified delay which you have


mentioned in the function but, setInterval() repeatedly executes a function at
specified intervals which we have mentioned in the function.
●​ ( Examples at Question number 90 and 91 )
31. What are pure functions?

●​ A pure function in JavaScript is a function that always returns the same


output given the same inputs, with no side effects. In other words, a pure
function does not depend on any external state or data change during a
program’s execution, and it only depends on its input arguments.​

32. What is an IIFE (Immediately Invoked Function Expression)?

●​ IIFE (Immediately Invoked Function Expression) is a JavaScript function


that runs as soon as it is defined.
●​ They are typically used to create a local scope for variables to prevent them
from polluting the global scope.

Ex: 1

Ex: 2

33. What is this keyword in JavaScript?

●​ This keyword refers to the object that the current function is being executed in
or the nearest object.
34. What are some commonly used array methods in JavaScript?

●​ Some of the common array methods are:


●​ push(), pop(), shift(), unshift(), splice(), slice(), concat(), join(), map(), filter(),
reduce(), forEach(), every(), some(), find(), and indexOf().

Ex: push() , pop() , shift() , unshift() methods examples.

concat() : is used to merge the arrays.

join() :
every() : it checks every element in array satisfies the condition or not

find() : it is used to find the elements which satisfy the condition.

indexOf() : index value of the passed value.

35. What is the difference between slice and splice method?

●​ slice() returns a shallow copy of a portion of an array into a new array. It will
not affect the main array.

●​ splice() changes the contents of an array by removing or replacing elements.


It will affect the array.
36. How do you clone an object in JavaScript?

●​ Cloning an object in JavaScript is done in several ways:


●​ Spread operator

●​ Object.assign()

●​ JSON.parse(JSON.stringify())

37. What is DOM?

●​ The DOM (Document Object Module) is an interface that represents the


structure and contents of a html document in a tree-like structure, where each
element is a node, so developers can easily access those nodes to
dynamically update the webpage.
38.What is a document in javaScript?

●​ In JavaScript, a document is an object that gives access to and manipulates the


currently loaded HTML document. It is a part of the window global object, which
represents the window of the current web page.

39.What is document.write() in javaScript?

●​ The document.write() is a method used to write the content directly in the html
document or in the browser.

40. What is a DOM event and give some examples?

●​ DOM events are actions that occur in a web page or browser, like clicking a
button, typing on the keyboard, or resizing the window. When an event
occurs, it can trigger a specific function or set of instructions to be executed.
●​ Some of the common DOM events are:
●​ Click: This event occurs when the user clicks on an element.
●​ Mouseover/Mouseout: These events occur when the mouse pointer moves
over or out of an element, respectively.
●​ Submit: This event occurs when a form is submitted, either by clicking a
submit button or pressing Enter while focused on a form field.
●​ Load: This event occurs when you load the page or refreshes the page.
●​ Keydown/Keyup: These events occur when a key on the keyboard is
pressed down or released.
41. How do you select an element in the DOM?

●​ To select an element in the DOM we use methods like


document.getElementById() , document.querySelector(), or
document.getElementByClassName() depending on the selection criteria.

42. What is the difference between innerText and innerHTML?

●​ The innerText and innerHTML properties are both used to manipulate the
content of HTML elements in JavaScript, but they behave differently:
●​ innerText : if we use innerText it returns the visible content of the specific
element, excluding any HTML tags.
●​ innerHTML : if we use innerHTML it returns the HTML content of the specific
element along with the HTML tags.
43. What is forEach method in JavaScript?

●​ forEach is a method in JavaScript used to loop over elements in an array or


array-like object. It executes a provided function once for each element in the
array.
●​ It will not return the array. , it simply iterates the array and executes the
provided function.

44. What is a map method in JavaScript?

●​ Map method is used to create a new array by applying a function to each


element in the original array.
●​ It returns the new array after applying a function to every element in the
original array.
45. What is the filter method in JavaScript?

●​ Filter method is used to create a new array with elements that satisfies the
specific condition which we’ll provide.

46. What is the difference between map and filter method?

●​ The map() method creates a new array by applying a function to each


element of the original array.
●​ Filter method is used to create a new array with elements that satisfies the
specific condition which we’ll provide.
Map :

Filter :
47. What is the reduce method in JavaScript?

●​ The Javascript array.reduce() method in JavaScript is used to reduce the


array to a single value and executes a provided function for each value of the
array (from left to right) and the return value of the function is stored in an
accumulator.

48.What is the difference between an attribute and a property?

Attribute:
●​ An attribute is a key-value pair that is specified in the HTML markup of an
element and attributes tells us the extra information about the tag.
●​ Attributes are used to provide initial values or settings for elements and are
written directly in the HTML tag.
●​ Examples of attributes include class, id, src, href, title, etc.

Property:
●​ A property is a key-value pair that represents the current state of an element
as it exists in the DOM (Document Object Model).
●​ Properties are accessed and manipulated using JavaScript, and they reflect
the current state or value of an element at runtime.
●​ Examples of properties include className, id, src, href, title, innerHTML,
textContent, etc.

49. What are Closures in JavaScript?

●​ A closure is a feature of JavaScript that allows inner functions to access the


outer scope of a function variable.
50. How do you handle errors in JavaScript?

●​ Errors can be handled in javascript by using ‘try’ and ‘catch’.

51. What is the difference between Object.keys() and Object.values()?

●​ Object.keys() returns an array of a given object's own property names.


●​ Object.values() returns an array of a given object's own property values.
52. What are template literals in JavaScript?

●​ Template literals are a feature in JavaScript that were introduced with ES6.
They allow you to create strings that can contain placeholders for variables or
expressions.
●​ Template literals are more flexible and maintainable than traditional string
concatenation methods.
●​ The template literal is enclosed by backticks.( `` ).

53. What is a scope in JavaScript?

●​ JavaScript scope refers to the region of the code where a particular variable
can be accessed or modified. It determines where you can use a variable or
function in your code.
●​ In JavaScript, there are three types of scope: global scope, function scope,
and block scope.

54. What is a Global scope in JavaScript?

●​ Global scope is the highest level of scope in JavaScript.


●​ Variables which are declared outside any function or block are in global scope
and can be accessed from anywhere in the code.

55. What is a Function scope in JavaScript?

●​ Function scope is a scope of a function.


●​ Variables declared inside a function are local to that function and can only be
accessed within the function.
56. What is a Block scope in JavaScript?

●​ Block scope is a new concept introduced in ES6.


●​ Variables declared with the let or const keywords inside a block are local to
that block and can only be accessed within that block.
57. What is a first class function in JavaScript?

●​ A first class function in computer science and programming languages where


functions are treated as first-class citizens.
●​ This means they can be:
Assigned to variables: You can assign a function to a variable just like any
other value.
Passed as arguments: Functions can be passed as arguments to other
functions.
Returned from other functions: Functions can be returned as values from
other functions.

58. What is a first order function in JavaScript?

●​ A first order function is a function that doesn’t accept another function as an


argument and doesn't return a function as its return value.
59. What is a unary function in JavaScript?

●​ A unary function in javascript is a function that takes exactly one argument. In


JavaScript unary functions are quite common.

60. What is Memoization in JavaScript?

●​ Memoization in JavaScript is an optimization technique used to improve


performance of programs by caching the results of frequently called functions.
●​ This allows the program to avoid redoing calculations when the function is
called again and access previously computed results from a cache.
61. What is NaN property?

●​ NaN property represents the “Not-a-Number” value, a value that is not a legal
number.
Ex:
62. What is Lexical scoping?

●​ Lexical scoping is a fundamental concept in JavaScript where it allows an


inner function to access variables from their outer functions, which can be
very useful for organising code.
●​ This behaviour is also known as closure.

63. What is a constructor in JavaScript?

●​ In JavaScript, a constructor is a function used for creating and initialising


objects.
●​ Constructor functions are typically used with the “new” keyword.
Ex:// Define a constructor function

// Create an instance of Person using the constructor function


64. What is a prototype in JavaScript?

●​ JavaScript prototypes are the mechanism by which objects inherit (takes)


properties and methods from another object.
●​ Every object in JavaScript has a built-in property called its prototype, which is
itself an object.
●​ Prototype Chaining is used to build new types of objects based on existing
ones.

65. What is Heap in JavaScript?

●​ Heap(Or memory heap) is the memory location where objects are stored
when we define variables.
●​ When you create objects or arrays this is the place where all the memory
allocations and de-allocation take place.

66. What is the Temporal Dead Zone?

●​ The Temporal Dead Zone (TDZ) in JavaScript is a specific area or period


where a variable is inaccessible until it has been initialised with a value.
●​ This behaviour occurs when declaring a variable with the let and const
keywords, but not with var.
67. What is the call() method in Javascript?

●​ call() method is used to call a function with specified ‘this’ value and allows
passing in arguments one by one separating with commas.
●​ Syntax: `function.call(thisArg, arg1, arg2, ...)`

68. What is the apply() method in Javascript?

●​ The apply() method is similar to call(), but it accepts arguments as array.


●​ Syntax: `function.apply(thisArg, [argsArray])`

69. What is the bind() method in Javascript?

●​ The bind() method is used to create a new function with a specified ‘this’ value
initial arguments(if any), without calling the original function.
●​ Syntax: ‘function.bind(thisArg, arg1, arg2, …)’
70.What is the difference between Authentication and Authorization?

●​ Authentication is a process of verifying user identity by checking the details


like username, password, fingerprint or security token.
●​ Authorization is a process of giving access or permissions to access certain
areas or perform certain actions after verifying who you are.

71. What is Web Storage?

●​ In JavaScript, web storage refers to the mechanisms provided by web


browsers to store data on the client side.
●​ There are two main types of web storage: Local Storage and Session Storage.
●​ Local storage
●​ Session storage

72. What is the difference between Local storage and Session storage?

●​ Local Storage: Data stored in Local storage remains there even after the
browser is closed and reopened.
●​ Data stored in local storage is available across all browser tabs and windows.
●​ Limited in size to 10 megabytes.

●​ Session Storage: Data stored in Session storage is related or tied to the


current browsing session. It's cleared when the browser is closed or the tab is
closed.
●​ Similar to local storage this session storage is also available across all
browser tabs, but it's cleared when the session ends.
●​ Limited in size 5 megabytes.

Methods in local and session storage :


73.What is a Cookie?

●​ Cookie is a small piece of data that a website stores on user’s computer or


device.
●​ It is used to remember information about users visit to a website, such as
login credentials, user preferences and shopping cart items.
●​ Cookies are sent from the web server to the browser and then stored on the
user's device.

74.Why do you need a Cookie?

●​ Cookies are used to remember information about the user profile. It basically
involves two steps:
●​ When a user visits a web page, the user profile can be stored in a cookie.
●​ Next time the user visits the page, the cookie remembers the user profile.

75.Why are the options in a Cookie?

●​ There are few options available for a cookie:


●​ By default, the cookie is deleted when the browser is closed but you can
change this behaviour by setting expiry date (in UTC time).
Syntax:

●​ By default, the cookie belongs to a current page. But you can tell the browser
what path the cookie belongs to by using a path parameter.
●​ Syntax:

76.How do you delete a Cookie?

●​ You can delete a cookie by setting the expiry date as a passed date.
●​ You should define the cookie path option to ensure that you delete the right
cookie. Some browsers don't allow you to delete a cookie unless you specify
a path parameter.
Syntax:

77.What is a strict mode in javascript?

●​ Strict mode is a feature introduced in ECMAScript that helps you to catch


mistakes.
●​ The Strict mode is declared by adding “use strict” to the beginning of a script
or function.
●​ Strict mode is useful to write secure javascript code by identifying bad syntax.
●​ So it is a very useful tool to write safer, cleaner and more optimized
JavaScript code.

78.What is the global object in javascript?

●​ The global object in JavaScript is a built-in object that always exists in the
global scope.
●​ The global object stores global variables and functions as its properties,
making them accessible throughout the JavaScript program.

79.What is the use of global object in javascript?

●​ Global object is accessible from anywhere in your JavaScript code.


●​ The global object contains built-in properties and functions that are available
globally.
●​ For example, in a browser environment, properties like window, document,
and console are part of the global object.
●​ Variables declared without the var, let, or const keywords (or not enclosed in a
function) become properties of the global object.
●​ You can also attach custom properties or functions to the global object.
Ex: // Accessing a global property

// Declaring a global variable

// Attaching a custom property to the global object


80.What is the purpose of delete operator?

●​ The purpose of the delete operator in JavaScript is to remove a property from


an object. It returns true if the property is deleted successfully, and false
otherwise.
Ex:

81.What is the purpose of typeof operator?

●​ The typeof operator in JavaScript is used to find out the data type of a
variable or expression. It returns a string indicating the type of the operand.
Ex:

82.What is eval?

●​ Eval is a function that evaluates javascript code as a string and returns is


completion value.
83.What is the difference between window and document?

WINDOW:
●​ The window object represents the browser window or tab that contains the
web page.
●​ It provides access to browser features like the URL of the current page
(window.location), methods for opening and closing windows (window.open(),
window.close()), and the browser's history (window.history).
●​ It also contains properties like window.innerWidth and window.innerHeight for
getting the dimensions of the browser window.

DOCUMENT:
●​ The document object represents the HTML document loaded in the browser
window.
●​ It provides access to the elements of the document, allowing you to
manipulate their content, structure, and styling using JavaScript.
●​ It contains methods like document.getElementById(),
document.querySelector(), and document.createElement() for selecting and
creating elements in the document.

84.What are the differences between undeclared and undefined variables?

Undeclared:
●​ The variables do not exist in a program and are not declared.
●​ If you try to read the value of an undeclared variable, then a runtime error is
encountered.

Undefined:​
●​ These variables are declared in the program but have not assigned any value.
●​ If you try to read the value of an undefined variable, an undefined value is
returned.
85.What is Event Bubbling in JavaScript?

●​ Event Bubbling is a concept in DOM. In this process if an event triggers on the


innermost nested elements first then it successively triggers on its parent
elements up to the outermost element.

Output :
86.Is JavaScript a case-sensitive language?

●​ Yes, JavaScript is a case-sensitive language. This means that it recognizes


the differences between uppercase and lowercase letters in identifiers such
as variable names, function names, and object properties.
●​ It's important to be consistent with your casing when naming variables,
functions, and other identifiers to avoid confusion and errors in your code.

87.What are events?

●​ Events in JavaScript are actions or occurrences that happen in the browser or


on the web page. They can be triggered by various user interactions, such as
mouse clicks, keyboard presses, or form submissions, or by the browser itself,
like page loads or DOM mutations.
●​ Event handlers are JavaScript functions that respond to these events,
allowing developers to create interactive web applications.

88.What is Global Execution context?

●​ The global execution context in JavaScript refers to the environment in which


the JavaScript code is executed. When the JavaScript engine first encounters
your script, it creates a global execution context and pushes it to the current
execution stack.
●​ Since the JS engine is single threaded there will be only one global
environment and there will be only one global execution context.
89.What is the use of the preventDefault method?

●​ In JavaScript, the preventDefault() method is used to prevent the default


action associated with an event from occurring. It's commonly used in event
handlers to stop the browser's default behaviour when handling certain
events, such as clicking a link or submitting a form.

90.What is the use of setTimeout?

●​ The setTimeout() method is used to call a function after a specified number of


milliseconds or a specific period of time.
91.What is the use of setInterval?

●​ The setInterval() method is used to call a function at specified intervals.( need


to specify time in milliseconds).

92.What is JSON?

●​ In simple words, JSON (JavaScript Object Notation) in JavaScript is a


lightweight data interchange format that is easy for humans to read and write,
and easy for machines to parse and generate.
●​ It's commonly used for transmitting data between a server and a web
application, and it's based on JavaScript object syntax.

93.What are the syntax rules of JSON?

●​ The data is in key/value pairs


●​ The data is separated by commas
●​ Strings: Enclosed in double quotes (").
●​ Booleans: true or false.
●​ Numbers: Integer or floating-point numbers.They can be written without
quotes.
●​ Ex:
94.What is the purpose of JSON stringify?

●​ When sending data to a web server, the data has to be in a string format.
●​ You can achieve this by converting a JSON object into a string using stringify()
method.

95.What is the purpose of JSON parse?

●​ When receiving the data from a web server, the data is always in a string
format.
●​ But you can convert this string value to a javascript object using the parse()
method.

96.How do you redirect new page in javascript?

●​ Redirecting to another page in JavaScript can be done using various


methods. Here are a few approaches:
●​ Using window.location.href
●​ Using window.location.assign()

●​ Using window.location.replace()

97.What is destructuring in javascript?

●​ Destructuring is a feature in JavaScript that allows you to extract data from


arrays and objects and assign it to distinct variables. This feature is
particularly useful when working with data that has a specific structure or
pattern.
●​ Array destructuring is used to extract data from arrays and assign it to
variables.
●​ Object destructuring is used to extract data from objects and assign it to
variables.
●​ (Clear examples at question number 128 and 129)

98.What are validations in javascript?

●​ In JavaScript, validation refers to the process of checking whether data input


by users meets certain criteria or constraints.
●​ This is commonly done in web development to ensure that user-provided data
is correct and appropriate for its intended use.
●​ There are different types of validations:
Presence Check: Verifying that required fields are not empty.
Presence Check: Verifying that required fields are not empty.
Length Check: Limiting the length of input data (e.g., maximum characters
allowed).
Range Check: Verifying that numeric values are within a certain range (e.g.,
age, quantity).
Pattern Matching: Using regular expressions to validate input against specific
patterns.

99.What is a Regular Expression?

●​ Regular expression is mainly used in validations and in short we call it as


regex.

Example :

100. How do you perform form validation without javascript?

●​ You can perform HTML form validation automatically without using javascript.
The validation is enabled by applying the required attribute to prevent form
submission when the input is empty.
●​ Ex: using required keyword
101.Trim method in JavaScript?

●​ The trim() method in JavaScript is used to remove whitespace (spaces, tabs,


newlines, etc.) from both ends of a string.
●​ This method returns a new string with the whitespace trimmed off from the
beginning and end of the original string.
●​ Ex:

102.Date method in JavaScript?

●​ In JavaScript, the Date object provides methods for working with dates and
times. These methods allow you to create, manipulate, and format dates and
times in various ways.
●​ Some of the methods are:
103.Math in JavaScript?

●​ Math is a built-in object that allows you to perform mathematical operations on


the Number type.

104.How do you find min and max value in an array?

●​ We can find the min and max values using Math.min and Math,max methods;
105.How do you reverse an array?

●​ We have many methods to reverse an array:


●​ Using reverse() method :

●​ Using spread operator:

106.What is a spread operator?

●​ The spread operator(‘...’) in JavaScript is a syntax introduced in ECMAScript 6


(ES6).
●​ It is commonly used for various tasks, such as copying arrays, concatenating
arrays, passing function arguments, and more.
Ex: Copying Arrays:

Concatenating arrays:
Adding Elements to Arrays:

107.What is a rest operator?

●​ The rest operator in JavaScript is used to represent the rest of the arguments
or an indefinite number of arguments in a function or an array. It is denoted by
the three dots …
●​ Function Parameters: When defining a function, you can use the rest operator
to collect any number of arguments passed to the function into a single array
parameter.
Ex:

108.What are loops in JavaScript?

●​ JavaScript Loops are powerful tools which are used to perform repeated tasks
based on a condition. Conditions typically return true or false . A loop will
continue running until the defined condition returns false .
109.What are the two types of loops in javascript?

●​ Entry Controlled loops: In this kind of loop type, the test condition is tested
before entering the loop body.
For example, For Loop and While Loop comes under this category.

●​ Exit Controlled Loops: In this kind of loop type, the test condition is tested or
evaluated at the end of the loop body. i.e, the loop body will execute at least
once irrespective of test condition true or false.
For example, do-while loop comes under this category.

110. What are the different types of loops in JavaScript ?

●​ There are several types of loops in Javascript :


●​ For Loop
●​ For-in loop
●​ For-of loop
●​ While loop
●​ Do while loop

111.What is ‘for’ loop in javascript?

●​ A for loop is a control flow statement that allows you to execute a block of
code repeatedly based on a specified condition.
●​ It's commonly used when you know exactly how many times you want to loop.
●​ Syntax:

112. How do you iterate over an array using a for loop?

●​ To iterate over the elements of an array by using the array's length property in
for loop:
Ex: Iterating fruits array
113.How do you create an infinite loop using a for loop?

●​ An infinite loop is a loop that continues to run indefinitely because the loop's
terminating condition is never met.
●​ You can create an infinite loop by omitting the ‘condition’ part of the ‘for’ loop:

114. How do you exit a for loop prematurely?

●​ You can use the break statement to exit a for loop prematurely:
115. How do you skip the current iteration of a for loop?

●​ You can use the continue statement to skip the current iteration of a for loop
and proceed to the next iteration:

116. What is the syntax of while loop in JavaScript ?

●​ The while loop in JavaScript is used to repeatedly execute a block of code as


long as a specified condition is true.

117. What is the syntax of do while loop in JavaScript ?

●​ The do...while statements combo defines a code block to be executed once, and
repeated as long as a condition is true.
●​ If you use a variable in the condition, you must initialise it before the loop, and
increment it within the loop. Otherwise the loop will never end. This will crash
your browser.
●​ Ex:
118.What is the difference between continue and break statement?

●​ Break : The break statement is used to exit a loop prematurely, regardless of the
loop condition.
●​ It is commonly used to stop the execution of a loop when a certain condition is
met.

●​ Continue : The continue statement is used to skip the current iteration of a loop
and move to the next iteration.
●​ It is commonly used to skip certain iterations based on a condition, without
exiting the loop entirely.

119. What are conditional statements in JavaScript?

●​ Conditional statements in JavaScript are used to execute different actions


based on different conditions.
●​ They allow a program to make decisions and choose between different
courses of action.

120.What are the types of conditional statements in JavaScript?

There are mainly two types of conditional statements in JavaScript:


●​ if...else statements
●​ switch statements

121.Explain the syntax of the if...else statement in JavaScript?

●​ The syntax of the if...else statement is as follows:


●​ And to check multiple statements

122.Explain the purpose of the switch statement in JavaScript?

●​ The switch statement is used to perform different actions based on different


conditions. It's an alternative to multiple if...else if...else statements when you
want to evaluate a single expression against multiple possible values.

123. What is the syntax of the switch statement in JavaScript?

Example for Switch statement:


124.What is the purpose of the default case in a switch statement?

●​ The ‘default’ case is optional and serves as a default action if none of the
case values match the expression.
●​ It's similar to the ‘else’ block in an if...else statement.

125.What happens if you don't use the break statement in a switch case?

●​ If you don't use the break statement in a switch case, the code execution
continues into the next case even if the current case matches.
●​ This means that all subsequent cases will also be executed until a break
statement is encountered or until the end of the switch block.

126. What is the ‘debugger’ statement?

●​ A debugger statement is a powerful tool used in JavaScript to pause the


execution of code and enter the browser's debugger interface.
●​ This allows you to peek into your code’s inner workings, check the values of
variables and see what is happening step-by-step.
●​ It's a handy tool for finding and fixing issues in your code during development.
●​ Ex:
127. What is the purpose of breakpoints in debugging?

●​ Breakpoints are like markers you can place in your code while debugging.
●​ When the program runs into a breakpoint, it pauses, allowing you to take a
closer look at what's happening in your code at that moment.
●​ They help you find and fix problems in your code by letting you see what's
going on step by step.

128. What is object destructuring in JavaScript?

●​ Object destructuring in JavaScript is a syntax that allows you to extract


multiple properties from an object and assign them to variables in a single,
concise statement.
●​ It's a convenient way to unpack values from objects and access them more
easily.
●​ Extracting Properties: With object destructuring, you can extract properties
from an object and assign them to variables with the same names as the
property keys.
129. What is array destructuring in JavaScript?

●​ Array destructuring is similar to object destructuring but is used for extracting


values from arrays and assigning them to variables.

130. What is the use of tree shaking?

●​ Tree shaking is a technique that removes unused code from your JavaScript
bundles, making them smaller and faster to load. It can help you optimise your
web performance and reduce your loading time.

Coding Questions in JavaScript


131. Implement a function to find the sum of all the numbers in an array?

132. Write the code to check if the given value is Palindrome or not?

(or)
We can use reverse method:
133.Remove duplicate elements from an array?

Using set method:

(or using for loop)


134.Smallest Number from An Array?

Math.min method:

For loop:
135.Largest Number from An Array?

Math.max method:

For loop method:


136.Find the frequency of elements in Array?

Frequency means each element repeated how many times.

Output:
137.Print all duplicate numbers in array?

Output :
138.Write a javascript function to calculate the sum of two numbers and
check if the sum is prime or not?

Output :
139.Write a javascript function that takes an array of numbers and returns the
new array with only the even numbers?

Output:

140.Write a javascript function to calculate the factorial of a given number?

Output:
141.How do you check if elements exist in an array ?

●​ To check if elements exist in an array, you can use various methods in


JavaScript:
●​ indexOf method:

●​ Includes method:

●​ Find method:

142.How do you remove an element from an array at a specific index?

●​ Splice method :
●​ Using loops :

143.Missing numbers in array?


144.Collect books from an array of objects and return a collection of books
as an array?

Output:

145. Fibonacci Series?

Output :
146. Flatten Array?

147. How to check if a given number is integer?

●​ number.isInteger method :

●​ Math.round() method :
●​ Math.floor() method :

148. How can we replace an element at a specific index in an array?


149. How can we insert an element at a specific index in an array?

Output :
150. How can you sort and reverse an array without changing the original
array?

Output :

151. Convert a given number into exact decimal points to the right side?

152. How to replace a given string in each array?

Using replace method :


Using map method :
153. How to find the average of numbers in a numbered array?

154. How to reverse an array without a reverse method?

155. Write a JavaScript program to convert a string to title case (capitalise


the first letter of each word)?

Using regular expression :


Using toUpperCase() method :
156. Sum of pairs?

Output :
157. Group by age?

158. Implement a function that takes two sorted arrays and merges them into
a single sorted array without using any built-in sorting functions.?
159. Write a javascript program to find the largest element in a nested array?

You might also like