Praise first, then watch, form a habit ~
1. What is the use of let and const in JS?
In modern js, let&const is a different way of creating variables. In the early days of JS, we used the var keyword to create variables. The let&const keyword was introduced in the ES6 release to create two different types of variables in JS, one immutable and the other mutable.
Const: Used to create an immutable variable. Immutable variables are those whose values never change throughout the life of a program.
Let: Let is used to create a mutable variable, which is a normal variable like var that can be changed any number of times.
2. What are the main types of errors in JS
JS has three types of errors:
Load-time errors: Errors that occur while loading a Web page, such as syntax errors, are called load-time errors and dynamically generate errors.
Runtime error: Error caused by misuse of commands in HTML language.
Logic errors: These errors are caused by incorrect logic being executed on functions that have different operations
3. How do I get DOM elements by category name
The use of the document in JS. GetElementsByClassName () method to get the element with the name of the class.
4. What is the scope chain of JS and its role
Normally, a variable takes a value in the scope of the function that created it. But if no value is found in the current scope, the chain is called the scope chain.
Scope chains in JS are mainly used to resolve the values of variables. Without this, many variables are defined in different scopes, and it is difficult for JS to select a value for the variable.
5. Explain the MUL function in JS
MUL represents a simple multiplication of numbers. In this technique, one value is passed as an argument to a function that returns another function, passes the second value to the function, and then repeats. For example, x*y*z can be expressed as
function mul (x) {
return function (y) {
return function (z) {
returnx * y * z; }}}Copy the code
6. Write a program to invert strings in pure JS
Use built-in functions: the built-in function reverse() reverses the string directly.
str="jQuery";
str = str.split("")
str = str.reverse()
str = str.join("")
alert(str);
Copy the code
First the string is split into arrays, then the array is reversed, and most recently the characters are concatenated to form strings. Using loops: First, the number of characters in the string is counted, and then a decrement loop is applied to the original string, which starts with the last character and prints each character until count becomes zero.
7. How do I redirect a page to another page in JS?
- Use location.href: window.location.href
- = “https://www.onlineinterviewquestions.com/” to use the location. The replace: window.location.replace(” https://www.onlineinterviewquestions.com/;” );
8. List some design patterns in JS:
Design patterns are common reusable solutions to common problems in software design. Here are some design patterns: Create patterns: This pattern abstracts the object instantiation process.
Structural patterns: These patterns work with different classes and objects to provide new functionality.
Behavior pattern: Also known as publish-subscribe pattern, it defines a one-to-many object relationship between one observed and multiple observers.
Parallel design patterns: These patterns deal with the multithreaded programming paradigm. Architectural design patterns: These patterns are used to address architectural design
9. What is the difference between the array.splice () and array.slice () methods in JS
Without further ado, let’s look at the first example:
Var arr =,1,2,3,4,5,6,7,8,9 [0]; // set an array console.log(arr.slice(2,7)); / / 2,3,4,5,6 console. The log (arr. Splice (2, 7)); //2,3,4,5,6,7,8 Slice (start,end) The first parameter indicates the start position, and the second parameter indicates the intercepted position (excluding the intercepted position) splice(start,length) The start position of the first parameter and the second parameter indicates the intercepted lengthCopy the code
Moving on to the second:
,1,2,3,4,5,6,7,8,9 var x = y = [0] the console. The log (x.s lice (2, 5)); / / 2 and 4 console. The log (x); [0,1,2,3,4,5,6,7,8,9] splice console.log(y.splice(2,5)); / / 2,3,4,5,6 console. The log (y); //[0,1,7,8,9] shows that the values in the original array are removedCopy the code
Slice and splice are both truncated from array objects, but there are significant differences between them. The first argument to slice and splice is the start of the truncation, the second argument to slice is the end of the truncation (not included), and the second argument to splice is the start of the truncation Length),slice makes no changes to the array, while splice strips the array.
10. How to dynamically add/remove object attributes in JS?
We can add properties to objects using Object. property_name = value and delete Object. property_name to delete properties. Such as:
let user = new Object();
// adding a property
user.name='Anil';
user.age =25;
console.log(user);
delete user.age;
console.log(user);
Copy the code
11. Explain what promise is.
A promise is an object in JS that generates a value that might yield a result in the future. The value can be a parsed value or a reason why the value was not parsed.
Promises can have three states:
- Pending: Initial state, neither success nor failure
- Depressing: Means that the operation will be completely successful
- Rejected: Indicates that the operation fails
12. What are the methods of array repetition
1. Using the set
function uniquearray(array) {
let unique_array= Array.from(set(array))
return unique_array;
}
Copy the code
2. Use the filter
function unque_array (arr) {
let unique_array = arr.filter(function(elem, index, self) {
return index == self.indexOf(elem);
})
return unique_array;
}
console.log(unique_array(array_with_duplicates));
Copy the code
3. Use the for loop
Array dups_names = ['Ron'.'Pal'.'Fred'.'Rongo'.'Ron'];
function dups_array(dups_names) {
let unique = {};
names.forEach(function(i) { If (! unique[i]) { unique[i] =true; }});returnObject.keys(unique); } // Ron, Pal, Fred, Rongo Dups_array(names);Copy the code
13. What is the difference between null and undeclared?
1. Null means “no object”, that is, there should be no value. When converted to a value, the value is 0. Typical usage:
(1) as the parameter of the function, indicating that the parameter of the function is not an object.
(2) as the end of the object prototype chain.
2. Undefined means “missing value”, that is, there should be a value here, but it is not defined yet, when converted to a value, NaN. Typical usage:
(1) If a variable is declared but not assigned, it is undefined.
(2) When the function is called, the argument that should be provided is not provided, which is equal to undefined.
(3) The object has no assigned attribute. The value of this attribute is undefined.
(4) If the function does not return a value, undefined is returned by default. 3. Undeclared: javascript syntax error, javascript cannot find the corresponding context if it is used directly without declaring it.
14. List some differences between basic and non-basic data types of JS.
1. There are six basic data types in JS: Undefined, Null, Boolean, Number, Symbol and String. There is also a complex data type ————Object, which is essentially an unordered set of name-value pairs. Object, Array, and Function are reference types.
2. Primitive data types are immutable, whereas non-primitive data types are mutable.
3. Basic data types are immutable because they cannot be changed once they are created, but non-basic data types are just mutable, meaning that once an object is created, it can be changed.
4. Base data types are compared to their values, which means that if two values have the same data type and have the same value, they are strictly equal.
5. Non-basic data types are not compared to values. For example, if two objects have the same properties and values, they are strictly not equal.
15. How do I add new attributes to an existing function
You can easily add new attributes to an existing function simply by assigning values to it. For example, if you have an existing object person, add a new attribute to person using the following code:
Person. Country = "India";Copy the code
16. What is the difference between deep copy and shallow copy in JS?
- Deep copy recursively copies all values or attributes in the new object, while copy copies only references.
- In a deep copy, changes in the new object do not affect the original object, while in a shallow copy, changes in the new object are changed in the original object.
- In the deep copy, the original object does not share the same properties as the new object, while in the shallow copy, they have the same properties.
17. How do I call a function every x seconds in JavaScript
In JS, we use the function setInterval() to call the function every x seconds. Such as:
setInterval(function (){ alert("Hello"); }, 3000);
Copy the code
18. Explain the JS expansion operator?
The expansion operator expands expressions where more than one argument/variable/element is needed, using three points (…) . Such as:
var mid = [3, 4];
var newarray = [1, 2, ...mid, 5, 6];
console.log(newarray);
// [1, 2, 3, 4, 5, 6]
Copy the code
19. How are host objects in JS different from native objects?
Host objects: These are objects provided by the runtime environment. This means that they are different in different environments. For example, the browser contains objects like Windows, but the Node.js environment provides objects like Node List.
Native objects: These are built-in objects in JS. They are also called global objects because the built-in objects are not affected by the runtime environment if you use JS.
Explain higher-order functions in JS?
Higher-order functions are the best feature of JS functional programming. It is a function that takes a function as an argument and returns a function as a result. Some of the built-in higher-order functions are Map, filter, reduce, and so on.
What is the difference between == and === in JS?
1. There is a difference between == and === for basic types such as string and number
1) Comparison between different types, == comparison of “value after conversion to the same type” to see whether “value” is equal, === if the type is different, the result is unequal.
2) The same type of comparison, direct “value” comparison, the two results are the same.
2. For advanced types such as Array and Object, there is no difference between == and ===.
There is a difference between basic types and advanced types, == and ===
1) For ==, convert the advanced type to the base type for a “value” comparison.
2) Because the type is different, === result is false.
22. What are anonymous functions in JS?
An anonymous function is a function that has no function name, such as:
(function(x, y){ alert(x + y); }) (2, 3);Copy the code
An anonymous function is created (in the first parenthesis), and the second parenthesis is used to call the anonymous function, passing in arguments.
23. Can I perform 301 redirection in JS?
JS runs entirely on the client. 301 is the response code that the server sends as a response. Therefore, it is not possible to perform a 301 redirect in JS.
24. Explain event bubbling and event catching in JS
Event capture and bubbling: In the HTML DOM API, there are two event propagation methods that determine the order in which events are received. The two methods are event bubbling and event capturing. The first method event bubbles to point the event to its intended target, and the second method is called event capture, where the event reaches down to the element.
Event capture
The capture process is rarely used, but when it is, it proves to be very useful. This process is also known as trickle mode. In this process, events are first captured by the outermost element and then propagated to the innermost element. Such as:
<div>
<ul>
<li></li>
</ul>
</div>
Copy the code
From the example above, assume that the click event occurred in the LI element, in which case the capture event would first process div, then UL, and finally hit the target element Li.
The event bubbling
Bubbling works like bubbling, in that the event is processed by the innermost element and then propagated to the outer element.
<div>
<ul>
<li></li>
</ul>
</div>
Copy the code
From the above example, assuming that the click event does occur within the LI element in the bubble model, the event will be handled first by LI, then by UL, and finally by the div element.
24. How do I export all files as one object?
Import * as objectName from ‘./file.js’ is used to import all exported members as objects. You can use the object’s dot (.) Operator to access an exported variable or method, such as:
objectname.member1;
objectname.member2;
objectname.memberfunc();
Copy the code
25. Explain what the arrow function is.
The arrow function is a concise way to write function expressions in ES6 and later. Arrow functions cannot be used as constructors, nor do they support the this, arguments, super, or new.target keywords, and are best suited for non-method functions. Normally, arrow functions look like const function_name = () => {}.
const greet=()=>{console.log('hello'); } greet();Copy the code
Explain function promotion in JS
The default behavior that JS allows to move declarations to the top is called promotion. The two ways to create functions in JS are function declarations and function expressions.
Function declaration
Functions that take specific parameters are called function declarations, and creating variables in JS is called declarations. Such as:
hoisted(); // logs "foo"
function hoisted() {
console.log('foo');
}Copy the code
Functional expression
When a function is created using an expression, it is called a function expression. Such as:
notHoisted(); // TypeError: notHoisted is not a function
var notHoisted = function() {
console.log('bar');
};
Copy the code
What’s the difference between module. Exports and exports?
Module and exports are two objects that node.js builds into every JS file. It can be printed through console.log(module) and console.log(exports). If you write the following two lines in main.js, then run $node main.js:
console.log(exports); // Output: {} console.log(module); // Output: Module {... , exports: {}, ... } (Note:... Represents omitting some other attributes.Copy the code
Module. exports and exports both start out as an empty object {}. In fact, both objects refer to the same memory block. This means that module.exports and exports are equivalent (with the exception of not changing the memory address they point to).
For example, exports.age = 18 and module.export.age = 18 are the same (both add an attribute to the original empty object {}, and require {age: 18}).
28. What are import and exports?
Import and exports help us write modular JS code. With import and exports, we can split code into multiple files. Import allows you to retrieve only certain variables or methods of a file. You can import methods or variables exported by a module.
//index.js
import name,age from './person';
console.log(name);
console.log(age);
//person.js
let name ='Sharad', occupation='developer', age =26;
export { name, age};
Copy the code
29. List some unit testing frameworks
Here are some of the most popular JS unit testing frameworks:
- Unit.js
- Jasmine
- Karma
- Chai
- AVA
- Mocha
- JSUnit
- QUnit
- Jest
What are the different types of pop-ups available in 30 JS
There are three types of pop-ups available in JS:
- Alert
- Confirm
- Prompt
31. How do I convert JS dates to ISO standards
The toISOString() method is used to convert A JS date to an ISO standard. It converts a JS Date object to a string using the ISO standard. Such as:
var date = new Date();
var n = date.toISOString();
console.log(n);
// YYYY-MM-DDTHH:mm:ss.sssZ
Copy the code
32. How to clone objects in JS
The object.assign () method is used to clone objects in JS. Such as:
var x = {myProp: "value"};
var y = Object.assign({}, x);
Copy the code
33. How to encode and decode in JS
The URL encodeURI() function is used to encode urls in JS. It takes the URL string as an argument and returns the encoded string.
Note: encodeURI() does not encode characters like: /? If you need to encode these characters, use encodeURIComponent(). Usage:
var uri = "my profile.php? Name = sammer&occupation = p ā ntiNG. "";
var encoded_uri = encodeURI(uri);
Copy the code
The decodeURI() function decodes urls in JS. It takes the encoded URL string as an argument and returns the decoded string.
var uri = "my profile.php? Name = sammer&occupation = p ā ntiNG. "";
var encoded_uri = encodeURI(uri);
decodeURI(encoded_uri);
Copy the code
34. Relationship between BOM and DOM
BOM stands for Browser Object Model, which deals with Browser Windows and frames.
DOM is an APPLICATION program interface (API) for HTML and XML. It complies with W3C standards, which are common to all browsers.
JS accesses, controls and modifies the client (Browser) by accessing the BOM (Browser Object Model) Object. Since the Window of BOM contains the Document, the properties and methods of the Window Object can be directly used and perceived. Therefore, you can directly use the Document attribute of the Window object to access, retrieve, and modify the content and structure of an XHTML document. Because the Document object is the root of the DOM.
In other words, the BOM contains the DOM(object), which is provided and accessed by the browser. From the BOM object to the DOM object, JS can manipulate the browser and the document that the browser reads.
35. What is the difference between the substr() and substring() functions in JS
The substr() function is of the form substr(startIndex,length). It returns the substring from startIndex and the number of ‘length’ characters.
var s = "hello"; (s.s ubstr (1, 4) = ="ello") / /true
Copy the code
The substring() function is of the form substring(startIndex,endIndex). It returns a substring from startIndex to endIndex-1.
var s = "hello"; (s.s ubstring = = (1, 4)"ell") / /true
Copy the code
36. Explain “use strict”? “
Use strict “is a JS directive introduced in Es5. The purpose of the “Use Strict” directive is to enforce code in strict mode. In strict mode, we cannot use variables without declaring them. Earlier versions of JS omitted “use strict”.
Explain the JS event delegation model?
There are some cool things in JS. One of them is the delegation model. When capturing and bubbling, functions are allowed to implement a handler to multiple elements at a particular time, called event delegation. Event delegates allow event listeners to be added to the parent node instead of the specified node. This particular listener analyzes bubbling events to find matches on child elements.
communication
Subject matter reference network, copyright belongs to the author all