Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

javascript

Uploaded by

hossainemon5821
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

javascript

Uploaded by

hossainemon5821
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

JavaScript

1. What is JavaScript, and what is its primary purpose in web development?

JavaScript is a high-level, versatile programming language primarily known for its use in web
development. It is an essential component of modern web browsers and enables the creation of
dynamic and interactive web pages. one of the most widely used programming languages.

The primary purpose of JavaScript in web development is to enhance the user experience by
allowing developers to create dynamic and interactive content.

JavaScript is mainly used for client-side scripting, which means it runs in the user's web browser
rather than on the server. This allows developers to create dynamic and responsive user
interfaces that can update and change without requiring a page reload.

JavaScript is used to manipulate the Document Object Model (DOM), which represents the
structure of an HTML document.

JavaScript enables developers to respond to user actions such as clicks, keypresses, and mouse
movements. This allows for the creation of interactive elements and responsive user interfaces.

JavaScript supports asynchronous programming, allowing developers to make asynchronous


requests to a server (AJAX) without blocking the execution of the rest of the code. This is crucial
for building efficient and responsive web applications.

JavaScript is supported by all major web browsers, making it a versatile language for building
web applications that work across different platforms.

There are numerous JavaScript frameworks and libraries, such as React, Angular, and Vue.js,
that simplify and enhance the process of building complex web applications by providing
reusable components and abstractions.

2. Explain the difference between JavaScript and Java.

JavaScript and Java are two distinct programming languages with different purposes, design
principles, and use cases. Here are some key differences between JavaScript and Java:

1. Purpose and Usage:


o JavaScript: Primarily used for client-side scripting in web development. It runs
in web browsers and is responsible for making web pages interactive and
dynamic. JavaScript is not limited to web development and can also be used on
the server side (e.g., with Node.js).
o Java: A general-purpose, object-oriented programming language. Java is often
used for developing server-side applications, mobile applications (Android), and
large-scale enterprise applications. It is not inherently tied to web development,
although it can be used for that purpose.
2. Platform:
o JavaScript: Runs in web browsers on the client side. Modern browsers have
JavaScript engines that interpret and execute JavaScript code.
o Java: Designed to be platform-independent. Java code is compiled into an
intermediate form called bytecode, which can be executed on any device that has
a Java Virtual Machine (JVM). This platform independence is one of the key
features of Java.
3. Syntax and Structure:
o JavaScript: Has C-style syntax and is a lightweight, interpreted language.
o Java: Also has C-style syntax, but it is a statically-typed language, meaning
variable types must be declared before compilation.
4. Inheritance and Object-Oriented Features:
o JavaScript: Prototypal inheritance, and it supports object-oriented programming
features
o Java: Class-based inheritance, where objects are instances of classes

3. How do you declare a variable in JavaScript?

In JavaScript, you can declare a variable using the var, let, or const keyword. The choice of
which keyword to use depends on the scope and mutability of the variable. Here are the basic
ways to declare variables in JavaScript:

Using var : var myVariable = "Hello, World!";

Variables declared with var are function-scoped, and they are hoisted to the top of their
scope during execution.

• Using let: let myVariable = "Hello, World!";

Variables declared with let are block-scoped, which means they are only accessible within the
block (enclosed by curly braces) where they are defined.

• Using const: const myVariable = "Hello, World!";

Variables declared with const are also block-scoped, and they cannot be reassigned once
a value is assigned.

In modern JavaScript, it's generally recommended to use let and const for variable
declarations, with const being the preferred choice whenever possible to enforce immutability.
Use let only when you need to reassign the variable.

4. What are the basic data types in JavaScript?


JavaScript has several basic data types that are used to represent different kinds of values. These
data types can be broadly categorized into two main groups: primitive data types and object data
types. Here are the basic data types in JavaScript:

1. Primitive Data Types:


o String: Represents textual data and is enclosed in single (' '), double (" "), or
backtick (` `) quotes.

let greeting = "Hello, World!";

• Number: Represents numeric data, including integers and floating-point numbers.

let age = 25;


let pi = 3.14;

• Boolean: Represents either true or false, and is often used for logical operations.

let isTrue = true;


let isFalse = false;

• Undefined: Represents a variable that has been declared but not assigned a value.

let undefinedVar;

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

let nullVar = null;

• Symbol (ES6 and later): Represents a unique identifier and is often used as an identifier for
object properties.

let mySymbol = Symbol("unique");

Object Data Types:

• Object: Represents a collection of key-value pairs, where keys are strings or symbols,
and values can be any data type.

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

• Array: Represents an ordered list of values and is created using square brackets.

let colors = ["red", "green", "blue"];


• Function: Represents a reusable block of code and is defined using the function keyword.

function addNumbers(a, b) {
return a + b;
}

• Date: Represents a date and time.

let currentDate = new Date();

These data types provide the building blocks for writing JavaScript programs. It's important to
note that JavaScript is a dynamically-typed language

5. Describe the role of the console.log() function in JavaScript.

The console.log() function in JavaScript is a method used for logging messages to the
console. It is a part of the Console API, which provides methods for interacting with the
browser's developer console. The primary purpose of console.log() is to output information,
such as text, variables, or object properties, to the console for debugging and development
purposes.

Here's a basic overview of the role of console.log():

console.log("Hello, World!");

The console.log() function can be used to display text messages in the console. This is useful
for providing feedback about the execution of your code.

let name = "John";


console.log("Name:", name);

You can use console.log() to log the values of variables. This is particularly helpful for
checking the current state of variables during runtime.

let age = 25;


console.log("Name:", name, "Age:", age);

The output of console.log() is typically visible in the browser's developer tools console, which
can be opened by right-clicking on a webpage, selecting "Inspect" or "Inspect Element," and
navigating to the "Console" tab. This tool is invaluable for developers to gain insights into their
code's behavior and troubleshoot issues during development. However, it's essential to remove or
disable unnecessary console.log() statements in production code to avoid unnecessary output
and potential performance issues.

6. What is a function in JavaScript, and how do you define one?


In JavaScript, a function is a reusable block of code that performs a specific task or set of tasks.
Functions are a fundamental building block of JavaScript programming and are used to organize
and modularize code, making it more manageable, readable, and reusable. Functions can accept
input parameters (arguments), perform computations, and return a result.

Here's the basic syntax for defining a function in JavaScript:

function functionName(parameter1, parameter2, /* ... */) {


// Function body: code to be executed
// It can include statements, expressions, and more.

// Optional: Return statement to return a value


return result;
}

Here:

• function keyword: Indicates the start of a function declaration.


• functionName: The name of the function, which is used to call and invoke the function.
• parameter1, parameter2, /* ... */: Optional parameters that the function can
accept. Parameters act as placeholders for values passed to the function.
• Function body: The block of code enclosed in curly braces {}. This is where the actual
logic of the function is defined.
• return result;: An optional return statement that specifies the value to be returned
by the function. If omitted, the function returns undefined.

Functions in JavaScript can also be assigned to variables, passed as arguments to other functions,
and even defined anonymously (without a name) as function expressions. They provide a
powerful mechanism for organizing and structuring code in a way that promotes reusability and
maintainability.

7. Explain the purpose of the return statement in a function.

The return statement in a JavaScript function serves the purpose of specifying the value that the
function should produce or provide back to the code that called it. When a function is invoked,
the return statement allows it to send a value (or undefined if no value is specified) back to the
calling code.

Here are the key purposes and aspects of the return statement:

1. Returning a Value:

function addNumbers(a, b) {
let sum = a + b;
return sum;
}
In this example, the return statement is used to send back the calculated sum of a and b to the
calling code. The value returned by the function can be assigned to a variable or used in any way
the calling code needs.

• Ending Function Execution: The return statement not only specifies the value to be
returned but also serves as an instruction to terminate the execution of the function.

function greet(name) {
if (!name) {
return "Hello, anonymous!";
}
return "Hello, " + name + "!";
}

In this example, if the name parameter is not provided (falsy), the function returns a default
greeting for anonymous users, and the function execution stops. If a name is provided, the
function continues to the second return statement.

It's important to note that a function can have multiple return statements, but only one of them
will be executed. Once a return statement is encountered, the function exits, and the specified
value is returned to the calling code

8. How can you check the data type of a variable in JavaScript?

In JavaScript, you can check the data type of a variable using the typeof operator. The typeof
operator returns a string indicating the data type of the operand. Here's how you can use it:

let myVar = "Hello, World!";

console.log(typeof myVar); // Output: "string"

The typeof operator is followed by the variable or expression you want to examine. It returns a
string representing the data type of the operand.

Here are some examples:

let num = 42;


console.log(typeof num); // Output: "number"

let bool = true;


console.log(typeof bool); // Output: "boolean"

let obj = { key: "value" };


console.log(typeof obj); // Output: "object"

let func = function () {};


console.log(typeof func); // Output: "function"
It's important to note that the typeof operator has some quirks. For example, it returns "object"
for null values, which is not intuitive. Additionally, it doesn't distinguish between different types
of objects (arrays, functions, regular objects) - they all return "object".

9. Describe the if...else statement in JavaScript.

The if...else statement in JavaScript is a control structure that allows you to execute different
blocks of code based on a specified condition. It enables your program to make decisions and
take different actions depending on whether a given condition evaluates to true or false. Here
is the basic syntax of the if...else statement:

if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}

• condition: An expression that is evaluated to either true or false. If the condition is


true, the code block inside the first set of curly braces {} is executed. Otherwise, if the
condition is false, the code block inside the second set of curly braces is executed.

Here's a simple example:

let temperature = 25;

if (temperature > 30) {


console.log("It's a hot day!");
} else {
console.log("It's not too hot today.");
}

In this example:

• The condition temperature > 30 is evaluated.


• If the condition is true, the code inside the first block is executed, logging "It's a hot day!"
to the console.
• If the condition is false, the code inside the else block is executed, logging "It's not too
hot today."

10.What is a ternary operator, and how is it used in JavaScript?

The ternary operator, also known as the conditional operator, is a concise way to write an
if...else statement in a single line of code. It is often used when you need to assign a value to
a variable based on a condition. The syntax of the ternary operator is as follows:

condition ? expressionIfTrue : expressionIfFalse;


• condition: A Boolean expression that is evaluated. If the condition is true, the
expression before the colon (:) is executed; otherwise, the expression after the colon is
executed.
• expressionIfTrue: The value to be assigned if the condition is true.
• expressionIfFalse: The value to be assigned if the condition is false.

Here's an example that uses the ternary operator to determine if a person is eligible to vote:

let age = 20;

let eligibility = age >= 18 ? "Eligible to vote" : "Not eligible to vote";


console.log(eligibility);

In this example:

• The condition age >= 18 is evaluated.


• If the condition is true, the string "Eligible to vote" is assigned to the variable
eligibility.
• If the condition is false, the string "Not eligible to vote" is assigned.

While the ternary operator can make code more concise, it's essential to use it judiciously.
Complex conditions or expressions might make the code less readable, and in such cases, an
if...else statement may be more appropriate.

11.Explain the switch statement and its use cases.

The switch statement in JavaScript is a control structure that allows you to execute different
blocks of code based on the value of an expression. It provides a concise way to handle multiple
conditions when you need to compare a single value against multiple possible values. The basic
syntax of a switch statement looks like this:

javascript
switch (expression) {
case value1:
// Code to be executed if expression equals value1
break;
case value2:
// Code to be executed if expression equals value2
break;
// Additional cases as needed
default:
// Code to be executed if none of the cases match expression
}

• expression: The value to be compared against the possible case values.


• case value1:: A specific value that expression is compared against. If it matches, the
associated block of code is executed.
• break: Optional keyword that terminates the switch statement. If omitted, the next case
will be executed, regardless of whether its condition is met.
• default:: An optional case that is executed if none of the other cases match. It's similar
to the else clause in an if...else statement.

Use Cases for switch Statements:

1. Multiple Conditions on a Single Value: The primary use case for switch statements is
when you need to check a single value against multiple possible values, and each value
corresponds to a different set of actions.
2. Readable Code for Limited Value Sets: switch statements are particularly useful when
you have a limited set of possible values, and the code can be more readable than a series
of if...else if statements.
3. Replacing Long Chains of if...else if Statements: When dealing with a long chain
of if...else if statements, a switch statement can make the code more concise and
maintainable.
4. Enumerations and Constants: switch statements are commonly used with constants or
enumeration-like values, providing a clear structure for handling different cases.

It's important to note that switch statements are not always the best choice.

12.How do you create a for loop in JavaScript? What is a while loop, and when
would you use it?

In JavaScript, a for loop is used to repeatedly execute a block of code a specified number of
times. It's a convenient way to perform tasks like iterating over arrays, generating sequences of
numbers, or executing code with a known number of iterations. The basic syntax of a for loop is
as follows:

for (initialization; condition; update) {


// Code to be executed in each iteration
}

• initialization: Executed before the loop starts. It typically initializes a counter


variable.
• condition: Checked before each iteration. If true, the loop continues; otherwise, it exits.
• update: Executed after each iteration. It typically increments or updates the counter
variable.

Now, regarding the while loop:

A while loop is another type of loop in JavaScript that continues to execute a block of code as
long as a specified condition is true. The basic syntax of a while loop is as follows:

while (condition) {
// Code to be executed as long as the condition is true
}
Here's an example of a while loop that counts from 1 to 5:

let count = 1;

while (count <= 5) {


console.log(count);
count++;
}

When to Use while Loops:

• When the Number of Iterations is Not Known in Advance: Use a while loop when
you don't know the number of iterations beforehand, and you want to continue looping as
long as a certain condition is true.
• When Working with Dynamic Conditions: while loops are suitable when the loop's
continuation depends on dynamic conditions that may change during the course of
execution.
• When Implementing Infinite Loops: while (true) can be used to create an infinite
loop. Be cautious when using infinite loops to ensure there's a way to exit the loop.

Both for and while loops are powerful constructs, and the choice between them depends on the
specific requirements of your code. In many cases, either loop type can be used interchangeably,
but for loops are often preferred when the number of iterations is known in advance.

13.How can you exit or break out of a loop prematurely in JavaScript?

In JavaScript, you can exit or break out of a loop prematurely using the break statement. The
break statement is used to terminate the execution of a loop, and it works with both for and
while loops. When a break statement is encountered inside a loop, the loop is immediately
exited, and the program continues with the next statement after the loop.

Here's an example of using break in a for loop:

for (let i = 0; i < 10; i++) {


console.log(i);
if (i === 5) {
break; // Exit the loop when i reaches 5
}
}

In this example, the loop will iterate from 0 to 5, and when i becomes equal to 5, the break
statement is encountered, and the loop is terminated.

Similarly, you can use break in a while loop:

javascript
let i = 0;

while (i < 10) {


console.log(i);
if (i === 5) {
break; // Exit the loop when i reaches 5
}
i++;
}

In both examples, the break statement is conditional on the value of i, but you can use it
based on any condition that you need.

It's important to note that the use of break should be judicious to avoid creating code that is
hard to understand or maintain. In some cases, there might be alternative ways to structure
your code without the need for premature exits from loops.

14.What is the purpose of the continue statement in a loop?

The continue statement in JavaScript is used to skip the rest of the code inside a loop for the
current iteration and move to the next iteration. When a continue statement is encountered, it
immediately jumps to the next iteration of the loop, skipping any code that follows it within the
current iteration.

The basic syntax of the continue statement is as follows:

for (initialization; condition; update) {

if (conditionToSkipRestOfCode) {
continue;
}

// Code here will be skipped if continue is executed


}

Here's a simple example using continue in a for loop to skip printing even numbers:

for (let i = 0; i < 5; i++) {


if (i % 2 === 0) {
continue; // Skip even numbers
}
console.log(i);
}

In this example, the loop iterates from 0 to 4, but when i is an even number (divisible by 2), the
continue statement is executed, skipping the console.log(i) statement for that iteration. As a
result, only odd numbers are printed to the console.

While continue can be a powerful tool for controlling the flow of your loops, it's important to
use it judiciously to maintain code readability and avoid creating complex and hard-to-follow
logic.
15. How do you define default values for function parameters in JavaScript?

In JavaScript, you can define default values for function parameters using the assignment
operator (=) in the function declaration. This allows you to specify a default value that will be
used if the corresponding argument is not provided when the function is called.

Here's the basic syntax for defining default values:

function myFunction(param1 = defaultValue1, param2 = defaultValue2) {


// Function body
}

In this syntax:

• param1, param2, etc.: The function parameters.


• defaultValue1, defaultValue2, etc.: The default values assigned to the parameters.

Here's an example of a function with default parameter values:

javascript
function greet(name = "Guest", greeting = "Hello") {
console.log(`${greeting}, ${name}!`);
}

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


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

In this example, the greet function has two parameters, name and greeting, each with a default
value. If the corresponding argument is not provided when calling the function, the default value
is used.

It's important to note the following regarding default parameter values:

Default values are evaluated at call time: The expression providing the default value is
evaluated when the function is called, not when the function is defined. This means you can use
dynamic expressions or values based on the current state of the program.

Default values can reference previous parameters: Default values can reference previously
declared parameters in the parameter list.

Default values can be undefined: If a parameter with a default value is explicitly passed as
undefined, the default value is used.

Using default parameter values is a helpful feature for making functions more flexible and
expressive, especially when dealing with optional parameters or providing sensible defaults for
commonly used values.
16. Describe the difference between function expressions and function
declarations.

Function expressions and function declarations are two ways to define functions in JavaScript,
and they differ in how they are created and when they are hoisted.

Function Declaration:

o A function declaration is a statement that defines a named function.


o It starts with the function keyword, followed by the name of the function, a list
of parameters in parentheses, and the function body in curly braces.
o Function declarations are hoisted, meaning they are moved to the top of their
containing scope during the compilation phase. This allows you to call the
function before its actual declaration in the code.

Example:

function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("John");

Function Expression:

• A function expression is the assignment of a function to a variable. The function can be


anonymous or have a name.
• It is created using the const, let, or var keyword, followed by a variable name, the
assignment operator, and the function definition.
• Function expressions are not hoisted in the same way as function declarations. The
variable is hoisted, but the assignment of the function to the variable occurs at runtime, so
you cannot call the function before the assignment.

Example:

const greet = function(name) {


console.log(`Hello, ${name}!`);
};
greet("John");

In summary, the key differences are related to hoisting and the way functions are defined.
Function declarations are hoisted along with their names, allowing them to be called before their
actual position in the code. Function expressions, on the other hand, involve the assignment of a
function to a variable, and the assignment is not hoisted in the same way, restricting the ability to
call the function before the assignment statement.

17. What is a callback function, and how is it used in JavaScript? How do you
create an anonymous function in JavaScript?
Callback Function:

In JavaScript, a callback function is a function that is passed as an argument to another function


and is executed after the completion of some operation. Callbacks are a way to ensure that
certain code doesn't execute until a specific task is completed, making them particularly useful
for asynchronous operations.

Here's a simple example to illustrate the concept of a callback function:

function doSomethingAsync(callback) {
setTimeout(function() {
console.log("Task is done!");
callback();
}, 1000);
}

function afterTask() {
console.log("Callback function executed.");
}

// Using the callback function


doSomethingAsync(afterTask);

In this example,

15. doSomethingAsync is a function that takes a callback function (callback) as an


argument.
16. Inside doSomethingAsync, there's a setTimeout function, simulating an asynchronous
task that takes 1000 milliseconds (1 second) to complete.
17. After the timeout, it logs "Task is done!" to the console and then invokes the provided
callback function (callback()).
18. The afterTask function is defined separately and serves as the callback function. In this
case, it simply logs "Callback function executed." to the console.

Finally, the doSomethingAsync(afterTask) line calls doSomethingAsync with afterTask as


the callback function. This means that after the asynchronous task (the timeout) is complete,
afterTask will be executed.

Anonymous Function in JavaScript:

An anonymous function is a function without a name. In JavaScript, you can create anonymous
functions in a couple of ways. Here's an example:

// Using function expression


var add = function(x, y) {
return x + y;
};
// Using arrow function (introduced in ES6)
var multiply = (a, b) => {
return a * b;
};

// Anonymous function as a callback


doSomethingAsync(function() {
console.log("Anonymous callback executed.");
}
);

In the above examples, add and multiply are named functions, while the function passed as a
callback to doSomethingAsync is an anonymous function. Anonymous functions are often used
for short-lived tasks or when a function is used only once.

Arrow functions (() => { /* code */ }) are a concise way to create anonymous functions,
and they also have a shorter syntax compared to traditional function expressions. They are
particularly useful in callback scenarios and are widely used in modern JavaScript development.

18. Explain the concept of scope in JavaScript, including global and local scope.
In JavaScript, the concept of scope refers to the visibility and accessibility of variables. A
variable's scope determines where in your code that variable can be accessed or modified.
JavaScript has two main types of scope: global scope and local (or function) scope.

Global Scope:

A variable declared outside of any function or block has a global scope. It can be accessed from
any part of your code, including both inside and outside functions.

Example:

let globalVariable = "I'm a global variable";

function exampleFunction() {
console.log(globalVariable); // Accessible inside the function
}

exampleFunction(); // Output: "I'm a global variable"


console.log(globalVariable); // Also accessible outside the function

Local (Function) Scope:

A variable declared inside a function or block has local scope. It is accessible only within that
function or block and not from outside.

Example:
function exampleFunction() {
// Local scope
let localVariable = "I'm a local variable";
console.log(localVariable); // Accessible inside the function
}

exampleFunction(); // Output: "I'm a local variable"

// This would throw an error because localVariable is not defined outside the
function
console.log(localVariable);

Block Scope (ES6+): In modern JavaScript (ES6 and later), the let and const keywords
introduce block-scoped variables. A block is any section of code surrounded by curly braces {}
(e.g., if statements, loops, and functions).

Scope Chain:

JavaScript follows a scope chain when resolving the value of a variable. If a variable is not found
in the current scope, JavaScript looks for it in the outer (enclosing) scope. This process continues
until the variable is found or until the global scope is reached. This is known as lexical scoping,
where the scope of a variable is determined by its position in the source code.

Understanding the scope is crucial for writing maintainable and bug-free code. It helps prevent
naming conflicts, allows for better organization of code, and ensures that variables are used in
the intended manner. Always consider the scope of your variables when designing and
structuring your JavaScript code.

19. What is a closure, and why is it important in JavaScript? Describe the concept
of function hoisting.

Closure:

A closure is a fundamental concept in JavaScript that allows a function to retain access to


variables from its outer (enclosing) scope, even after the outer function has finished executing. In
simpler terms, a closure is created when a function is defined inside another function, and the
inner function has access to the variables of the outer function, even after the outer function has
completed execution.

Example:

function outerFunction() {
let outerVariable = "I'm from the outer function";

function innerFunction() {
console.log(outerVariable);
}

return innerFunction;
}

const closure = outerFunction();


closure(); // Output: "I'm from the outer function"

In this example, innerFunction is defined inside outerFunction, and it has access to


outerVariable even after outerFunction has completed. When outerFunction is invoked
and assigned to the variable closure, it returns the inner function. Later, when closure() is
called, it still has access to outerVariable, demonstrating the concept of closure.

Importance of Closures:

1. Data Encapsulation: Closures allow for data encapsulation, helping to create private
variables. The variables inside the outer function are not directly accessible from outside,
but they can be accessed through the inner function.
2. Function Factory: Closures are commonly used to create function factories, where a
function returns another function with specific behavior based on the initial parameters.
3. Callback Functions: Closures are frequently used in callback functions, allowing the
callback to access variables from the surrounding context.
4. Module Pattern: Closures are a key component of the module pattern, enabling the
creation of private and public methods within a module.

Function Hoisting:

Function hoisting is a JavaScript behavior where function declarations are moved (hoisted) to the
top of their containing scope during the compilation phase. This means that you can call a
function before its actual declaration in the code.

Example:

hoistedFunction(); // Output: "I'm hoisted!"

function hoistedFunction() {
console.log("I'm hoisted!");
}

Function hoisting applies only to function declarations, not to function expressions. When you
declare a function using the function keyword, it is hoisted along with its entire definition.

Understanding function hoisting is important for writing predictable code and avoiding issues
where a function is called before its declaration. However, it's good practice to declare functions
and variables at the beginning of their scope to enhance code readability and maintainability.

20. How do you create an array in JavaScript, and what is its structure?

In JavaScript, you can create an array using the array literal notation or the Array constructor.
Here's how you can create an array using each method:
Using Array Literal Notation:

The array literal notation involves using square brackets [] to declare an array. You can initialize
the array with elements inside the brackets, separated by commas.

Example:

const fruits = ["apple", "banana", "orange"];

// Creating an empty array


const emptyArray = [];

Using Array Constructor:

You can also use the Array constructor to create an array. You can pass the elements as
arguments to the constructor, or you can create an array with a specific length.

Example:

const colors = new Array("red", "green", "blue");

// Creating an empty array


const anotherEmptyArray = new Array();

Array Structure:

An array in JavaScript is an ordered, indexed collection of values. Key features of an array


include:

1. Indexing:
o Array elements are accessed using zero-based indices. The first element is at
index 0, the second at index 1, and so on.
o You can access array elements using square bracket notation.

const fruits = ["apple", "banana", "orange"];


console.log(fruits[0]); // Output: "apple"
console.log(fruits[1]); // Output: "banana"

2. Length:

• The length property indicates the number of elements in the array.


• It is automatically updated as elements are added or removed.

const fruits = ["apple", "banana", "orange"];


console.log(fruits.length); // Output: 3

3. Mixed Data Types:


• Arrays in JavaScript can contain elements of different data types, including numbers,
strings, objects, or even other arrays.

const mixedArray = [1, "two", { key: "value" }, [3, 4]];

4. Dynamic Size:

• JavaScript arrays are dynamic, meaning you can add or remove elements at any time.

const numbers = [1, 2, 3];


numbers.push(4); // Adds an element to the end
numbers.pop(); // Removes the last element

5. Iteration:

• Arrays can be iterated using loops or array methods like forEach, map, filter, and
others.

const numbers = [1, 2, 3];

for (let i = 0; i < numbers.length; i++) {


console.log(numbers[i]);
}

// Using forEach
numbers.forEach(function (number) {
console.log(number);
});

Arrays in JavaScript are versatile and widely used for storing and manipulating collections of
data. Understanding how to create, access, and manipulate arrays is fundamental for JavaScript
development.

21. What is the difference between an array and an object in JavaScript?

In JavaScript, both arrays and objects are used to store and manipulate data, but they have
distinct characteristics and use cases. Here's a comparison between arrays and objects based on
various points:

1. Declaration and Initialization:

Array: Ordered, iterating by index, support any data type,has builtin method like(pop(), splice(), shift()
, unshift()
let myArray = [1, 2, 3, 4];

Object: Unordered, access by keys, key must be string, value any data type, no buildin method

let myObject = {key1: 'value1', key2: 'value2', key3: 'value3'};


1. Ordering:
o Array:
▪ Ordered collection of elements. Each element has an index (starting from
0).
▪ Elements are accessed using numerical indices.
o Object:
▪ Unordered collection of key-value pairs.
▪ Access values using keys (strings).
2. Data Types:
o Array:
▪ Can store any data type, including other arrays.
▪ Elements are accessed by index.
o Object:
▪ Values can be of any data type, and keys are always strings.
▪ Access values by key.
3. Use Cases:
o Array:
▪ Used when the order of elements is important (e.g., lists, sequences).
▪ Suitable for iterating through elements using loops.
o Object:
▪ Used when data is better represented as key-value pairs (e.g., representing
entities with properties).
▪ Convenient for quick data lookups based on keys.
4. Length/Size:
o Array:
▪ Has a length property indicating the number of elements.
o Object:
▪ Does not have a built-in property for the number of key-value pairs, but
you can use methods like Object.keys(obj).length to get the count.
5. Methods:
o Array:
▪ Arrays come with built-in methods like push(), pop(), shift(), and
unshift() for adding and removing elements.
o Object:
▪ Objects do not have built-in methods for manipulating their structure like
arrays, but you can add, modify, or delete key-value pairs.
6. Iteration:
o Array:
▪ Easily iterated using loops or array methods like forEach().
o Object:
▪ Iteration requires additional steps, such as converting keys into an array
using Object.keys(obj) and then iterating.
In summary, arrays are suitable for ordered collections of similar elements, while objects are
more appropriate for dealing with data in a key-value pair format, where each value has a distinct
identifier (key). Understanding the nature of your data and the operations you need to perform on
it will help you choose between arrays and objects in JavaScript.

22. Explain how to add and remove elements from an array. Describe the purpose
of the forEach() method for arrays.

Adding Elements to an Array:

There are several ways to add elements to an array in JavaScript.

1. push() Method:

The push() method adds one or more elements to the end of an array and returns the new length
of the array.

const fruits = ["apple", "banana"];


fruits.push("orange");
console.log(fruits); // Output: ["apple", "banana", "orange"]
2. unshift() Method:

The unshift() method adds one or more elements to the beginning of an array and returns the
new length of the array.

const fruits = ["banana", "orange"];


fruits.unshift("apple");
console.log(fruits); // Output: ["apple", "banana", "orange"]
3. splice() Method:

The splice() method can be used to add elements at a specific position in the array. It also
allows for the removal of elements.

const fruits = ["apple", "banana", "orange"];


fruits.splice(1, 0, "grape"); // Adds "grape" at index 1
console.log(fruits); // Output: ["apple", "grape", "banana", "orange"]

Removing Elements from an Array:

Similarly, there are various methods to remove elements from an array.

1. pop() Method:

The pop() method removes the last element from an array and returns that element.

const fruits = ["apple", "banana", "orange"];


const removedFruit = fruits.pop();
console.log(removedFruit); // Output: "orange"
console.log(fruits); // Output: ["apple", "banana"]
2. shift() Method:

The shift() method removes the first element from an array and returns that element.

const fruits = ["apple", "banana", "orange"];


const removedFruit = fruits.shift();
console.log(removedFruit); // Output: "apple"
console.log(fruits); // Output: ["banana", "orange"]
3. splice() Method for Removal:

The splice() method can be used to remove elements at a specific position in the array.

const fruits = ["apple", "banana", "orange"];


fruits.splice(1, 1); // Removes 1 element at index 1
console.log(fruits); // Output: ["apple", "orange"]

forEach() Method:

The forEach() method is used to iterate over elements in an array. It executes a provided
function once for each array element, allowing you to perform a specific action for each element.

const numbers = [1, 2, 3, 4, 5];

numbers.forEach(function (number) {
console.log(number * 2);
});
Output:
2
4
6
8
10

The forEach() method takes a callback function as an argument, and this function is called once
for each element in the array. The callback function can take three parameters: the current
element, the index of the current element, and the array itself.

const numbers = [1, 2, 3, 4, 5];

numbers.forEach(function (number, index, array) {


console.log(`Index ${index}: ${number} (from array: ${array})`);
});
Output:
Index 0: 1 (from array: 1,2,3,4,5)
Index 1: 2 (from array: 1,2,3,4,5)
Index 2: 3 (from array: 1,2,3,4,5)
Index 3: 4 (from array: 1,2,3,4,5)
Index 4: 5 (from array: 1,2,3,4,5)
The forEach() method is commonly used when you want to perform an action for each element
in the array without the need for a traditional for loop. It provides a more concise and expressive
way to iterate over arrays.

23. Explain the difference between getElementById and querySelector for element
selection.

Both getElementById and querySelector are methods in JavaScript that are used to select
HTML elements from the Document Object Model (DOM), but they have some key differences
in terms of their syntax and capabilities.

getElementById: Old method, fast, support all browser, find only ID, ID should be unique

The getElementById method is a traditional and straightforward way to select an element based
on its unique identifier (ID). It is commonly used when you have a specific element with a
known ID in your HTML.

Syntax:

const element = document.getElementById("myElementId");

querySelector: New method, slower, support update browser, find CSS selector, Select first match

The querySelector method is more versatile and allows for more flexible element selection. It
uses CSS selectors to target elements, providing a broader range of options compared to
getElementById.

Syntax:

const element = document.querySelector("#myElementId");

Let's compare getElementById and querySelector in JavaScript based on various points:

1. Purpose:
o getElementById: Finds an element in the document with the specified ID.

querySelector: Finds the first element in the document that matches the
specified CSS selector.

1. Compatibility:
o getElementById:
▪ Limited to selecting elements based on their ID.
▪ Older method, but widely supported in all browsers.
o querySelector:
▪ Allows more complex selections using CSS selectors, supporting classes,
attributes, and more.
▪ Introduced in modern browsers and supported in IE8 and later.
2. Element Selection:
o getElementById:
▪ Directly selects an element based on its unique ID.
▪ Returns a single element or null if not found.
o querySelector:
▪ Allows selection using any valid CSS selector.
▪ Returns the first matching element or null if not found.
3. Performance:
o getElementById:
▪ Generally faster when selecting elements by ID because it's a direct
lookup.
▪ Optimized for this specific use case.
o querySelector:
▪ May be slightly slower, especially for complex selectors, as it needs to
traverse the entire document.
4. Usage:
o getElementById:
▪ Ideal when working with elements that have unique IDs.
▪ Straightforward and efficient for selecting a single element by its ID.
o querySelector:
▪ Useful for more complex selections where other attributes or relationships
matter.
▪ Provides flexibility for selecting elements using various CSS selectors.
5. Multiple Matches:
o getElementById:
▪ Should only be used when expecting a single match, as IDs should be
unique.
o querySelector:
▪ Returns the first match, but if multiple elements match the selector, only
the first one encountered is returned.

In summary, getElementById is specialized for selecting elements by their unique IDs,


providing a simple and efficient way to access a specific element. On the other hand,
querySelector is more versatile, allowing for complex selections based on CSS selectors, but
may be slightly slower and should be used when the flexibility of CSS selectors is needed.

Real coding example:


<body>
<div id="myDiv">
<p class="myClass">This is a paragraph with class "myClass".</p>
</div>
<script>
let elementById = document.getElementById('myDiv');
elementById.style.backgroundColor = 'lightgray';
let elementByQuerySelector = document.querySelector('.myClass');
elementByQuerySelector.innerHTML += ' (Modified by querySelector)';
</script>
</body>
24. How can you change the content or attributes of an HTML element using
JavaScript?

You can change the content or attributes of an HTML element using JavaScript by accessing the
element in the Document Object Model (DOM) and then modifying its properties. Here are
common ways to achieve this:

Changing Content:

1. innerText or textContent:

• Use innerText or textContent properties to change the text content of an element.

const myElement = document.getElementById("myElement");


myElement.innerText = "New Text Content";
2. innerHTML:

• Use the innerHTML property to change the HTML content of an element.

const myElement = document.getElementById("myElement");


myElement.innerHTML = "<strong>New HTML Content</strong>";

Changing Attributes:

1. setAttribute:

• Use the setAttribute method to change or add an attribute to an element.

const myImage = document.getElementById("myImage");


// Change the "src" attribute
myImage.setAttribute("src", "new-image.jpg");
2. Direct Property Assignment:

• You can directly assign new values to certain properties like src, href, value, etc.

// Assuming an element with id "myLink" (an <a> element)


const myLink = document.getElementById("myLink");
// Change the "href" attribute
myLink.href = "https://www.example.com";

Example:

Consider an HTML element with the following structure:


<div id="myDiv">Original Content</div>

You can change the content and attributes using JavaScript as follows:

const myDiv = document.getElementById("myDiv");


myDiv.innerText = "New Content";
myDiv.innerHTML = "<strong>New HTML Content</strong>";
// Change the "class" attribute
myDiv.setAttribute("class", "newClass");

After executing this JavaScript code, the HTML will be modified to:

<div id="myDiv" class="newClass">New Content<strong>New HTML


Content</strong></div>

Keep in mind that manipulating the DOM directly can have performance implications, especially
if done frequently. If you're making multiple changes, consider using document fragments, and
always be mindful of potential security issues, such as cross-site scripting (XSS).

25. How do you make an AJAX request in JavaScript?

To make an AJAX (Asynchronous JavaScript and XML) request in JavaScript, you can use the
XMLHttpRequest object or the more modern fetch API. Here, I'll provide examples for both
methods:

Using XMLHttpRequest:
// Create a new XMLHttpRequest object
var xhr = new XMLHttpRequest();

// Configure it: specify the type of request and the URL


xhr.open('GET', 'https://api.example.com/data', true);

// Set up a callback function to handle the response


xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// The request is complete, and the response is successful
console.log(xhr.responseText);
}
};

// Send the request


xhr.send();

Using fetch:
// Make a GET request using the fetch API
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Assuming the response is in JSON format
})
.then(data => {
// Handle the data
console.log(data);
})
.catch(error => {
// Handle errors
console.error('Fetch error:', error);
});

Key points:

1. XMLHttpRequest:
o Create a new XMLHttpRequest object.
o Configure it using the open method, specifying the HTTP method (GET, POST,
etc.) and the URL.
o Set up a callback function using the onreadystatechange event to handle the
response when the state changes.
o Send the request using the send method.
2. fetch API:
o Use the fetch function, providing the URL as the first argument.
o fetch returns a Promise, and you can use then to handle the response.
o Check the response.ok property to ensure the response is successful.
o Use response.json() to parse the response as JSON, or response.text() for
plain text.
o Handle the data in the second then block.
o Use catch to handle errors.

The fetch API is more modern and provides a more straightforward and flexible interface for
making HTTP requests. It also supports Promises, making it easier to work with asynchronous
code. However, keep in mind that fetch might not be supported in older browsers, so you may
need to use a polyfill or stick with XMLHttpRequest in such cases.

Q1. What is JavaScript?

JavaScript is a lightweight, interpreted programming language with object-oriented


capabilities that allows you to build interactivity into otherwise static HTML pages. The
general-purpose core of the language has been embedded in Netscape, Internet
Explorer, and other web browsers.

Q2. What is the difference between Java & JavaScript?

Java JavaScript
Java is an OOP programming language. JavaScript is an OOP scripting language.
It creates applications that run in a virtual
The code is run on a browser only.
machine or browser.
Java code needs to be compiled. JavaScript code are all in the form of text.
Q3. What are the data types supported by JavaScript?

The data types supported by JavaScript are:

• Undefined
• Null
• Boolean
• String
• Symbol
• Number
• Object

Q4. What are the features of JavaScript?

Following are the features of JavaScript:


• It is a lightweight, interpreted programming language.
• It is designed for creating network-centric applications.
• It is complementary to and integrated with Java.
• It is an open and cross-platform scripting language.

Q5. Is JavaScript a case-sensitive language?

Yes, JavaScript is a case sensitive language. The language keywords, variables,


function names, and any other identifiers must always be typed with a consistent
capitalization of letters.

Q6. What are the advantages of JavaScript?

Following are the advantages of using JavaScript −

• Less server interaction − You can validate user input before sending the page
off to the server. This saves server traffic, which means less load on your server.
• Immediate feedback to the visitors − They don’t have to wait for a page reload
to see if they have forgotten to enter something.
• Increased interactivity − You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.
• Richer interfaces − You can use JavaScript to include such items as drag-and-
drop components and sliders to give a Rich Interface to your site visitors.

Check out Java Interview Questions to learn more about Java!

Q7. How can you create an object in JavaScript?

JavaScript supports Object concept very well. You can create an object using
the object literal as follows −
1 var emp = {
2 name: "Daniel",
3 age: 23
};
4
Q8. How can you create an Array in JavaScript?

You can define arrays using the array literal as follows-

1 var x = [];
2 var y = [1, 2, 3, 4, 5];
Q9. What is a name function in JavaScript & how to define it?

A named function declares a name as soon as it is defined. It can be defined


using function keyword as :

1 function named(){
2 // write code here
3 }
Q10. Can you assign an anonymous function to a variable and pass it as
an argument to another function?

Yes! An anonymous function can be assigned to a variable. It can also be passed as an


argument to another function.

If you wish to learn JavaScript and build your own applications, then check out our Web
developer course online which comes with instructor-led live training and real-life project
experience. Edureka’s Java Certification Course makes you proficient in skills to work
with back-end and front-end web technologies. It includes training on Web
Development, jQuery, Angular, NodeJS, ExpressJS and MongoDB.

Q11. What is argument objects in JavaScript & how to get the type of
arguments passed to a function?

JavaScript variable arguments represents the arguments that are passed to a


function. Using type of operator, we can get the type of arguments passed to a
function. For example −

1 function func(x){
2 console.log(typeof x, arguments.length);
3 }
4 func(); //==> "undefined", 0
func(7); //==> "number", 1
5
func("1", "2", "3"); //==> "string", 3
6
Q12. What are the scopes of a variable in JavaScript?
The scope of a variable is the region of your program in which it is defined. JavaScript
variable will have only two scopes.
• Global Variables − A global variable has global scope which means it is visible
everywhere in your JavaScript code.
• Local Variables − A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.

Q13. What is the purpose of ‘This’ operator in JavaScript?

The JavaScript this keyword refers to the object it belongs to. This has different values
depending on where it is used. In a method, this refers to the owner object and in a
function, this refers to the global object.

Q14. What is Callback?

A callback is a plain JavaScript function passed to some method as an argument or


option. It is a function that is to be executed after another function has finished
executing, hence the name ‘call back‘. In JavaScript, functions are objects. Because of
this, functions can take functions as arguments, and can be returned by other functions.

Q15. What is Closure? Give an example.

Closures are created whenever a variable that is defined outside the current scope is
accessed from within some inner scope. It gives you access to an outer function’s
scope from an inner function. In JavaScript, closures are created every time a function
is created. To use a closure, simply define a function inside another function and
expose it.

Q16. Name some of the built-in methods and the values returned by
them.

Built-in Method Values


CharAt() It returns the character at the specified index.
Concat() It joins two or more strings.
forEach() It calls a function for each element in the
array.
It returns the index within the calling String
indexOf() object of the first occurrence of the specified
value.
length() It returns the length of the string.
It removes the last element from an array and
pop()
returns that element.
It adds one or more elements to the end of an
push()
array and returns the new length of the array.
It reverses the order of the elements of an
reverse()
array.

Q17. What are the variable naming conventions in JavaScript?

The following rules are to be followed while naming variables in JavaScript:

1. You should not use any of the JavaScript reserved keyword as variable name.
For example, break or boolean variable names are not valid.
2. JavaScript variable names should not start with a numeral (0-9). They must
begin with a letter or the underscore character. For example, 123name is an
invalid variable name but _123name or name123 is a valid one.
3. JavaScript variable names are case sensitive. For example, Test and test are
two different variables.

Q18. How does Type Of Operator work?

The type of operator is used to get the data type of its operand. The operand can be
either a literal or a data structure such as a variable, a function, or an object. It is
a unary operator that is placed before its single operand, which can be of any type. Its
value is a string indicating the data type of the operand.

Q19. How to create a cookie using JavaScript?

The simplest way to create a cookie is to assign a string value to


the document.cookie object, which looks like this-

Syntax :

1 document.cookie = "key1 = value1; key2 = value2; expires = date";


Q20. How to read a cookie using JavaScript?
Reading a cookie is just as simple as writing one, because the value of the
document.cookie object is the cookie. So you can use this string whenever you want to
access the cookie.

• The document.cookie string will keep a list of name = value pairs separated by
semicolons, where name is the name of a cookie and value is its string value.
• You can use strings’ split() function to break the string into key and values.

Q21. How to delete a cookie using JavaScript?

If you want to delete a cookie so that subsequent attempts to read the cookie in
JavaScript return nothing, you just need to set the expiration date to a time in the past.
You should define the cookie path to ensure that you delete the right cookie. Some
browsers will not let you delete a cookie if you don’t specify the path.

Q22. Explain call(), apply() and, bind() methods.

In JavaScript, the `call()`, `apply()`, and `bind()` methods are used to manipulate the
execution context and binding of functions. They provide ways to explicitly set the value
of `this` within a function and pass arguments to the function.

1. `call()`: The `call()` method allows you to invoke a function with a specified `this`
value and individual arguments passed in as separate parameters. It takes the
context object as the first argument, followed by the function arguments.

“`javascript

function greet(name) {

console.log(`Hello, ${name}! My name is ${this.name}.`);

const person = {

name: ‘John’

};

greet.call(person, ‘Alice’);

// Output: Hello, Alice! My name is John.

“`
In this example, `call()` is used to invoke the `greet()` function with the `person` object
as the execution context and the argument `’Alice’`.

2. `apply()`: The `apply()` method is similar to `call()`, but it accepts arguments as


an array or an array-like object. It also allows you to set the `this` value explicitly.

“`javascript

function greet(name, age) {

console.log(`Hello, ${name}! I am ${age} years old.`);

console.log(`My name is ${this.name}.`);

const person = {

name: ‘John’

};

greet.apply(person, [‘Alice’, 25]);

// Output: Hello, Alice! I am 25 years old.

// My name is John.

“`

In this example, `apply()` is used to invoke the `greet()` function with the `person` object as the
execution context and an array `[‘Alice’, 25]` as the arguments.

3. `bind()`: The `bind()` method creates a new function that has a specified `this` value and,
optionally, pre-defined arguments. It allows you to create a function with a fixed
execution context that can be called later.

“`javascript

function greet() {

console.log(`Hello, ${this.name}!`);

}
const person = {

name: ‘John’

};

const greetPerson = greet.bind(person);

greetPerson();

// Output: Hello, John!

“`

In this example, `bind()` is used to create a new function `greetPerson` with the `person` object
as the fixed execution context. When `greetPerson()` is called, it prints `”Hello, John!”`.

The key difference between `call()`, `apply()`, and `bind()` lies in how they handle function
invocation and argument passing. While `call()` and `apply()` immediately invoke the function,
`bind()` creates a new function with the desired execution context but doesn’t invoke it right
away.

These methods provide flexibility in manipulating function execution and context, enabling the
creation of reusable functions and control over `this` binding in JavaScript.

Q23. Explain Hoisting in javascript.

Hoisting is a behavior in JavaScript where variable and function declarations are moved to the
top of their respective scopes during the compilation phase, before the actual code execution
takes place. This means that you can use variables and functions before they are declared in your
code.

However, it is important to note that only the declarations are hoisted, not the initializations or
assignments. So, while the declarations are moved to the top, any assignments or initializations
remain in their original place.

In the case of variable hoisting, when a variable is declared using the `var` keyword, its
declaration is hoisted to the top of its scope. This means you can use the variable before it is
explicitly declared in the code. However, if you try to access the value of the variable before it is
assigned, it will return `undefined`.

For example:
“`javascript

console.log(myVariable); // Output: undefined

var myVariable = 10;

console.log(myVariable); // Output: 10

“`

In the above example, even though `myVariable` is accessed before its declaration, it doesn’t
throw an error. However, the initial value is `undefined` until it is assigned the value of `10`.

Function declarations are also hoisted in JavaScript. This means you can call a function before it
is defined in the code. For example:

“`javascript

myFunction(); // Output: “Hello, World!”

function myFunction() {

console.log(“Hello, World!”);

“`

In this case, the function declaration is hoisted to the top, so we can call `myFunction()` before
its actual declaration.

It’s important to understand hoisting in JavaScript to avoid unexpected behavior and to write
clean and maintainable code. It is recommended to declare variables and functions at the
beginning of their respective scopes to make your code more readable and prevent potential
issues related to hoisting.

Q24. What is the difference between exec () and test () methods in javascript?
The `exec()` and `test()` methods are both used in JavaScript for working with regular
expressions, but they serve different purposes.

1. `exec()` method: The `exec()` method is a regular expression method that searches a
specified string for a match and returns an array containing information about the match
or `null` if no match is found. It returns an array where the first element is the matched
substring, and subsequent elements provide additional information such as captured
groups, index, and input string.

“`javascript

const regex = /hello (w+)/;

const str = ‘hello world’;

const result = regex.exec(str);

console.log(result);

// Output: [“hello world”, “world”, index: 0, input: “hello world”, groups: undefined]

Q25. What is the difference between the var and let keywords in javascript?

The var and let keywords are both used to declare variables in JavaScript, but they have some
key differences.

Scope

The main difference between var and let is the scope of the variables they create. Variables
declared with var have function scope, which means they are accessible throughout the function
in which they are declared. Variables declared with let have block scope, which means they are
only accessible within the block where they are declared.

For example, the following code will print the value of x twice, even though the second x is
declared inside a block:

JavaScript

var x = 10;
{

var x = 20;

console.log(x); // 20

console.log(x); // 10

If we change the var keyword to let, the second x will not be accessible outside the block:

JavaScript

let x = 10;

let x = 20;

console.log(x); // 20

console.log(x); // ReferenceError: x is not defined

Hoisting

Another difference between var and let is that var declarations are hoisted, while let declarations
are not. Hoisting means that the declaration of a variable is moved to the top of the scope in
which it is declared, even though it is not actually executed until later.

For example, the following code will print the value of x even though the x declaration is not
actually executed until the console.log() statement:

JavaScript

var x;

console.log(x); // undefined

x = 10;
If we change the var keyword to let, the console.log() statement will throw an error because x is
not defined yet:

JavaScript

let x;

console.log(x); // ReferenceError: x is not defined

x = 10;

Redeclaration

Finally, var declarations can be redeclared, while let declarations cannot. This means that you
can declare a variable with the same name twice in the same scope with var, but you will get an
error if you try to do the same with let.

Java Certification Training Course

Weekday / Weekend BatchesSee Batch Details

For example, the following code will not cause an error:

JavaScript

var x = 10;

x = 20;

console.log(x); // 20

However, the following code will cause an error:


JavaScript

let x = 10;

x = 20;

console.log(x); // ReferenceError: x is not defined

The var and let keywords are both used to declare variables in JavaScript, but they have some
key differences in terms of scope, hoisting, and redeclaration. In general, it is recommended to
use let instead of var, as it provides more predictable and reliable behavior.

Q28. What is the difference between Attributes and Property?

Attributes- provide more details on an element like id, type, value etc.

Property- is the value assigned to the property like type=”text”, value=’Name’ etc.

Q29. List out the different ways an HTML element can be accessed in a
JavaScript code.

Here are the list of ways an HTML element can be accessed in a Javascript code:
(i) getElementById(‘idname’): Gets an element by its ID name
(ii) getElementsByClass(‘classname’): Gets all the elements that have the given
classname.
(iii) getElementsByTagName(‘tagname’): Gets all the elements that have the given
tag name.
(iv) querySelector(): This function takes css style selector and returns the first selected
element.

Q30. In how many ways a JavaScript code can be involved in an HTML


file?

There are 3 different ways in which a JavaScript code can be involved in an HTML file:

• Inline
• Internal
• External

An inline function is a JavaScript function, which is assigned to a variable created at


runtime. You can differentiate between Inline Functions and Anonymous since an inline
function is assigned to a variable and can be easily reused. When you need a
JavaScript for a function, you can either have the script integrated in the page you are
working on, or you can have it placed in a separate file that you call, when needed. This
is the difference between an internal script and an external script.
Q31. Explain Higher Order Functions in javascript.

Higher-order functions in JavaScript are functions that can take other functions as
inputs or return functions as their outputs. They make it possible to use strong functional
programming methods that make code more flexible, reused, and expressive. By
treating functions as first-class citizens, they make it possible to abstract behaviour and
make flexible code structures.

Q32. What are the ways to define a variable in JavaScript?

The three possible ways of defining a variable in JavaScript are:

• Var – The JavaScript variables statement is used to declare a variable and,


optionally, we can initialize the value of that variable. Example: var a =10;
Variable declarations are processed before the execution of the code.
• Const – The idea of const functions is not allow them to modify the object on
which they are called. When a function is declared as const, it can be called on
any type of object.
• Let – It is a signal that the variable may be reassigned, such as a counter in a
loop, or a value swap in an algorithm. It also signals that the variable will be used
only in the block it’s defined in.

Q33. What is a Typed language?

Typed Language is in which the values are associated with values and not
with variables. It is of two types:

• Dynamically: in this, the variable can hold multiple types; like in JS a variable
can take number, chars.
• Statically: in this, the variable can hold only one type, like in Java a variable
declared of string can take only set of characters and nothing else.
o

Q34. What is the difference between Local storage & Session storage?
Local Storage – The data is not sent back to the server for every HTTP request
(HTML, images, JavaScript, CSS, etc) – reducing the amount of traffic between client
and server. It will stay until it is manually cleared through settings or program.

Session Storage – It is similar to local storage; the only difference is while data stored
in local storage has no expiration time, data stored in session storage gets cleared
when the page session ends. Session Storage will leave when the browser is closed.

Q35. What is the difference between the operators ‘==‘ & ‘===‘?

The main difference between “==” and “===” operator is that formerly compares variable
by making type correction e.g. if you compare a number with a string with numeric
literal, == allows that, but === doesn’t allow that, because it not only checks the value
but also type of two variable, if two variables are not of the same type “===” return false,
while “==” return true.

Q36. What is currying in JavaScript?

Currying is a functional programming method in JavaScript that turns a function with


many arguments into a series of functions that each take one argument. It lets you only
use some of the inputs, so you can make functions that can be used more than once
and are specialised.

Q37. What is the difference between null & undefined?

Undefined means a variable has been declared but has not yet been assigned a value.
On the other hand, null is an assignment value. It can be assigned to a variable as a
representation of no value. Also, undefined and null are two distinct types: undefined is
a type itself (undefined) while null is an object.

Q38. What is the difference between undeclared & undefined?

Undeclared variables are those that do not exist in a program and are not declared. If
the program tries to read the value of an undeclared variable, then a runtime error is
encountered. Undefined variables are those that are declared in the program but have
not been given any value. If the program tries to read the value of an undefined
variable, an undefined value is returned.

Q39. Name some of the JavaScript Frameworks


A JavaScript
framework is an application framework written in JavaScript. It differs from a JavaScript
library in its control flow. There are many JavaScript Frameworks available but some of
the most commonly used frameworks are:

• Angular
• React
• Vue

Q40. What is the difference between window & document in JavaScript?

Window Document
The document also comes under the window
JavaScript window is a global object which
and can be considered as the property of the
holds variables, functions, history, location.
window.

Q41. What is the difference between innerHTML & innerText?

innerHTML – It will process an HTML tag if found in a string

innerText – It will not process an HTML tag if found in a string

Q42. What is an event bubbling in JavaScript?

Event bubbling is a way of event propagation in the HTML DOM API, when an event
occurs in an element inside another element, and both elements have registered a
handle for that event. With bubbling, the event is first captured and handled by
the innermost element and then propagated to outer elements. The execution starts
from that event and goes to its parent element. Then the execution passes to its parent
element and so on till the body element.

Q43. What is NaN in JavaScript?

NaN is a short form of Not a Number. Since NaN always compares unequal to any
number, including NaN, it is usually used to indicate an error condition for a function that
should return a valid number. When a string or something else is being converted into
a number and that cannot be done, then we get to see NaN.

Q44. How do JavaScript primitive/object types passed in functions?

One of the differences between the two is that Primitive Data Types are passed By
Value and Objects are passed By Reference.

• By Value means creating a COPY of the original. Picture it like twins: they are
born exactly the same, but the first twin doesn’t lose a leg when the second twin
loses his in the war.
• By Reference means creating an ALIAS to the original. When your Mom calls
you “Pumpkin Pie” although your name is Margaret, this doesn’t suddenly give
birth to a clone of yourself: you are still one, but you can be called by these two
very different names.

Q45. How can you convert the string of any base to integer in
JavaScript?

The parseInt() function is used to convert numbers between different bases. It takes the
string to be converted as its first parameter, and the second parameter is the base of
the given string.

For example-

1 parseInt("4F", 16)
Q46. What would be the result of 2+5+”3″?

Since 2 and 5 are integers, they will be added numerically. And since 3 is a string, its
concatenation will be done. So the result would be 73. The ” ” makes all the difference
here and represents 3 as a string and not a number.

Q47. What are Exports & Imports?

Imports and exports help us to write modular JavaScript code. Using Imports and
exports we can split our code into multiple files. For example-
1
2 //------ lib.js ------</span>
3 export const sqrt = Math.sqrt;</span>
export function square(x) {</span>
4 return x * x;</span>
5 }
6 export function diag(x, y) {
7 return sqrt(square(x) + square(y));
}
8
9 //------ main.js ------</span>
10 { square, diag } from 'lib';
11 console.log(square(5)); // 25
12 console.log(diag(4, 3)); // 5
13
Now with this, we have reached the final section of JS Interview Questions.

Q48. What is the ‘Strict’ mode in JavaScript and how can it be enabled?

Strict mode is a way to introduce better error-checking into your code.

• When you use strict mode, you cannot use implicitly declared variables, or assign
a value to a read-only property, or add a property to an object that is not
extensible.
• You can enable strict mode by adding “use strict” at the beginning of a file, a
program, or a function.

Q49. What is a prompt box 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. A prompt box is
often used if you want the user to input a value before entering a page. When a prompt
box pops up, the user will have to click either “OK” or “Cancel” to proceed after entering
an input value.

Q50. What will be the output of the code below?

1 var Y = 1;
2 if (function F(){})
3 {
4 y += Typeof F;</span>
}
5 console.log(y);
6
The output would be 1undefined. The if condition statement evaluates using eval, so
eval(function f(){}) returns function f(){} (which is true). Therefore, inside the if statement,
executing typeof f returns undefined because the if statement code executes at run
time, and the statement inside the if condition is evaluated during run time.
Q51. What is the difference between Call & Apply?

The call() method calls a function with a given this value and arguments provided
individually.

Syntax-

1 fun.call(thisArg[, arg1[, arg2[, ...]]])


The apply() method calls a function with a given this value, and arguments provided as
an array.

Syntax-

1 fun.apply(thisArg, [argsArray])
Q52. How to empty an Array in JavaScript?

There are a number of methods you can use to empty an array:

Method 1 –

1 arrayList = []
Above code will set the variable arrayList to a new empty array. This is recommended if
you don’t have references to the original array arrayList anywhere else, because it will
actually create a new, empty array. You should be careful with this method of emptying
the array, because if you have referenced this array from another variable, then the
original reference array will remain unchanged.

Method 2 –

1 arrayList.length = 0;
The code above will clear the existing array by setting its length to 0. This way of
emptying the array also updates all the reference variables that point to the original
array. Therefore, this method is useful when you want to update all reference variables
pointing to arrayList.

Method 3 –

1 arrayList.splice(0, arrayList.length);
The implementation above will also work perfectly. This way of emptying the array will
also update all the references to the original array.

Method 4 –
1 while(arrayList.length)
2 {
3 arrayList.pop();
}
4
The implementation above can also empty arrays, but it is usually not recommended to
use this method often.

Q53. What will be the output of the following code?

1 var Output = (function(x)


2 {
3 Delete X;
4 return X;
5 }
)(0);
6 console.log(output);
7
The output would be 0. The delete operator is used to delete properties from an object.
Here x is not an object but a local variable. delete operators don’t affect local variables.

Q54. What do you mean by Self Invoking Functions?

Self-invoking functions, also known as immediately invoked function expressions (IIFE),


are functions in JavaScript that are executed immediately after they are defined, without
requiring an explicit function call.

The syntax for creating a self-invoking function is to enclose the function declaration or
expression within parentheses and immediately invoke it using parentheses or other
operators.

Here’s an example of a self-invoking function:

“`javascript

(function() {

// Function body

})();

“`

In this example, the function is defined inside parentheses `(function() { … })`. The
trailing parentheses `()` immediately invoke the function. The function is executed once
and then discarded, as it doesn’t have a reference to be called again.
Self-invoking functions are commonly used to create a separate scope for variables,
functions, or modules, preventing pollution of the global namespace. By encapsulating
code within a self-invoking function, you can declare variables without the risk of them
conflicting with other variables in the global scope.

Here’s an example demonstrating the use of a self-invoking function to create a private


variable:

“`javascript

(function() {

var privateVariable = ‘This is private’;

// Other code within the function

})();

“`

In this case, the variable `privateVariable` is only accessible within the scope of the self-
invoking function and cannot be accessed or modified from outside.

Self-invoking functions can also be used to execute code immediately and provide a
way to return values or assign the result to a variable:

“`javascript

var result = (function() {

// Code logic

return someValue;

})();

“`
In this example, the result of the self-invoking function is assigned to the `result`
variable. This allows you to perform calculations, initialize variables, or execute code
right away while maintaining a clean separation of scope.

Self-invoking functions offer a useful technique for creating isolated scopes and
executing code immediately without cluttering the global scope. They are commonly
used in modular patterns and for avoiding naming collisions or leaking variables.

Q55. What will be the output of the following code?

1
var X = { Foo : 1};
2 var Output = (function()
3 {
4 delete X.foo;
5 return X.foo;
}
6 )();
7 console.log(output);
8
The output would be undefined. The delete operator is used to delete the property of an
object. Here, x is an object which has the property foo, and as it is a self-invoking
function, we will delete the foo property from object x. After doing so, when we try to
reference a deleted property foo, the result is undefined.

Q56. What will be the output of the following code?

1 var Employee =
2 {
3 company: 'xyz'
4 }
var Emp1 = Object.create(employee);
5 delete Emp1.company Console.log(emp1.company);
6
The output would be xyz. Here, emp1 object has company as its prototype property.
The delete operator doesn’t delete prototype property. emp1 object doesn’t have
company as its own property. However, we can delete the company property directly
from the Employee object using delete Employee.company.

Q57. What will be the output of the code below?

1 //nfe (named function expression)


2 var Foo = Function Bar()
3 {
4 return 7;
};
5 typeof Bar();
6
The output would be Reference Error. A function definition can have only one reference
variable as its function name.

You might also like