You are on page 1of 7

Javascript Questions

Contents
1. What the difference between var, let and const ?...........................................................................1
2. How to get the title of HTML page with JavaScript?........................................................................2
3. What the difference between switch and else if condition in Javascript ?.......................................2
4. What is arrow functions in js ?.........................................................................................................2
5. What the purpose of queryselector in js ?.......................................................................................2
6. Simple way to write if else logic in js using ternary operator ?........................................................2
7. What is Null coalescing(??) ?...........................................................................................................2
8. What is the difference between ‘== ‘ and ‘===’ in JavaScript?........................................................3
9. How to handle errors in Js ?.............................................................................................................3
10. What are Promises in JavaScript? How do they work?................................................................3
11. What is the purpose of the map() function in JavaScript?...........................................................4
12. How does setTimeout() function work in JavaScript?..................................................................4
13. How does the localStorage object work in JavaScript? How is it different from sessionStorage? 4
14. How to set item and get item from local storage ?......................................................................4
15. What is the purpose of the this keyword in JavaScript? How does its value get determined?....5
16. what is closest in js ?....................................................................................................................5
17. How do u convert string to int or float in js ?...............................................................................5
18. How to u check if an element present in array ?..........................................................................5
19. How to use JSON.stringify and JSON.parse in JS ?........................................................................6
20. What the difference between replace and replaceAll in JS ?.......................................................6
21. How to add element in array at first position ?............................................................................6
22. How do you convert a number to a string in JavaScript?.............................................................6
23. How do you get hostname of a website ?....................................................................................6
24. What is optional chaining (?.) ?....................................................................................................6
25. What is a Regular Expression.......................................................................................................6
1. What the difference between var, let and const ?
var has function scope, let has block scope, and const is used for variables that are not intended to be
reassigned.

Var ===function scope + can be re assigned and redeclare +gives you undefined when u access
before declaration

let ==block scope +can be reassigned but cant be redeclare +gives reference error

Const ==block scope +cant do both+gives reference error

2. How to get the title of HTML page with JavaScript?


Document.title is used to get the HTML page title.

3. What the difference between switch and else if condition in Javascript ?


The switch statement is useful when you have a single expression with multiple possible values to
compare, while the else if statement is suitable for handling multiple conditions sequentially.

the switch statement has been known to have better performance in cases where there are a larger
number of cases to check. This is because the switch statement typically uses direct value comparison,
which can be optimized by JavaScript engines for efficient execution.

Cause switch uses jump table (a data structure) and stores addresses of code.

4. What is arrow functions in js ?


Arrow functions, also known as fat arrow functions( => ), are a shorthand syntax for writing functions in
JavaScript.

Easy way to write js function we use arrow function using fat arrow operator

Example const square=(x,y)=>x*y;

Have lecical this binding.

5. What the purpose of queryselector in js ?


The querySelector method in JavaScript is used to select and retrieve the first element that matches a
specified CSS selector from the document or a specific element. It allows you to interact with and
manipulate individual elements in the HTML DOM (Document Object Model).Will return null if not
present .

Const head1=document .querySelctor(“h1”);gives very first elemnt which matches this selctor
6. Simple way to write if else logic in js using ternary operator ?
The ternary operator provides a concise way to write an if...else statement with a single expression.

It has the following syntax: condition ? expression1 : expression2.

If the condition is true, expression1 is evaluated and returned; otherwise, expression2 is evaluated and
returned.

7. What is Null coalescing(??) ?


Null coalescing is a feature introduced in JavaScript to provide a concise way of handling nullish values
(null or undefined) by providing a default value. The nullish coalescing operator (??) is used for this
purpose.

const name = null;


const defaultName = "John Doe";
const result = name ?? defaultName;
console.log(result); // Output: "John Doe"

8. What is the difference between ‘== ‘ and ‘===’ in JavaScript?


In JavaScript, the == (loose equality) and === (strict equality) operators are used to compare values for
equality. However, they have some important differences in how they perform the comparison:

Loose Equality (==):

The == operator compares the values for equality after performing type coercion if necessary.

1 == '1' would evaluate to true because the string '1' is coerced into the number 1 before comparison.

Strict Equality (===):

The === operator compares the values for equality without performing any type coercion.

1 === '1' would evaluate to false because the number 1 and the string '1' are of different types.

9. How to handle errors in Js ?


Try...Catch:

 The try...catch statement is used to catch and handle exceptions that occur within a specific
block of code.
 The try block contains the code that might generate an error.
 If an error occurs within the try block, the catch block is executed, allowing you to handle the
error.

try {
// Code that might throw an error
} catch (error) {
// Handle the error
}

10. What are Promises in JavaScript? How do they work?pending resolved rejected
Promises in JavaScript are used to handle asynchronous operations by representing the eventual
completion or failure of an operation, allowing for more organized and manageable asynchronous code

-Example:

const myPromise = new Promise((resolve, reject) => {


// Asynchronous operation
// If successful, call resolve(value)
// If failed, call reject(error)
});
myPromise
.then((value) => {
// Handle fulfillment
})
.catch((error) => {
// Handle rejection
})
.finally(() => {
// Cleanup or finalization
});

11. What is the purpose of the map() function in JavaScript?


The map() function in JavaScript is a higher-order function that is used to transform elements of an array.
It iterates over each element of an array, applies a provided callback function to each element, and
returns a new array containing the results of the callback function.

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


const doubledNumbers = numbers.map((number) => number * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
12. How does setTimeout() function work in JavaScript?
The setTimeout() function in JavaScript is used to schedule the execution of a function or the evaluation
of an expression after a specified delay. It allows you to introduce a time delay in your code.

const timeoutId = setTimeout(callback, delay);


clearTimeout(timeoutId);

13. How does the localStorage object work in JavaScript? How is it different from
sessionStorage?
localStorage allows data to be stored persistently in the browser, while sessionStorage stores data for the
duration of a session or browsing context.

14. How to set item and get item from local storage ?
To set item

localStorage.setItem("key", "value");

to get item

const value = localStorage.getItem("key");

15. What is the purpose of the this keyword in JavaScript? How does its value get
determined?
The `this` keyword in JavaScript is used to refer to the current execution context or the object on which a
method is invoked, and its value is determined dynamically at runtime based on the function invocation.

16. what is closest in js ?


The `closest()` method in JavaScript is used to find the closest ancestor element that matches a specified
selector.

const element = document.querySelector('.my-element');


const closestParent = element.closest('.parent-class');

17. How do u convert string to int or float in js ?


parseInt(): Parses a string and returns an integer.

const str = "42";


const number = parseInt(str);

parseFloat(): Parses a string and returns a floating-point number.


const str = "3.14";
const number = parseFloat(str);

18. How to u check if an element present in array ?


We can use two diffrenet methods ‘includes’ and ‘indexOf’

Using includes:

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


const element = 3;

if (array.includes(element)) {
console.log("Element is present in the array.");
} else {
console.log("Element is not present in the array.");
}

using indexOf :

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


const element = 3;

if (array.indexOf(element) !== -1) {


console.log("Element is present in the array.");
} else {
console.log("Element is not present in the array.");
}

19. How to use JSON.stringify and JSON.parse in JS ?


To convert object in to JSON we use JSON.stringify

To convert back JSON to js object we use JSON.parse.

20. What the difference between replace and replaceAll in JS ?


replaceAll() replaces all occurrences of search with replaceWith ,

while replace() replaces only the first occurence.

21. How to add element in array at first position ?


We can use unshift to add element in the beginning
var a = [23, 45, 12, 67];
a.unshift(34);
console.log(a); // [34, 23, 45, 12, 67]

22. How do you convert a number to a string in JavaScript?


JavaScript Number toString() method in Javascript is used with a number and converts the number to a
string.

23. How do you get hostname of a website ?


We use window.location.hostname to get host name of the website.

24. What is optional chaining (?.) ?


The optional chaining ?. is a safe way to access nested object properties, even if an intermediate
property doesn’t exist.

While dealing with nested object or function which may be null or defined optional chaining bcomes

Handy it return undefined if value id null or undfined otherwise without optional chianin it will show
error handy

Example

let user = null;

console.log(user.address) // throws error because null does not have address object

console.log( user?.address ) // undefined because user is null so it will break at user and returns
undefined;

25. What is a Regular Expression


A regular expression is a sequence of characters that forms a search pattern. You can use this search
pattern for searching data in a text. These can be used to perform all types of text search and text
replace operations. Let's see the syntax format now,

N* or or more character s like n

[0-9] search in the range 0 to 9 smilarly

You might also like