JavaScript Interview Questions and Answers (1)
JavaScript Interview Questions and Answers (1)
1. What is Javascript?
JavaScript is a scripting language most often used for client-side and server-side web
development.
function sayHello() {
[Link]('Hello, hoisting!');
}
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.
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.
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;
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();
if (true) {
var y = 20;
[Link](x); // Output: 10
[Link](y); // Output: 20
}
[Link](x); // Output: 10
[Link](y); // Output: 20
}
example();
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>
[Link]
// External JavaScript code
function greet() {
alert("Hello, World!");
}
Bracket notation:
let person = {
name: "John",
age: 30
};
[Link](myVariable); // Output: 42
[Link](myvariable); // Output: "Hello"
9
n
Boolean: Represents a logical value that can be either true or false.
Example: true, false
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
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;
}
ES6 Class:
Example:
class Person {
constructor(name, age, occupation) {
[Link] = name;
[Link] = age;
[Link] = occupation;
}
}
[Link]():
11
suhas@[Link]
Example:
let personPrototype = {
greeting: function() {
[Link]("Hello, I'm " + [Link]);
}
};
12
suhas@[Link]
Event is the predefined object in js where it contains all the information related to click
event.
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.`);
}
}
[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;
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
[Link](canVote); // Yes
Assignment Operators: Assignment operators are used to assign values to
variables.
Example:
let x = 10;
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);
}
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);
}
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
}
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
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
function incrementCount() {
count++;
[Link](count);
}
eval(code); // Output: 15
eval(dynamicCode); // Output: 50
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);
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];
const y = 20;
const y = 30; // Error: Identifier 'y' has already been declared
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:
<script>
// Event handler function
function handleClick() {
[Link]("Button clicked!");
}
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 + "!");
}
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 + "!");
};
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 + "!");
};
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.
<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.
<script>
// Get the form element
const form = [Link]('myForm');
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](z);
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.`);
}
}
speak() {
[Link](`${[Link]} barks!`);
}
}
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']
33
suhas@[Link]
const fruits2 = ['orange', 'grape'];
const combinedFruits = [Link](fruits2);
[Link](combinedFruits); // Output: ['apple', 'banana', 'orange', 'grape']
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
Example:
const str = 'Hello, World!';
[Link]([Link](7)); // Output: 'W'
34
suhas@[Link]
Example:
const str1 = 'Hello,';
const str2 = ' World!';
[Link]([Link](str2)); // Output: 'Hello, World!'
Example:
const str = 'Hello, World!';
[Link]([Link]('World', 'JavaScript')); // Output: 'Hello, JavaScript!'
Using [Link]():
[Link]('[Link]
Using [Link]():
[Link]('[Link]
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 };
36
suhas@[Link]
if ([Link](obj).length === 0) {
[Link]("The object is empty");
} else {
[Link]("The object is not empty");
}
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.
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:
[Link] = function() {
[Link]('Hello, my name is ' + [Link] + ' and I am ' + [Link] + ' years old.');
};
}
40
suhas@[Link]