0% found this document useful (0 votes)
3 views40 pages

JavaScript Interview Questions and Answers (1)

The document provides a comprehensive list of JavaScript interview questions and answers covering fundamental concepts such as variables, functions, data types, and object manipulation. Key topics include hoisting, the difference between '==' and '===', DOM, and the use of keywords like 'let', 'var', and 'const'. Additionally, it discusses features of JavaScript, event handling, and methods for array manipulation.

Uploaded by

ambadi29072003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views40 pages

JavaScript Interview Questions and Answers (1)

The document provides a comprehensive list of JavaScript interview questions and answers covering fundamental concepts such as variables, functions, data types, and object manipulation. Key topics include hoisting, the difference between '==' and '===', DOM, and the use of keywords like 'let', 'var', and 'const'. Additionally, it discusses features of JavaScript, event handling, and methods for array manipulation.

Uploaded by

ambadi29072003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JavaScript Interview Questions and Answers

1. What is Javascript?
JavaScript is a scripting language most often used for client-side and server-side web
development.

2. Explain Hoisting in javascript


Hoisting is a JavaScript behaviour where variable and function declarations are moved
to the top of their containing scope during the compilation phase, before the code is
executed.
Example:
[Link](message); // Output: undefined
var message = 'Hello, hoisting!';

sayHello(); // Output: Hello, hoisting!

function sayHello() {
[Link]('Hello, hoisting!');
}

3. What is the difference between == and ===?


“==” checks equality only,
“===” checks for equality as well as the type.
4. What is NaN property in JavaScript?
NaN property represents the “Not-a-Number” value. It indicates a value that is not a
legal number. Type of NaN will return a Number.
To check if a value is NaN, we use the is NaN() function,
Example:
isNaN("Hello") // Returns true
isNaN(345) // Returns false

5. What is DOM?

1
n
DOM stands for the Document Object Model. Dom defines a standard for accessing the
document. It is a platform that allows to dynamically access and update the content or
structure or style of the document.

6. What is the difference between undefined value and null value?

 Undefined value: A value that is not defined and has no keyword is known as
undefined value.

Example:
int number;//Here, a number has an undefined value.
 Null value: A value that is explicitly specified by the keyword "null" is
known as a null value.

Example:
String str=null;//Here, str has a null value.

7. What would be the result of 1+2+'3'


The result is 33

8. How do you change the style of a HTML element?


document. getElementById("myText").[Link] = "10";

9. What is Prompt() method in JavaScript?


A prompt box is a box which allows the user to enter input by providing a text box. The
prompt() method displays a dialog box that prompts the visitor for input.

10. What is typeof operator?

The typeof operator is a built-in JavaScript operator that allows you to determine the
data type of a given value or expression. It returns a string indicating the type of the
operand.
Example:
let x = 42;

2
n
let y = "Hello";
let z = true;

[Link](typeof x); // Output: "number"


[Link](typeof y); // Output: "string"
[Link](typeof z); // Output: "boolean"

11. What is let keyword in JavaScript?

The let keyword is used to declare block-scoped variables. It was introduced in


ECMAScript 6 (ES6) as an alternative to the var keyword, which declares variables
with function scope or global scope.
The let keyword allows you to declare variables that are limited in scope to the block,
statement, or expression in which they are defined. This means that a variable declared
with let is only accessible within the block of code where it is defined, including any
nested blocks. Outside of that block, the variable is not accessible.
Example:
function example() {
let x = 10;

if (true) {
let y = 20;
[Link](x); // Output: 10
[Link](y); // Output: 20
}

[Link](x); // Output: 10
[Link](y); // Error: y is not defined
}

example();

12. What is var keyword in JavaScript?


3
n
The var keyword is used to declare variables. It was the primary way to declare
variables in JavaScript before the introduction of let and const in ECMAScript 6 (ES6).
Variables declared with var have function scope or global scope, depending on where
they are declared. This means that a variable declared with var is accessible throughout
the entire function in which it is defined, regardless of the block scope.
Example:
function example() {
var x = 10;

if (true) {
var y = 20;
[Link](x); // Output: 10
[Link](y); // Output: 20
}

[Link](x); // Output: 10
[Link](y); // Output: 20
}

example();

13. What is const keyword in JavaScript?


The const keyword is used to declare variables that have block scope and whose values
cannot be reassigned once they are initialized. It was introduced in ECMAScript 6
(ES6) as a way to declare constants in JavaScript.
When you declare a variable with const, you must initialize it with a value at the same
time. Once the value is assigned, it cannot be changed throughout the rest of the
program.
Example:
const pi = 3.14;
[Link](pi); // Output: 3.14

pi = 3.14159; // Error: Assignment to a constant variable


4
n
14. What is arrays in JavaScript?
In JavaScript, an array is a data structure used to store multiple values in a single
variable. It is a built-in object type that provides a way to organize and manipulate
collections of elements.
There are two ways to create array in JavaScript like other languages.
• The first way to create array
var names = new Array ();
names [0] = "Vikas";
names [1] = "Ashish";
names [2] = "Nikhil";
• The second way to create array
var names = new Array ("Vikas", "Ashish", "Nikhil");

15. What arrow functions?


Arrow functions, also known as fat arrow functions, are a concise syntax introduced in
ECMAScript 6 (ES6) for defining functions in JavaScript. They provide a more concise
and expressive way to write function expressions.
Syntax:
(parameters) => {
// function body
};
Example:
const add = (a, b) => a + b;

[Link](add(2, 3)); // Output: 5

16. What are object? Explain How to add and remove elements from object.
An object is a data structure that allows you to store and organize data in key-value
pairs.
An object consists of properties, where each property has a key (also called a property
name or identifier) and a corresponding value. The key is always a string, and the value

5
n
can be of any data type, including other objects, arrays, functions, and primitive values
such as strings, numbers, and booleans.
Example:
let person = {
name: "John",
age: 30,
profession: "Developer"
};
delete [Link];

17. How to add JavaScript to HTML document? Explain each way with examples.
There are three ways to add JavaScript code to an HTML document.
 Inline javascript
<!DOCTYPE html>
<html>
<head>
<title>Inline JavaScript Example</title>
</head>
<body>
<h1>Inline JavaScript Example</h1>

<script>
// Inline JavaScript code
alert("Hello, World!");
</script>
</body>
</html>
 Internal javascript
<!DOCTYPE html>
<html>
<head>
<title>Internal JavaScript Example</title>
<script>
6
n
// Internal JavaScript code
function greet() {
alert("Hello, World!");
}
</script>
</head>
<body>
<h1>Internal JavaScript Example</h1>

<button onclick="greet()">Click Me</button>


</body>
</html>
 External javascript
<!DOCTYPE html>
<html>
<head>
<title>External JavaScript Example</title>
<script src="[Link]"></script>
</head>
<body>
<h1>External JavaScript Example</h1>

<button onclick="greet()">Click Me</button>


</body>
</html>

[Link]
// External JavaScript code
function greet() {
alert("Hello, World!");
}

18. Who created javascript?


7
n
Javascript is created by Brendan Eich. He developed the language while working at
Netscape Communications Corporation in 1995.

19. What are the different ways to access object properties?


In JavaScript, there are several ways to access object properties.
 Dot notation:
let person = {
name: "John",
age: 30
};

[Link]([Link]); // Output: "John"


[Link]([Link]); // Output: 30

 Bracket notation:
let person = {
name: "John",
age: 30
};

[Link](person["name"]); // Output: "John"


[Link](person["age"]); // Output: 30

 Computed property access (ES6):


let propertyName = "name";
let person = {
name: "John",
age: 30
};

[Link](person[propertyName]); // Output: "John"

 Object destructuring (ES6):


8
n
let person = {
name: "John",
age: 30
};

let { name, age } = person;

[Link](name); // Output: "John"


[Link](age); // Output: 30

20. Is JavaScript a case-sensitive language


Yes, JavaScript is a case-sensitive language.
Example:
let myVariable = 42;
let myvariable = "Hello";

[Link](myVariable); // Output: 42
[Link](myvariable); // Output: "Hello"

21. What advantages are using arrow functions?


 Arrow functions have shorter syntax than regular function expressions.
 Arrow functions have implicit return statements.
 Arrow functions increase readability.

22. What are the primitive data types in JavaScript?


In JavaScript, there are six primitive data types:
 String: Represents a sequence of characters enclosed in single quotes ('') or
double quotes ("").
Example: "Hello, world!"

 Number: Represents numeric values, including integers and floating-point


numbers.
Example: 42, 3.14

9
n
 Boolean: Represents a logical value that can be either true or false.
Example: true, false

 Null: Represents the intentional absence of any object value.


Example: null

 Undefined: Represents an uninitialized or unassigned value.


Example: undefined

 Symbol (introduced in ECMAScript 6): Represents a unique and immutable


value that can be used as an identifier for object properties.
Example: Symbol("mySymbol")

23. What are some advantages of using External JavaScript?


 It separates HTML and code.
 It makes HTML and JavaScript easier to read and maintain.
 Cached JavaScript files can speed up page loads.

24. Is javascript a statically typed or a dynamically typed language?

JavaScript is a dynamically typed language. This means that variable types are
determined dynamically at runtime, rather than being explicitly declared or enforced
during compilation or initialization.
In JavaScript, you can assign a value of any type to a variable without explicitly
specifying its type. The type of a variable can change during the execution of the
program based on the value assigned to it.
Example:
let x = 42; // x is initially assigned a number
x = "Hello"; // x is now assigned a string
x = true; // x is now assigned a Boolean

25. What are the possible ways to create objects in JavaScript?

10
suhas@[Link]
In JavaScript, there are four ways to create an object — using object literals, constructor
functions, ES6 classes and object.
 Object Literal:
Example:
let person = {
name: "John",
age: 25,
occupation: "Developer"
};

 Constructor Function:
Example:
function Person(name, age, occupation) {
[Link] = name;
[Link] = age;
[Link] = occupation;
}

let person = new Person("John", 25, "Developer");

 ES6 Class:
Example:
class Person {
constructor(name, age, occupation) {
[Link] = name;
[Link] = age;
[Link] = occupation;
}
}

let person = new Person("John", 25, "Developer");

 [Link]():
11
suhas@[Link]
Example:
let personPrototype = {
greeting: function() {
[Link]("Hello, I'm " + [Link]);
}
};

let person = [Link](personPrototype);


[Link] = "John";
[Link] = 25;
[Link] = "Developer";
26. What is JavaScript? Explain the features of JavaScript.
JavaScript is a scripting language most often used for client-side and server-side web
development.
The features of JavaScript are:
 Case Sensitive
In Javascript, names, variables, keywords, and functions are case-sensitive.
 Arrow Functions
Javascript helps to optimize syntax in anonymous functions with the arrow
function syntax.
 Date and Time Handling
Javascript has built-in functions for getting 'date' and time.
 Event Handling
Events are actions. Javascript provides event-handling options.
 Control Statements
Javascript has control statements like if-else-if, switch case, and loop. Users can
write complex code using these control statements.
 Scripting
Javascript executes the client-side script in the browser.

27. What are events?

12
suhas@[Link]
Event is the predefined object in js where it contains all the information related to click
event.

28. What is the purpose of the array slice method?


The slice() method in JavaScript is used to create a new array that contains a shallow
copy of a portion of an existing array. It does not modify the original array but returns
a new array with the selected elements.
Example:
const numbers = [1, 2, 3, 4, 5];
const slicedArray = [Link](1, 4);

[Link](slicedArray); // Output: [2, 3, 4]

29. What is the purpose of the array splice method?


The splice() method in JavaScript is used to change the contents of an array by
removing, replacing, or adding elements. It modifies the original array and returns an
array containing the removed elements.
Example:
const fruits = ['apple', 'banana', 'orange', 'grape'];

// Remove one element at index 1


[Link](1, 1);
[Link](fruits); // Output: ['apple', 'orange', 'grape']

30. What are classes in javascript?

Classes in JavaScript are a way to define blueprints for creating objects with similar
properties and behaviors. They are a fundamental part of object-oriented programming
(OOP) in JavaScript. Introduced in ECMAScript 2015 (ES6)
Example:
class Person {
13
suhas@[Link]
constructor(name, age) {
[Link] = name;
[Link] = age;
}

sayHello() {
[Link](`Hello, my name is ${[Link]} and I am ${[Link]} years old.`);
}
}

31. What is the definition of a Higher-Order Function?


A higher order function is a function that takes one or more functions as arguments, or
returns a function as its result.
Example:
function multiplier(factor) {
return function(number) {
return number * factor;
};
}

const double = multiplier(2);


const triple = multiplier(3);

[Link](double(5)); // Output: 10
[Link](triple(5)); // Output: 15

32. What are the different types of operators in JavaScript? Explain each type with
an Example.

In JavaScript, there are several types of operators that perform different operations on
values. Here are the main types of operators along with examples:
 Arithmetic Operators: Arithmetic operators are used to perform mathematical
calculations.
14
suhas@[Link]
Example:
let x = 5;
let y = 3;

[Link](x + y); // Addition: 8


[Link](x - y); // Subtraction: 2
[Link](x * y); // Multiplication: 15
[Link](x / y); // Division: 1.6666666666666667
[Link](x % y); // Modulus (Remainder): 2
[Link](x ** y); // Exponentiation: 125

 Comparison Operators: Comparison operators are used to compare two


values and return a Boolean result (true or false).
Example:
let x = 5;
let y = 3;

[Link](x > y); // Greater than: true


[Link](x < y); // Less than: false
[Link](x >= y); // Greater than or equal to: true
[Link](x <= y); // Less than or equal to: false
[Link](x === y); // Equality: false
[Link](x !== y); // Inequality: true

 Logical Operators: Logical operators are used to combine or manipulate


Boolean values.
Example:
let x = 5;
let y = 3;
let z = 7;

[Link](x > y && x < z); // Logical AND: true


[Link](x > y || x > z); // Logical OR: true
[Link](!(x > y)); // Logical NOT: false

15
suhas@[Link]
 Unary Operators: Unary operators work on a single operand.
Example:
let x = 5;

[Link](-x); // Negation: -5
[Link](++x); // Increment: 6
[Link](--x); // Decrement: 5
[Link](!true); // Logical NOT: false

 Conditional (Ternary) Operator: The conditional operator (also known as


the ternary operator) is a shorthand for an if...else statement.
Example:
let age = 18;
let canVote = (age >= 18) ? "Yes" : "No";

[Link](canVote); // Yes
 Assignment Operators: Assignment operators are used to assign values to
variables.
Example:
let x = 10;

x += 5; // Addition assignment: x = x + 5 (15)


x -= 3; // Subtraction assignment: x = x - 3 (12)
x *= 2; // Multiplication assignment: x = x * 2 (24)
x /= 4; // Division assignment: x = x / 4 (6)
x %= 5; // Modulus assignment: x = x % 5 (1)

33. Explain is Scope in JavaScript?

Scope in JavaScript refers to the visibility and accessibility of variables, functions, and
objects within a particular part of the code during runtime. It determines where
variables and functions are accessible and where they are not.

16
suhas@[Link]
 Global Scope: Variables declared outside of any function or block have global
scope. They can be accessed from anywhere in the code, including inside
functions.
Example:
let globalVariable = "I am a global variable";

function globalFunction() {
[Link](globalVariable);
}

globalFunction(); // Output: I am a global variable

 Local Scope: Variables declared inside a function have local scope. They are
only accessible within that function and are not visible outside of it.
Example:
function localFunction() {
let localVariable = "I am a local variable";
[Link](localVariable);
}

localFunction(); // Output: I am a local variable


[Link](localVariable); // Error: localVariable is not defined

34. What are the types of errors in javascript?


In JavaScript, there are several types of errors that can occur during the execution of a
program.
 Syntax Errors: Syntax errors occur when the JavaScript code violates the
language's syntax rules.
Example:
if (x > 5 { // SyntaxError: Missing closing parenthesis
[Link]("x is greater than 5");
}

17
suhas@[Link]
 Reference Errors: Reference errors occur when an invalid reference or
identifier is used in the code.
Example:
[Link](message); // ReferenceError: message is not defined

function myFunction() {
[Link](innerVariable); // ReferenceError: innerVariable is not defined
}

 Type Errors: Type errors occur when an operation is performed on a value of


an inappropriate type.
Example:
let x = 10;
x(); // TypeError: x is not a function

let person = null;


[Link]([Link]); // TypeError: Cannot read property 'name' of null

 Range Errors: Range errors occur when a value is not within the expected
range or set of allowed values.
Example:
let array = [1, 2, 3];
[Link](array[5]); // RangeError: Invalid array index

let negativeNumber = -10;


[Link]([Link](negativeNumber)); // RangeError: Invalid argument

 Eval Errors: Eval errors occur when there is an issue with the eval() function.
The eval() function is used to evaluate JavaScript code dynamically.
Example:
eval("alert('Hello, World!"); // EvalError: Unterminated string literal

35. Is JavaScript a compiled or interpreted language


18
suhas@[Link]
JavaScript is an interpreted language, not a compiled language

36. What is the use of setInterval?


The setInterval() function is commonly used to set a delay for functions that are
executed again and again, such as animations.

37. What is the purpose of clearTimeout method?


The clearTimeout method in JavaScript is used to cancel a timeout previously set with
the setTimeout function. It allows you to stop the execution of a function that was
scheduled to run after a specific delay.
Example:
function showMessage() {
[Link]("Hello, World!");
}

// Schedule the showMessage function to execute after 2 seconds


let timeoutId = setTimeout(showMessage, 2000);

// Cancel the timeout before it executes


clearTimeout(timeoutId);

38. What is the purpose of clearInterval method?


The clearInterval method in JavaScript is used to cancel the recurring execution of a
function that was scheduled to run at fixed intervals using the setInterval function.
Example:
let count = 0;

function incrementCount() {
count++;
[Link](count);
}

// Call incrementCount function every 1 second (1000 milliseconds)


19
suhas@[Link]
let intervalId = setInterval(incrementCount, 1000);

// Stop the interval after 5 seconds


setTimeout(function() {
clearInterval(intervalId);
}, 5000);

39. What is the difference between slice and splice?


slice splice
Returns removed elements from the array Returns selected elements from the array
Mutates original array Does not mutate original array
Can add new elements to array Can’t add new elements

40. What is eval?


In JavaScript, eval() is a global function that evaluates or executes a string of code
dynamically at runtime. It takes the provided code as a string parameter and executes it
as if it were part of the original code.
Example:
let x = 5;
let y = 10;
let code = "[Link](x + y);";

eval(code); // Output: 15

let dynamicCode = "let z = x * y; [Link](z);";

eval(dynamicCode); // Output: 50

41. What is the purpose of setTimeout function?


The setTimeout function in JavaScript is used to schedule the execution of a function
or the evaluation of a code snippet after a specified delay. It allows you to introduce a
time delay before executing a specific action.
Example:
20
suhas@[Link]
function showMessage() {
[Link]("Hello, World!");
}

// Call showMessage function after 2 seconds


setTimeout(showMessage, 2000);

// Using an anonymous function


setTimeout(function() {
[Link]("Delayed message");
}, 3000);

42. How do you get the current url with javascript?

In JavaScript, you can get the current URL (Uniform Resource Locator) of the webpage
using the [Link] object. The [Link] object provides information
about the current URL and various properties and methods to access different parts of
the URL.
Example:
let currentURL = [Link];
[Link](currentURL);

43. How do you combine two or more arrays?

To combine two or more arrays in JavaScript, you can use the concat() method or the
spread operator (...).
Example:
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
let array3 = [7, 8, 9];

let combinedArray = [Link](array2, array3);


[Link](combinedArray);
21
suhas@[Link]
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

44. Can I redeclare let and const variables


In JavaScript, you cannot redeclare a variable using the let or const keywords within
the same scope. If you attempt to redeclare a let or const variable, it will result in an
error.
Example:
let x = 5;
let x = 10; // Error: Identifier 'x' has already been declared

const y = 20;
const y = 30; // Error: Identifier 'y' has already been declared

45. What is an anonymous function?


An anonymous function in JavaScript is a function that is defined without a name.
Instead of providing a name for the function, it is directly declared as an expression and
assigned to a variable or used as a callback.
Example:
let sayHello = function() {
[Link]("Hello!");
};

sayHello(); // Output: Hello!

46. How do you display the current date in javascript?


To display the current date in JavaScript, you can use the Date object along with various
methods to extract the desired information. Here's an
Example:
let currentDate = new Date();

let year = [Link]();


let month = [Link]() + 1; // Note: Months are zero-based, so we add 1
to get the actual month.
22
suhas@[Link]
let day = [Link]();

[Link]("Current Date: " + year + "-" + month + "-" + day);


47. Explain the different Output statements in JavaScript with Examples.
In JavaScript, there are several ways to output or display information to the console or
the user.
 [Link]():
[Link]("Hello, World!"); // Output: Hello, World!

let num = 42;


[Link]("The value of num is:", num); // Output: The value of num is: 42

let person = { name: "John", age: 30 };


[Link](person); // Output: { name: "John", age: 30 }

 alert():
alert("Welcome to our website!"); // Displays a popup with the message
"Welcome to our website!"

 [Link]():
[Link]("Hello, World!"); // Output: Hello, World!

 innerHTML:
<div id="myElement"></div>

<script>
let element = [Link]("myElement");
[Link] = "Hello, World!"; // The content of the div will be
replaced with "Hello, World!"
</script>

48. What are Events in JS? Briefly Explain Event Handlers in JS with Examples.

23
suhas@[Link]
In JavaScript, events are actions or occurrences that happen in the browser or on a web
page. These events can be triggered by the user, such as clicking a button or submitting
a form, or they can be triggered by the browser itself, such as when the page finishes
loading or when a timer expires. Events allow you to respond to user interactions and
perform specific actions in your JavaScript code.
Example:

<button id="myButton">Click Me</button>

<script>
// Event handler function
function handleClick() {
[Link]("Button clicked!");
}

// Attaching the event handler to the button


let button = [Link]("myButton");
[Link]("click", handleClick);
</script>

49. What are functions? Explain the different types of function with example
In JavaScript, a function is a block of reusable code that performs a specific task or
calculates a value.
 Named Function:
A named function is a function that is defined with a specific name. It can be called by
its name whenever you want to execute its code.
Example:
function greet(name) {
[Link]("Hello, " + name + "!");
}

greet("John"); // Output: Hello, John!

24
suhas@[Link]
 Anonymous Function:
An anonymous function is a function that is not assigned a name. It is often used
as a callback function or assigned to a variable.
Example:
let greet = function (name) {
[Link]("Hello, " + name + "!");
};

greet("John"); // Output: Hello, John!

 Arrow Function:
Arrow functions are a concise syntax introduced in ES6. They provide a more
compact way to define functions
Example:
let greet = (name) => {
[Link]("Hello, " + name + "!");
};

greet("John"); // Output: Hello, John!

50. Explain with example About looping and control statements in JavaScript.
In JavaScript, looping and control statements are used to control the flow of execution
in a program. They allow you to repeat a block of code or conditionally execute code
based on certain conditions.
 for loop:
for (let i = 0; i < 5; i++) {
[Link](i);
}
// Output: 0 1 2 3 4

 while loop:
let i = 0;
while (i < 5) {
25
suhas@[Link]
[Link](i); i+
+;
}
// Output: 0 1 2 3 4

 do-while loop:
let i = 0;
do {
[Link](i); i+
+;
} while (i < 5);
// Output: 0 1 2 3 4

 if statement:
let age = 20;
if (age >= 18) {
[Link]("You are an adult.");
} else {
[Link]("You are a minor.");
}
// Output: You are an adult.

 switch statement:
let day = "Monday";
switch (day) {
case "Monday":
[Link]("It's Monday.");
break;
case "Tuesday":
[Link]("It's Tuesday.");
break;
default:
[Link]("It's another day.");
26
suhas@[Link]
}
// Output: It's Monday.

51. What is DOM in JS? Explain Each DOM methods with Examples.

In JavaScript, the DOM (Document Object Model) is a programming interface that


represents the structure and content of an HTML or XML document. It provides
methods and properties that allow you to manipulate and interact with the elements on
a web page.
 getElementById():
The getElementById() method is used to select an element from the DOM based on its
unique ID attribute.
Example:
<div id="myDiv">Hello, World!</div>

<script>
let element = [Link]("myDiv");
[Link]([Link]); // Output: Hello, World!
</script>

 getElementsByClassName():
The getElementsByClassName() method is used to select elements from the DOM
based on their class names. It returns a collection of elements.
Example:
<p class="highlight">This is a paragraph.</p>
<p class="highlight">This is another paragraph.</p>

<script>
let elements = [Link]("highlight");
for (let i = 0; i < [Link]; i++) {
[Link](elements[i].innerHTML);
}
// Output:
27
suhas@[Link]
// This is a paragraph.
// This is another paragraph.
</script>

 getElementsByTagName():
The getElementsByTagName() method is used to select elements from the DOM based
on their tag names. It returns a collection of elements.
Example:
<p>This is a paragraph.</p>
<div>This is a div.</div>
<p>This is another paragraph.</p>

<script>
let elements = [Link]("p");
for (let i = 0; i < [Link]; i++) {
[Link](elements[i].innerHTML);
}
// Output:
// This is a paragraph.
// This is another paragraph.
</script>

 querySelector():
The querySelector() method is used to select an element from the DOM using a CSS
selector. It returns the first matching element.
Example:
<div class="myDiv">Hello, World!</div>

<script>
let element = [Link](".myDiv");
[Link]([Link]); // Output: Hello, World!
</script>

28
suhas@[Link]
52. What are callbacks?
In JavaScript, a callback is a function that is passed as an argument to another function
and is invoked or called within that function.

53. How do you submit a form using JavaScript?


To submit a form using JavaScript, you can utilize the submit() method of the
HTMLFormElement object.
Example:
<form id="myForm">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Submit">
</form>

<script>
// Get the form element
const form = [Link]('myForm');

// Add an event listener to the form's submit event


[Link]('submit', function(event) {
[Link](); // Prevent the default form submission behavior

// Perform any necessary form validation or other actions

// Submit the form programmatically


[Link]();
});
</script>

54. How do you check whether a string contains a substring?


In JavaScript, there are multiple ways to check whether a string contains a substring.
Here are a few common approaches:
 Using the includes() method:
29
suhas@[Link]
The includes() method is a built-in method for strings that returns true if the specified
substring is found within the string, and false otherwise.
Example:
const str = 'Hello, world!';
const substring = 'world';

[Link]([Link](substring)); // Output: true


 Using the indexOf() method:
The indexOf() method returns the index of the first occurrence of a substring within a
string. If the substring is not found, it returns -1. You can use this method to check if
the returned index is greater than or equal to 0.
Example:
const str = 'Hello, world!';
const substring = 'world';

[Link]([Link](substring) >= 0); // Output: true

55. How do you validate an email in javascript?

To validate an email address in JavaScript, you can use regular expressions. Regular
expressions provide a powerful way to match and validate patterns.
Example:
function validateEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return [Link](email);
}

// Example usage
const email1 = 'test@[Link]';
const email2 = '[Link]@com';
const email3 = 'another@example';

[Link](validateEmail(email1)); // Output: true


30
suhas@[Link]
[Link](validateEmail(email2)); // Output: false
[Link](validateEmail(email3)); // Output: false

56. Give an example where do you really need semicolon

In JavaScript, semicolons are used to terminate statements. While JavaScript has


automatic semicolon insertion (ASI) rules that insert semicolons in certain cases, there
are scenarios where using semicolons explicitly is necessary.
Example:
// Example 1: Function as an Immediately Invoked Function Expression (IIFE)
(function() {
[Link]('This is an IIFE');
})();

// Example 2: Multiple statements on the same line


const name = 'John Doe'; [Link]('Hello, ' + name);

// Example 3: Using semicolons to separate statements


const x = 5;
const y = 10;
const z = x + y;

[Link](z);

57. How do you extend classes?

In JavaScript, you can extend classes using the extends keyword to create a subclass or
derived class. The derived class inherits properties and methods from the parent class.
Example:
class Animal {
constructor(name) {
[Link] = name;
}
31
suhas@[Link]
speak() {
[Link](`${[Link]} makes a sound.`);
}
}

class Dog extends Animal {


constructor(name, breed) {
super(name); // Call the parent class constructor using super()
[Link] = breed;
}

speak() {
[Link](`${[Link]} barks!`);
}
}

// Create instances of the classes


const animal = new Animal('Animal');
[Link](); // Output: "Animal makes a sound."

const dog = new Dog('Buddy', 'Labrador');


[Link](); // Output: "Buddy barks!"

58. Explain arrays in JavaScript. Explain methods of Array with example

Arrays in JavaScript are used to store multiple values in a single variable. They are
ordered, indexed collections of values that can be of any data type, such as numbers,
strings, objects, or even other arrays. Arrays in JavaScript are dynamic, meaning their
size can change dynamically by adding or removing elements.
 push(): Adds one or more elements to the end of an array and returns the new
length of the array.
Example:
32
suhas@[Link]
const fruits = ['apple', 'banana'];
[Link]('orange');
[Link](fruits); // Output: ['apple', 'banana', 'orange']

 pop(): Removes the last element from an array and returns that element.
Example:
const fruits = ['apple', 'banana', 'orange'];
const removedFruit = [Link]();
[Link](removedFruit); // Output: 'orange'
[Link](fruits); // Output: ['apple', 'banana']

 shift(): Removes the first element from an array and returns that element.
Example:
const fruits = ['apple', 'banana', 'orange'];
const removedFruit = [Link]();
[Link](removedFruit); // Output: 'apple'
[Link](fruits); // Output: ['banana', 'orange']

 unshift(): Adds one or more elements to the beginning of an array and returns
the new length of the array.
Example:
const fruits = ['banana', 'orange'];
[Link]('apple');
[Link](fruits); // Output: ['apple', 'banana', 'orange']

 slice(): Returns a new array containing a portion of the original array,


specified by start and end indices.
Example:
const fruits = ['apple', 'banana', 'orange', 'grape', 'mango'];
const slicedFruits = [Link](1, 4);
[Link](slicedFruits); // Output: ['banana', 'orange', 'grape']

 concat(): Joins two or more arrays and returns a new array.


Example:
const fruits1 = ['apple', 'banana'];

33
suhas@[Link]
const fruits2 = ['orange', 'grape'];
const combinedFruits = [Link](fruits2);
[Link](combinedFruits); // Output: ['apple', 'banana', 'orange', 'grape']

59. Explain Strings in JavaScript. Explain methods of Strings with example

Strings in JavaScript are sequences of characters enclosed in single quotes ('') or double
quotes (""). They are used to represent text and can be manipulated using various string
methods provided by the String object.
 length: Returns the length of a string.
Example:
const str = 'Hello, World!';
[Link]([Link]); // Output: 13

 charAt(): Returns the character at a specified index in a string.

Example:
const str = 'Hello, World!';
[Link]([Link](7)); // Output: 'W'

 substring(): Returns a portion of a string based on start and end indices


Example:
const str = 'Hello, World!';
[Link]([Link](7, 12)); // Output: 'World'

 toUpperCase(): Converts a string to uppercase.


Example:
const str = 'Hello, World!';
[Link]([Link]()); // Output: 'HELLO, WORLD!'

 toLowerCase(): Converts a string to lowercase.


Example:
const str = 'Hello, World!';
[Link]([Link]()); // Output: 'hello, world!'

 concat(): Concatenates two or more strings.

34
suhas@[Link]
Example:
const str1 = 'Hello,';
const str2 = ' World!';
[Link]([Link](str2)); // Output: 'Hello, World!'

 indexOf(): Returns the index of the first occurrence of a specified substring


within a string.
Example:
const str = 'Hello, World!';
[Link]([Link]('World')); // Output: 7

 replace(): Replaces a specified value or substring with another value.

Example:
const str = 'Hello, World!';
[Link]([Link]('World', 'JavaScript')); // Output: 'Hello, JavaScript!'

 split(): Splits a string into an array of substrings based on a specified


separator.
Example:
const str = 'Hello, World!';
[Link]([Link](', ')); // Output: ['Hello', 'World!']

60. How do you redirect new page in javascript?


To redirect to a new page in JavaScript, you can use the [Link] object's href
property or the assign() method.
 Using [Link]:
[Link] = '[Link]

 Using [Link]():
[Link]('[Link]

 Using [Link]():
[Link]('[Link]

61. How do you check if a key exists in an object?

35
suhas@[Link]
To check if a key exists in an object in JavaScript, you can use the hasOwnProperty()
method or the in operator.
 Using the hasOwnProperty() method:
const obj = { name: 'John', age: 25 };

[Link]([Link]('name')); // Output: true


[Link]([Link]('gender')); // Output: false
 Using the in operator:
const obj = { name: 'John', age: 25 };

[Link]('name' in obj); // Output: true


[Link]('gender' in obj); // Output: false

62. What is an arguments object?


In JavaScript, the arguments object is a built-in object available within the scope of a
function. It contains an array-like collection of arguments passed to the function when
it is invoked.
Example:
function sum() {
let total = 0;
for (let i = 0; i < [Link]; i++) {
total += arguments[i];
}
return total;
}

[Link](sum(1, 2, 3)); // Output: 6


[Link](sum(4, 5, 6, 7)); // Output: 22

63. How do you test for an empty object?


To test if an object is empty in JavaScript, you can check if it has any own properties
using the [Link]() method or by checking the object's length.
Example:
const obj = {};

36
suhas@[Link]
if ([Link](obj).length === 0) {
[Link]("The object is empty");
} else {
[Link]("The object is not empty");
}

64. What is this keyword in javascript?


In JavaScript, the this keyword refers to the object that is currently executing the code
or the context in which the code is being executed. It is a special identifier that allows
you to access properties and methods within the scope of that object.
Example:
const obj = {
name: "John",
sayHello: function() {
[Link](`Hello, ${[Link]}!`);
}
};

[Link](); // Output: Hello, John!

65. what are callback fuctions in javascript?


In JavaScript, a callback function is a function that is passed as an argument to another
function and is executed at a later point in time or in response to an event. Callback
functions are a way to ensure that certain code is executed only after a particular task
or operation is completed.
Example:
function doMath(a, b, callback) {
const sum = a + b;
const difference = a - b;
// Call the callback function with the calculated values
callback(sum, difference);
}
37
suhas@[Link]
// Define a callback function
function handleResults(sum, difference) {
[Link]("Sum:", sum);
[Link]("Difference:", difference);
}

// Call the doMath function with the handleResults callback


doMath(10, 5, handleResults);

66. Why JavaScript is dynamically typed language? Explain the uses of JavaScript.
JavaScript is considered a dynamically typed language because it allows variables to
hold values of any data type, and the type of a variable can be changed during runtime.
This means that you don't have to explicitly declare the type of a variable before using
it, and the type of a variable can change based on the value assigned to it.
 Web development: JavaScript is primarily used to make web pages interactive,
handle user interactions, and create dynamic content on websites.

 Client-side scripting: JavaScript runs directly in the web browser, allowing


you to validate forms, manipulate HTML elements, and enhance the user
experience.

 Front-end frameworks: JavaScript frameworks like React, Angular, and


[Link] enable the development of complex and interactive user interfaces for
web applications.

 Server-side development: With [Link], JavaScript can be used on the server-


side to build scalable and high-performance applications, handling server logic
and database operations.

 Game development: JavaScript, along with libraries and game engines, can
be used to create browser-based games and even mobile games.

38
suhas@[Link]
67. What is the use of a constructor function in javascript?
In JavaScript, a constructor function is used to create and initialize objects of a
particular class or type. It serves as a blueprint for creating multiple instances of objects
with similar properties and methods.
Example:

function Person(name, age) {


[Link] = name;
[Link] = age;

[Link] = function() {
[Link]('Hello, my name is ' + [Link] + ' and I am ' + [Link] + ' years old.');
};
}

// Creating instances of Person using the constructor function


var person1 = new Person('John', 30);
var person2 = new Person('Jane', 25);

// Accessing properties and invoking methods


[Link]([Link]); // Output: John
[Link]([Link]); // Output: 25
[Link](); // Output: Hello, my name is John and I am 30 years old.
[Link](); // Output: Hello, my name is Jane and I am 25 years old.

68. Is there any relation between Java and JavaScript


JavaScript has no direct relation to Java besides being used for web technologies. The
name choice was a marketing move to encourage adoption.

69. How do you trim a string in javascript?


In JavaScript, you can trim a string by removing any leading and trailing whitespace
characters (such as spaces, tabs, or line breaks) from it. JavaScript provides two
methods for trimming strings: trim() and trimStart()/trimEnd().
39
suhas@[Link]
 trim(): The trim() method removes whitespace from both the beginning and the
end of a string.
 Example:
const str = ' Hello, World! ';
const trimmedStr = [Link]();
[Link](trimmedStr); // Output: 'Hello, World!'
 trimStart() and trimEnd(): These methods allow you to trim whitespace
from either the start or end of a string, respectively. They are available starting
from ECMAScript 2021 (ES12).
Example:
const str = ' Hello, World! ';
const trimmedStartStr = [Link]();
const trimmedEndStr = [Link]();
[Link](trimmedStartStr); // Output: 'Hello, World! '
[Link](trimmedEndStr); // Output: ' Hello, World!'

40
suhas@[Link]

You might also like