JavaScript Interview Questions and Answers
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.
function sayHello() {
console.log('Hello, hoisting!');
}
5. What is DOM?
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.
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.
if (true) {
let y = 20;
console.log(x); // Output: 10
console.log(y); // Output: 20
}
console.log(x); // Output: 10
console.log(y); // Error: y is not defined
}
example();
if (true) {
var y = 20;
console.log(x); // Output: 10
console.log(y); // Output: 20
}
console.log(x); // Output: 10
console.log(y); // Output: 20
}
example();
<script>
// Inline JavaScript code
alert("Hello, World!");
</script>
</body>
</html>
Internal javascript
<!DOCTYPE html>
<html>
<head>
<title>Internal JavaScript Example</title>
<script>
// Internal JavaScript code
function greet() {
alert("Hello, World!");
}
</script>
</head>
<body>
<h1>Internal JavaScript Example</h1>
script.js
// External JavaScript code
function greet() {
alert("Hello, World!");
}
properties?
In JavaScript, there are several ways to access object properties.
Dot notation:
let person = {
name: "John",
age: 30
};
Bracket notation:
let person = {
name: "John",
age: 30
};
console.log(myVariable); // Output: 42
console.log(myvariable); // Output: "Hello"
JavaScript?
It separates HTML and code.
It makes HTML and JavaScript easier to read and maintain.
Cached JavaScript files can speed up page loads.
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
JavaScript?
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) {
this.name = name;
this.age = age;
this.occupation = occupation;
}
ES6 Class:
Example:
class Person {
constructor(name, age, occupation) {
this.name = name;
this.age = age;
this.occupation = occupation;
}
}
Object.create():
Example:
let personPrototype = {
greeting: function() {
console.log("Hello, I'm " + this.name);
}
};
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.
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age}
years old.`);
}
}
console.log(double(5)); // Output: 10
console.log(triple(5)); // Output: 15
32. What are the different types of operators in
console.log(-x); // Negation: -5
console.log(++x); // Increment: 6
console.log(--x); // Decrement: 5
console.log(!true); // Logical NOT: false
function globalFunction() {
console.log(globalVariable);
}
globalFunction(); // Output: I am a global variable
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];
console.log(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++;
console.log(count);
}
slice splice
Returns removed elements from Returns selected elements from
the array the array
Mutates original array Does not mutate original array
Can add new elements to array Can’t add new elements
eval(code); // Output: 15
eval(dynamicCode); // Output: 50
In JavaScript, you can get the current URL (Uniform Resource Locator)
of the webpage using the window.location object. The window.location
object provides information about the current URL and various properties
and methods to access different parts of the URL.
Example:
let currentURL = window.location.href;
console.log(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
with Examples.
In JavaScript, there are several ways to output or display information to
the console or the user.
console.log():
console.log("Hello, World!"); // Output: Hello, World!
alert():
alert("Welcome to our website!"); // Displays a popup with the
message "Welcome to our website!"
document.write():
document.write("Hello, World!"); // Output: Hello, World!
innerHTML:
<div id="myElement"></div>
<script>
let element = document.getElementById("myElement");
element.innerHTML = "Hello, World!"; // The content of the div
will be replaced with "Hello, World!"
</script>
<script>
// Event handler function
function handleClick() {
console.log("Button clicked!");
}
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) {
console.log("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) => {
console.log("Hello, " + name + "!");
};
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++) {
console.log(i);
}
// Output: 0 1 2 3 4
while loop:
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
// Output: 0 1 2 3 4
do-while loop:
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
// Output: 0 1 2 3 4
if statement:
let age = 20;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
// Output: You are an adult.
switch statement:
let day = "Monday";
switch (day) {
case "Monday":
console.log("It's Monday.");
break;
case "Tuesday":
console.log("It's Tuesday.");
break;
default:
console.log("It's another day.");
}
// Output: It's Monday.
Examples.
<script>
let element = document.getElementById("myDiv");
console.log(element.innerHTML); // 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 = document.getElementsByClassName("highlight");
for (let i = 0; i < elements.length; i++) {
console.log(elements[i].innerHTML);
}
// Output:
// 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 = document.getElementsByTagName("p");
for (let i = 0; i < elements.length; i++) {
console.log(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 = document.querySelector(".myDiv");
console.log(element.innerHTML); // Output: Hello, World!
</script>
<script>
// Get the form element
const form = document.getElementById('myForm');
// Add an event listener to the form's submit event
form.addEventListener('submit', function(event) {
event.preventDefault(); // Prevent the default form submission behavior
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:
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';
// Example usage
const email1 = '[email protected]';
const email2 = 'invalid.email@com';
const email3 = 'another@example';
console.log(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) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
speak() {
console.log(`${this.name} barks!`);
}
}
pop(): Removes the last element from an array and returns that
element.
Example:
const fruits = ['apple', 'banana', 'orange'];
const removedFruit = fruits.pop();
console.log(removedFruit); // Output: 'orange'
console.log(fruits); // Output: ['apple', 'banana']
shift(): Removes the first element from an array and returns that
element.
Example:
const fruits = ['apple', 'banana', 'orange'];
const removedFruit = fruits.shift();
console.log(removedFruit); // Output: 'apple'
console.log(fruits); // Output: ['banana', 'orange']
Using window.location.assign():
window.location.assign('https://www.example.com');
Using window.location.replace():
window.location.replace('https://www.example.com');
61. How do you check if a key exists in an object?
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 };
if (Object.keys(obj).length === 0) {
console.log("The object is empty");
} else {
console.log("The object is not empty");
}
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) {
this.name = name;
this.age = age;
this.greet = function() {
console.log('Hello, my name is ' + this.name + ' and I am ' + this.age + '
years old.');
};
}