javascript
javascript
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 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.
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:
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:
Variables declared with var are function-scoped, and they are hoisted to the top of their
scope during execution.
Variables declared with let are block-scoped, which means they are only accessible within the
block (enclosed by curly braces) where they are defined.
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.
• Boolean: Represents either true or false, and is often used for logical operations.
• Undefined: Represents a variable that has been declared but not assigned a value.
let undefinedVar;
• Symbol (ES6 and later): Represents a unique identifier and is often used as an identifier for
object properties.
• 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.
function addNumbers(a, b) {
return a + b;
}
These data types provide the building blocks for writing JavaScript programs. It's important to
note that JavaScript is a dynamically-typed language
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.
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.
You can use console.log() to log the values of variables. This is particularly helpful for
checking the current state of variables during runtime.
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.
Here:
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.
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
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:
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.
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
}
In this example:
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:
Here's an example that uses the ternary operator to determine if a person is eligible to vote:
In this example:
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.
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
}
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:
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;
• 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.
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.
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.
javascript
let i = 0;
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.
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.
if (conditionToSkipRestOfCode) {
continue;
}
Here's a simple example using continue in a for loop to skip printing even numbers:
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.
In this syntax:
javascript
function greet(name = "Guest", greeting = "Hello") {
console.log(`${greeting}, ${name}!`);
}
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.
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:
Example:
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("John");
Function Expression:
Example:
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:
function doSomethingAsync(callback) {
setTimeout(function() {
console.log("Task is done!");
callback();
}, 1000);
}
function afterTask() {
console.log("Callback function executed.");
}
In this example,
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:
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:
function exampleFunction() {
console.log(globalVariable); // Accessible inside the function
}
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
}
// 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:
Example:
function outerFunction() {
let outerVariable = "I'm from the outer function";
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
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:
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:
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:
Array Structure:
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.
2. Length:
4. Dynamic Size:
• JavaScript arrays are dynamic, meaning you can add or remove elements at any time.
5. Iteration:
• Arrays can be iterated using loops or array methods like forEach, map, filter, and
others.
// 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.
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:
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
22. Explain how to add and remove elements from an array. Describe the purpose
of the forEach() method for arrays.
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.
The unshift() method adds one or more elements to the beginning of an array and returns the
new length of the array.
The splice() method can be used to add elements at a specific position in the array. It also
allows for the removal of elements.
1. pop() Method:
The pop() method removes the last element from an array and returns that element.
The shift() method removes the first element from an array and returns that element.
The splice() method can be used to remove elements at a specific position in the array.
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.
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.
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:
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:
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.
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:
Changing Attributes:
1. setAttribute:
• You can directly assign new values to certain properties like src, href, value, etc.
Example:
You can change the content and attributes using JavaScript as follows:
After executing this JavaScript code, the HTML will be modified to:
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).
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();
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.
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?
• Undefined
• Null
• Boolean
• String
• Symbol
• Number
• Object
• 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.
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?
1 var x = [];
2 var y = [1, 2, 3, 4, 5];
Q9. What is a name function in JavaScript & how to define it?
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?
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?
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.
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.
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.
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.
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.
Syntax :
• 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.
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.
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) {
const person = {
name: ‘John’
};
greet.call(person, ‘Alice’);
“`
In this example, `call()` is used to invoke the `greet()` function with the `person` object
as the execution context and the argument `’Alice’`.
“`javascript
const person = {
name: ‘John’
};
// 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’
};
greetPerson();
“`
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.
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: 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
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
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
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;
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.
JavaScript
var x = 10;
x = 20;
console.log(x); // 20
let x = 10;
x = 20;
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.
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.
There are 3 different ways in which a JavaScript code can be involved in an HTML file:
• Inline
• Internal
• External
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.
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.
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.
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.
• Angular
• React
• Vue
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.
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.
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.
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.
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?
• 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.
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.
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-
Syntax-
1 fun.apply(thisArg, [argsArray])
Q52. How to empty an Array in JavaScript?
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.
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.
“`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.
“`javascript
(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
// 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.
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.
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.