0% found this document useful (0 votes)
4 views16 pages

Fundamentals of JavaScript_document

The document provides a comprehensive overview of JavaScript, covering its definition, basic data types, functions, and key concepts such as hoisting, closures, and asynchronous programming. It also discusses various methods for manipulating the DOM, creating objects and arrays, handling errors, and using cookies. Additionally, it explains the differences between synchronous and asynchronous programming, variable typing, and offers insights into performance optimization techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views16 pages

Fundamentals of JavaScript_document

The document provides a comprehensive overview of JavaScript, covering its definition, basic data types, functions, and key concepts such as hoisting, closures, and asynchronous programming. It also discusses various methods for manipulating the DOM, creating objects and arrays, handling errors, and using cookies. Additionally, it explains the differences between synchronous and asynchronous programming, variable typing, and offers insights into performance optimization techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

1. What is JavaScript?

Answer:

JavaScript is a high-level, interpreted programming language primarily used for creating interactive
effects within web browsers. It is often used alongside HTML and CSS to build dynamic web
pages and web applications.

2. What are the basic data types in JavaScript?

Answer:

JavaScript has primitive data types like string, number, boolean, null, undefined, and symbol
(added in ES6), along with the complex data type object.

3. What is the difference between == and === in JavaScript?

Answer:

== is the equality operator, which checks for equality after type coercion, while === is the strict
equality operator, which checks for equality without type coercion.

4. What are functions in JavaScript?Answer: How do you define and call them?

Answer:

Functions in JavaScript are blocks of code that perform a specific task. They are defined using the
function keyword, followed by the function name and parameters (if any).

function sayHello( name)

return ‘hi’ + name; }

console.log(sayHello(‘AjayReddy’));

5. How do you comment in JavaScript?

Answer:

In JavaScript, single-line comments start with //, and multi-line comments are enclosed between /*
and */.

6. What is the difference between let, const, and var?

Answer:

var is function-scoped, let and const are block-scoped. Variables declared with const cannot be
reassigned, while variables declared with let can be reassigned. Additionally, const requires
initialization during declaration.

7. What is the purpose of console.log () in JavaScript?

Answer:

console.log () is used to print messages to the console for debugging purposes. It helps developers
inspect values, track the flow of execution, and identify errors in their code.
8. What are the different ways to create objects in JavaScript?

Answer:

Objects can be created using object literals, the new keyword, constructor functions, or with
Object.create() method.

9. What is the purpose of this keyword in JavaScript?

Answer:

this refers to the object to which a method belongs or the context in which a function is called. Its
value is determined at runtime.

10. Explain the difference between null and undefined in JavaScript.

Answer:

null represents the intentional absence of any object value, while undefined represents the absence
of a value or uninitialized variable.

11. What are the arrow functions in JavaScript?

Answer:

Arrow functions are a short and concise way of writing functions in JavaScript. The general syntax
of an arrow function is as below:

const helloWorld = () => {

console.log("hello world!");

};

12. What is Hoisting in javascript?

Answer:

Hoisting in javascript is the default process behavior of moving declaration of all the variables and
functions on top of the scope where scope can be either local or global.

hoistedFunction(); //declared as function even after it is called

function hoistedFunction( ){

console.log(" Hi There! ");

13. What is NaN property in JavaScript?

Answer:

NaN property in JavaScript is the “Not-a-Number” value that is not a legal number.
14. Define REST parameter in JavaScript.

Answer:

Rest parameter is used to declare the function with improved handling of parameters. Rest
parameter syntax can be used to create functions to perform functions on the variable number of
arguments. It also helps to convert any number of arguments into an array as well as helps in
extracting some or all parts of the arguments.

15. Define Spread Parameter in JavaScript.

Answer:

In a function call, we use the spread operator. It's also to spread one or more arguments that are
expected in a function call.The spread operator is used to take an array or an object and spread
them.

16. What is Object Destructuring?

Answer:

Object destructuring is a method to extract elements from an array or an object.const arr = [1, 2,
3];

const [first,second,third,fourth] = arr;

console.log(first); // Outputs 1

console.log(second); // Outputs 2

console.log(third); // Outputs 3

17. What is Async/Await ?

Answer:

Async-await functions are executed sequentially one after another in an easier way.

18. What is DOM?

Answer:

DOM stands for Document Object Model. DOM is a programming interface for HTML and XML
documents.When the browser tries to render an HTML document, it creates an object based on the
HTML document called DOM. Using this DOM, we can manipulate or change various elements
inside the HTML document.

19. What is document.writeln() ?

Answer:

document is an object and writeln is a method used for to print content on browser.

20. How can you create an Array in JavaScript?

Answer:

we can define arrays using the array literal as follows: var arr=[10,20,30];
21. List out the different ways an HTML element can be accessed in a JavaScript code.

Answer:

Here, these are the 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.

22. In how many ways a JavaScript code can be involved in an HTML file?

Answer:

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

a. Inline
b. Internal
c. External
23. What is Anonymous function in JavaScript?

Answer:

These types of functions doesn't contain any name. They are declared dynamically at runtime.

var display=function( ) {

document.writeln("Anonymous Function");

display( );

24. Define closure.

Answer:

In JavaScript, we need closures when a variable which is defined outside the scope in reference is
accessed from some inner scope.

var num = 10;

function sum( )

document.writeln(num+num);

sum( );

25. How to create objects in JavaScript?


Answer:

There are 3 ways to create an object in JavaScript.

a. By object literal
b. By creating an instance of Object
c. By Object Constructor

26. How to create an Array in JavaScript?

Answer:

There are 3 ways to create an array in JavaScript.

a. By array literal
b. By creating an instance of Array
c. By using an Array constructor

27. What is charAt() function ?

Answer:

charAt() : returns the character at the specific index.

charAt(0)

28. What is toUpperCase() function?

Answer:

toUpperCase() converts string to upper case letters.

29. What is Global scope?

Answer:

Variables that are not inside any function or the curly braces is known as Global Scope. These
variables can be accessed from all parts of the code.

30. What is the Local Scope?

Answer:

Variables declared inside a scope or function is known as function. Variables where it can be
accessed only within that function. That means they cannot be accessed outside code.

31. Explain the difference between synchronous and asynchronous programming in


JavaScript.

Answer:
Synchronous programming means that code is executed sequentially, one statement at a time.
Asynchronous programming, on the other hand, allows multiple operations to be performed
concurrently.

In JavaScript, asynchronous programming is commonly achieved using callbacks, promises, or the


async/await syntax. Asynchronous code allows for non-blocking behavior, which is crucial for
tasks like fetching data from servers or handling user interactions without freezing the UI.

32. How can you optimize the performance of JavaScript code?

Answer:

There are several techniques for optimizing JavaScript performance:

Minimize DOM manipulation: Reduce the number of DOM queries and updates.
Use efficient data structures and algorithms.
Avoid unnecessary calculations and function calls.
Optimize loops by reducing the number of iterations and avoiding unnecessary work inside loops.
Minimize network requests and utilize caching where possible.
Use tools like browser developer tools and performance profiling to identify bottlenecks and optimize
critical code paths.

33. What are closures in JavaScript, and how do they work?

Answer:

Closures are functions that retain access to variables from their lexical scope even after the scope has
exited. This means that closure can access variables defined in its outer function even after that function
has finished executing.

Closures are created whenever a function is defined within another function. They are powerful because
they allow for data encapsulation and the creation of private variables in JavaScript.

34. Explain Hoisting in javascript.

Answer:

Hoisting is the default behaviour of javascript where all the variable and function declarations are moved
on top.This means that irrespective of where the variables and functions are declared, they are moved on
top of the scope. The scope can be both local and global.

hoistedFunction();

function hoistedFunction(){

console.log(" Hello world! ");

35. Why do we use the word “debugger” in javascript?

Answer:

The debugger for the browser must be activated in order to debug the code. Built-in debuggers may be
switched on and off, requiring the user to report faults. The remaining section of the code should stop
execution before moving on to the next line while debugging.

36. What is the output of the following code snippet?


let x = 'Hello';
let y = 'World';
console.log(x + ' ' + y);

Answer:

‘Hello World’

37. What is called Variable typing in JavaScript ?

Answer:

The variable typing is the type of variable used to store a number and using that same variable to assign
a “string”.

Name=40;

Name=”Edunet foundation”

38. What are the types of Pop up boxes available in JavaScript?

Answer:

There are three types of pop boxes available in JavaScript.

Alert
Confirm
Prompt

39. What is the difference between an alert box and a confirmation box?

Answer:

An alert box will display only one button which is the OK button. It is used to inform the user about the
agreement has to agree. But a Confirmation box displays two buttons OK and cancel, where the user can
decide to agree or not.

40. What is the disadvantage of using inner HTML in JavaScript?

Answer:

There are lots of disadvantages of using the innerHTML in JavaScript as the content will replace
everywhere. If you use += like “innerHTML = innerHTML + ‘html'” still the old content is replaced by
HTML. It preserves event handlers attached to any DOM elements.

41. Which keywords are used to handle exceptions?

Answer:

The try statement lets you test a block of code to check for errors.
The catch statement lets you handle the error if any are present.
The throw statement lets you make your errors.

42. What is the use of the blur function?

Answer:

It is used to remove focus from the selected element. This method starts the blur event or it can be
attached to a function to run when a blur event occurs.

43. How to get the status of a CheckBox?

Answer:

document.getElementById("GFG").checked;

44. Write the errors shown in JavaScript.

Answer:

There are three different types of errors in JavaScript.

Syntax error: A syntax error is an error in the syntax of a sequence of characters or tokens that are
intended to be written in a particular programming language.

Logical error: It is the most difficult error to trace as it is the error on the logical part of the coding or
logical error is a bug in a program that causes to operate incorrectly and terminate abnormally.

Runtime Error: A runtime error is an error that occurs during the running of the program, also known as
an exception.

45. How are JavaScript and ECMA Script related?

Answer:

JavaScript is the main language that has to maintain some rules and regulations which is ECMA Script,
these rules also bring new features for the language JavaScript.

46. How to use any browser for debugging?

Answer:

By pressing the F12 we can trigger the debugging mode of any browser and can view the result by taping
the console.

47. What is the syntax of ‘Self Invoking Function’ ?

Answer:

(function () {
return // body of the function
}());

48. What would be the result of 3+2+”7??

Answer:

Here, 3 and 2 behave like an integer, and “7” behaves like a string. So 3 plus 2 will be 5. Then the output
will be 5+”7? = 57.
49. Which company developed JavaScript?

Answer:

Netscape developed JavaScript and was created by Brenden Eich in the year of 1995.

50. What do you mean by NULL in JavaScript?

Answer:

The NULL value represents no value or no object. It is known as empty value/object.

51. What is the difference between ViewState and SessionState?

Answer:

ViewState: It is specific to a single page in a session.

SessionState: It is user specific that can access all the data on the web pages.

52. Explain how to read a file using JavaScript?

Answer:

readFile( Path, Options, Callback)

53. Explain how to write a file using JavaScript?

Answer:

writeFile( Path, Data, Callback)

54. How to convert the string of any base to integer in JavaScript?

Answer:

In JavaScript, parseInt() function is used to convert the string to an integer. This function returns an
integer of base which is specified in second argument of parseInt() function. The parseInt() function
returns Nan (not a number) when the string doesn’t contain number.

55. How can the style/class of an element be changed?

Answer:

document.getElementById("myText").style.fontSize = "16px;

56. What is a cookie in JavaScript?

Answer:

In JavaScript, a cookie is a small piece of data stored on the client-side (user's browser) that persists
across sessions. Cookies are commonly used to store information such as user preferences, shopping cart
items, or session identifiers.

57. How do you create a cookie in JavaScript?

Answer:

We can create a cookie in JavaScript using the document.cookie property. Example given below
document.cookie=” username=Ajay; expires=Thu, 01 Apr 2024 00:00:00 UTC; “

58. How do you delete a cookie in JavaScript?

Answer:

To delete a cookie in JavaScript, you can set its expiration date to a time in the past. Like below

document.cookie=” username=Ajay; expires=Thu, 01 Apr 2024 00:00:00 UTC; “

59. Are cookies secure for storing sensitive information?

Answer:

No, cookies are not inherently secure for storing sensitive information because they can be accessed and
modified by the client-side code or intercepted in transit. For sensitive information, it's recommended to
use other mechanisms like HTTPS and server-side storage with proper encryption.

60. What are some alternatives to cookies in JavaScript?

Answer:

Some alternatives to cookies in JavaScript include:

Web Storage (localStorage and sessionStorage)


IndexedDB
Server-side sessions with tokens
JSON Web Tokens (JWT)
Browser fingerprinting techniques.

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


let a = 2;
if(a > 3) {
console.log('Yes');
} else {
console.log('No');
}

Answer:

No

62. What is the output of this code snippet?

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


console.log(i);
}

Answer:
012

63. Consider the following code:


let x = 5;
let result = (x > 3) ? 'Yes' : 'No';
console.log(result);
What is the output?

Answer:

Yes

64. Find the error in the following code:

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


if(i % 2 == 0) continue;
console.log(i);
}

Answer:

It only print odd numbers

65. In JavaScript, what is a callback function?

Answer:

A function passed an argument to another function

66. What is the result of trying to extend the length of an array using a function in JavaScript?

function extendArray(arr) {
arr.push(5);
}
let myArr = [1, 2, 3];
extendArray(myArr);
console.log(myArr.length);

Answer:

67. What is the output of this code snippet?


let arr = [10, 20, 30, 40];
let newArr = arr.map(x => x / 10);
console.log(newArr);

Answer:

[1,2,3,4]
68. What will be the output of this code snippet?
let numbers = [1, 2, 3];
numbers[10] = 11;
console.log(numbers.length);

Answer:

11

69. Consider the following code:


let arr = [1, 2, 3];
arr[5] = 5;
console.log(arr.filter(x => x === undefined).length);
What is the output?

Answer:

70. What will be the output of console.log(typeof { })?

Answer:

Object

71. Identify the error in this code:


document.getElementById('myBtn').onClick = function() {
console.log('Button clicked');
};

Answer:

Incorrect event property

72. What does the following JavaScript code do?

fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data));

Answer:

Request data from ('https://api.example.com/data')

73. What will this Fetch API code snippet do?


fetch('https://api.example.com/update', {
method: 'POST',
body: JSON.stringify({name: 'Alice'})
})
.then(response => response.json())
.then(data => console.log(data));

Answer:

Submit data to the url and logs the response.


74. Identify the issue in this fetch request:
fetch('https://api.example.com/data', {
method: 'GET',
body: JSON.stringify({id: 1})
});

Answer:

Get request should not have a body

75. What will this code output?

try {
let x = y;
} catch(e) {
console.log(typeof e);
}

Answer:
Object

76. Identify the error in this code:


try {
let result = 'Result';
console.log(result);
} catch(e) {
console.log(e);
} finally {
console.log(reslt);
}

Answer:

Misplaced variable in finally block

77. What does the following ES6 code output?


let [a, b] = [1, 2];
console.log(a);

Answer: 1

78. What is a Promise in JavaScript?

Answer:

An object representing the eventual completion of failure Of an asynchronous operation.

79. What does the following code do?


new Promise((resolve, reject) => {
setTimeout(() => resolve('Result'), 2000);
})
.then(result => console.log(result));

Answer:

Result after 2 seconds


80. What is currying in JavaScript?

Answer:

The process of breaking down a function into a series of functions that each take a single argument.

81. What will the following curried function output?


function multiply(a) {
return function(b) {
return a * b;
};
}
let multiplyByTwo = multiply(2);
console.log(multiplyByTwo(3));

Answer:

82. Consider this code:


class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
} let rect = new Rectangle(5, 10);
console.log(rect.area);
What is the output?

Answer:

50

83. What will the following inheritance code output?

class Animal {
speak() {
return 'I am an animal';
}
}
class Dog extends Animal {
speak() {
return super.speak() + ', but more specifically a dog';
}
}
let dog = new Dog();
console.log(dog.speak());

Answer:

I am an animal but more specifically a dog

84. pot the error in this class inheritance:


class Animal { constructor(name) {
this.name = name;
}
}
class Cat extends Animal {
constructor(name, lives) {
super();
this.lives = lives;
}
}

Answer:

Missing name argument in the super call

85. What will be the result of this code if localStorage already has 10 items?

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


localStorage.setItem(key${i}, value${i});
}
console.log(localStorage.length);

Answer:

15

86. In JavaScript, answer if the following expressions result in true or false.

"0" == 0 // true or false ?


"" == 0 // true or false ?
"" == "0" // true or false ?

Answer:

The result will be True for 1st and 2nd case and False for the 3rd case.

87. Write a function that takes a string as input and returns the string reversed.

function reverseString(str){

return str.split('').reverse().join('');}

console.log(reverseString('hello')); //

Answer: 'olleh'

88. Write a function to calculate the factorial of a given number.

function factorial(n) {

if (n === 0 || n === 1) {

return 1;

} else {

return n * factorial(n - 1);

console.log(factorial(5)); //
Answer:

120 (5! = 5*4*3*2*1 = 120)

89. Write a function to check if a given string is a palindrome (reads the same forwards and
backwards).

function isPalindrome(str) {

const reversedStr = str.split('').reverse().join('');

return str === reversedStr;}

console.log(isPalindrome('radar'));

console.log(isPalindrome('hello'));

Answer:

True

False

90. Find the Longest Word: Write a function that takes a sentence as input an returns the longest
word in it.

function longestWord(sentence) {

const words = sentence.split(' ');

let longest = '';

for (let word of words) {

if (word.length > longest.length) {

longest = word;}}return longest;}

console.log(longestWord('The quick brown fox jumps over the lazy dog'));

Answer:

'jumps'

You might also like