Javascript Questions and Answers
Javascript Questions and Answers
1.What is JavaScript?
● 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 :
● 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.
● 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?
● Functions can be created using the function keyword followed by the function
name and a set of parentheses that contain the parameters.
● Ex:
● 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:
● The Operators are special symbols or keywords that are used to perform
operations on operands, such as arithmetic calculations, logical comparisons, or
value assignments.
● There are several types of operators in JavaScript. Here are some main types of
operators :
● Type Operator: the typeof operator is used to find out the type of a variable or
an expression.
● Ex:
● 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.
● 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.
● There are several ways to define objects in JavaScript. Here are some
common methods:
Object.create method:
“new” keyword :
28.What is ES6?
● ES6 added array methods like find(), findIndex(), includes(), entries(), keys(),
values(), and from().
Ex: 1
Ex: 2
● 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?
join() :
every() : it checks every element in array satisfies the condition or not
● slice() returns a shallow copy of a portion of an array into a new array. It will
not affect the main array.
● Object.assign()
● JSON.parse(JSON.stringify())
● The document.write() is a method used to write the content directly in the html
document or in the browser.
● 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?
● 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?
● Filter method is used to create a new array with elements that satisfies the
specific condition which we’ll provide.
Filter :
47. What is the reduce method in JavaScript?
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.
● 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.( `` ).
● 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.
● NaN property represents the “Not-a-Number” value, a value that is not a legal
number.
Ex:
62. What is Lexical scoping?
● 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.
● 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, ...)`
● 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?
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.
● 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.
● 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:
● 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:
● 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.
● 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?
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.
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?
Output :
86.Is JavaScript a case-sensitive language?
92.What is JSON?
● 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.
● 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.
● Using window.location.replace()
Example :
● 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?
● 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?
● We can find the min and max values using Math.min and Math,max methods;
105.How do you reverse an array?
Concatenating arrays:
Adding Elements to Arrays:
● 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:
● 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.
● 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:
● 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:
● 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:
● 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.
● 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.
● 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.
● 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.
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?
Math.min method:
For loop:
135.Largest Number from An Array?
Math.max method:
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:
Output:
141.How do you check if elements exist in an array ?
● Includes method:
● Find method:
● Splice method :
● Using loops :
Output:
Output :
146. Flatten Array?
● number.isInteger method :
● Math.round() method :
● Math.floor() method :
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?
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?