takeaway
It is said that gold nine silver ten is a good season for interview. Recently, I saw some front-end interview questions on GitHub, which are also quite basic. I sorted them out here, because there are many contents, and I divided them into HTML, CSS and JavaScript here. To find a job that I love, of course, including myself, let’s go!
Because the nuggets of a boiling point, here to explain first, this article is suitable for the current job or feel that their foundation is not too solid small partners, big god will skip it.
Forward since github.com/yangshun/fr…
- HTML report addresses
- CSS article addresses
1. Please explain the event delegation.
Event delegates add event listeners to parent elements rather than setting event listeners individually for each child element. When a child element is fired, events bubble up to the parent element, and listeners fire. The benefits of this technique are:
1. Memory footprint is reduced because you need only one event handler for the parent element instead of adding event handlers for each descendant. 2. There is no need to unbind handlers from deleted elements or bind handlers to new elements.
2. Please shareJavaScript
In thethis
.
JS “this” is a relatively complex concept, which can not be explained clearly in a few simple sentences. Roughly speaking, how the function is called determines the value of this. I have read many articles about this on the Internet, and Arnav Aggrawal wrote it clearly. The value of this must comply with the following rules:
1. Use the new keyword when calling a function. This is a brand new object inside the function. 2. If the apply, call, or bind methods are used to call and create a function, this is the object passed as an argument to those methods. 3. When a function is called as a method in an object, this is the object on which the function is called. For example, when obj.method() is called, this inside the function is bound to the obj object. 4. If the calling function does not conform to the above rules, then the value of this refers to the global object. The value of this refers to the window object in the browser environment, but in strict mode (‘use strict’), the value of this is undefined. 5. If more than one of the above rules is true, the higher rule (number 1 highest, number 4 lowest) will determine the value of this. 6. If this function is an arrow function in ES2015, all the above rules are ignored and this is set to the context in which it was created.
3. Explain how stereotype inheritance works.
This is a very common JavaScript problem. All JS objects have a prototype property that points to their prototype object. When it tries to access an object’s properties, if it doesn’t find one on that object, it also searches for that object’s prototype, and the prototype of that object’s prototype, working its way up until it finds an attribute with a matching name or reaches the end of the prototype chain. This behavior mimics classical inheritance, but is more like delegation than inheritance.
4. Say you are rightAMD
andCommonJS
Understanding.
They are all ways to implement a modular architecture, which JavaScript didn’t have until ES2015. CommonJS is synchronous, while AMD (Asynchronous Module Definition) is obviously Asynchronous. CommonJS is designed with server-side development in mind, while AMD supports asynchronous loading modules that are better suited for browsers.
I find AMD’s syntax very verbose, and CommonJS is closer to the usage conventions of import statements in other languages. For the most part, I don’t think AMD needs to use it because if you bundle all your JavaScript into one file, you won’t get the benefits of asynchronous loading. In addition, CommonJS is syntactically closer to Node’s modular writing style, with less context switching overhead when switching between both ends of development using JavaScript.
I’m glad to see that ES2015 supports both synchronous and asynchronous module loading solutions, so we can finally use only one solution. It’s not yet fully available in browsers and Node, but you can use transcoding tools to do the conversion.
5. Please explain why the following code cannot be usedIIFE:function foo(){ }();
And what changes need to be made to make itIIFE
?
IIFE (Immediately Invoked Function Expressions) represents the immediate execution of the Function. The JavaScript parser calls function foo(){}(); Function foo(){} and (); . Where, the former is a function declaration; The latter (a pair of parentheses) is an attempt to call a function without specifying a name, so it throws an Uncaught SyntaxError: Unexpected Token) error.
Function foo(){})() {function foo(){}()); The above functions are not exposed to the global scope. You can omit the function name if you do not need to reference itself inside the function.
You might use the void operator: void function foo(){}(); . But there are problems with this approach. The value of the expression is undefined, so do not use this method if your IIFE returns a value. Such as:
const foo = void function bar() { return 'foo'; } (); console.log(foo); // undefinedCopy the code
6.null
,undefined
What is the difference between undeclared variables and undeclared variables? How are these state values checked and determined?
Variables are undeclared variables when you assign a value to a variable without declaring it first using var, let, or const. Undeclared variables leave the current scope and become variables defined under the global scope. In strict mode, assigning a value to an undeclared variable raises ReferenceError. Like using global variables, using undeclared variables is a very bad practice and should be avoided whenever possible. To check for them, place the code that uses them in a try/catch statement.
function foo() { x = 1; // In strict mode, raise ReferenceError} foo(); console.log(x); / / 1Copy the code
The value of a variable is undefined when it has been declared but not assigned. If the result of a function is assigned to a variable, but the function returns no value, the value of the variable is undefined. To check it, use strict equality (===); Or use typeof, which returns the string ‘undefined’. Note that non-strict equality (==) cannot be used for checking, because it will also return true if the variable value is null.
var foo;
console.log(foo); // undefined
console.log(foo === undefined); // true
console.log(typeof foo === 'undefined'); // trueconsole.log(foo == null); // true. Error, do not use non-strict equality!function bar() {}
var baz = bar();
console.log(baz); // undefined
Copy the code
Null can only be explicitly assigned to a variable. It represents a null value, as opposed to the meaning of being explicitly assigned to undefined. To check for null values, use the strict equality operator. Note that, as before, non-strict equality (==) cannot be used to check, because it will return true if the variable value is undefined.
var foo = null;
console.log(foo === null); // trueconsole.log(foo == undefined); // true. Error, do not use non-strict equality!Copy the code
As a matter of personal habit, I never use undeclared variables. If I define variables that are not used for the time being, I explicitly assign them null after the declaration.
7. What are closures and why are they used?
A closure is a combination of a function and the lexical environment in which it is declared. The fields used in lexical scopes are determined by where variables are declared in the code. A closure is a function that can access the scope of an external (enclosing) function even if it is returned by an external function.
Why use closures? 1. Use closures to privatize data or simulate private methods, also known as the modular pattern. 2. Coriolization of some parameter functions.
8. Please specify.forEach
Circulation and.map()
The main differences between cycles, in what cases are they used?
To understand the difference between the two, let’s look at what they do.
1. ForEach through the elements of the array. Callbacks are performed for each element. No return value. const a = [1, 2, 3]; Const double = a.fleach ((num, index) => {// call code associated with num, index}); A new array is created by calling a function on each element to "map" each element to a new element. const a = [1, 2, 3]; const doubled = a.map(num => {return num * 2;
});
// doubled = [2, 4, 6]
Copy the code
The main difference between.foreach and.map() is that.map() returns a new array. If you want a result, but don’t want to change the original array, use.map(). If you only need to iterate over an array, use forEach.
9. What are the typical application scenarios of anonymous functions?
Anonymous functions can be used in IIFE to encapsulate code in a local scope so that its declared variables are not exposed to the global scope.
(function() {// Some code. }) (); Anonymous functions can be used as callback functions that are used only once and need not be used elsewhere. When handlers are defined inside the program that calls them, the code is better closed and readable, saving you the trouble of finding the location of the body of the handler.setTimeout(function() {
console.log('Hello world! '); }, 1000); Anonymous functions can be used for functional programming or Lodash (similar to callback functions). const arr = [1, 2, 3]; const double = arr.map(function(el) {
returnel * 2; }); console.log(double); / / (2, 4, 6]Copy the code
10. How do you organize your code? (Module Pattern or Classical Inheritance?)
I used to organize my models using Backbone. Backbone encourages an object-oriented approach by creating and adding methods to Backbone models.
Module mode is still a good way to go, but now I use the React/ Redux-based Flux architecture, which encourages a one-way function programming approach. I represent my APP model with plain Objects and write utility pure functions to manipulate those objects. Use Actions and reducers to handle state, just like other Redux applications.
I avoid classical inheritance as much as possible. If I have to, I will stick to those principles.
11. Host object(the host objects)
And native objects(native objects)
What is the difference between?
Native objects are JavaScript built-in objects defined by the ECMAScript specification, such as String, Math, RegExp, Object, Function, and so on.
Host objects are provided by the runtime environment (browser or Node), such as Window, XMLHTTPRequest, and so on.
12. What is the difference between the following statements:
function Person(){}
var person = Person()
var person = new Person()
Copy the code
The question is very vague. I guess this is looking at JavaScript constructors. Technically, function Person(){} is just a plain old function declaration. It is a convention to use pascalcase-named functions as constructors.
Var person = person () calls Person as a normal function, not as a constructor. This is a common mistake if the function is used as a constructor. Normally, constructors do not return anything, so calling the constructor like a normal function returns only the variable assigned to the instance by undefined.
Var person = new person () Uses the new operator to create an instance of the Person object that inherits from Person.prototype. Another way is to use object.create, for example:
Object. The create ` (Person) prototype).function Person(name) {
this.name = name;
}
var person = Person('John');
console.log(person); // undefined
console.log(person.name); // Uncaught TypeError: Cannot read property 'name' of undefined
var person = new Person('John');
console.log(person); // Person { name: "John" }
console.log(person.name); // "john"
Copy the code
13..call
和 .apply
What’s the difference?
Both.call and.apply are used to call functions, and the first argument will be used as the value of this within the function. However,.call accepts a comma-separated argument as the following argument, while.apply accepts an array of arguments as the following argument. An easy way to remember this is to associate the C in call with comma-separated and the A in Apply with array.
function add(a, b) {
returna + b; } console.log(add.call(null, 1, 2)); // 3 console.log(add.apply(null, [1, 2])); / / 3Copy the code
14. Please specifyFunction.prototype.bind
The use of.
From MDN:
The bind() method creates a new function that, when called, sets its this keyword to the supplied value and, when called, provides a given sequence of arguments before any supply.
In my experience, it’s useful to bind the value of this to a method of a class that you want to pass to another function. This is often done in the React component.
15. When will you need itdocument.write()
?
Document.write () is used to write a string of text to the document stream opened by document.open(). When document.write() is executed after the page is loaded, it calls Document.open, which clears the entire document ( and are removed!). And replaces the document contents with the given string parameters. Therefore, it is often considered dangerous and prone to misuse.
There are some answers online that explain how document.write() is used to analyze code, or when you want to include styles that only work if JavaScript is enabled. It’s even used in HTML5 boilerplate code to parallel load scripts and keep them in order! However, I suspect that these reasons for use are outdated and can now be implemented without document.write(). Please correct me if I am wrong.
Please explain in as much detail as possibleAjax
.
Ajax (Asynchronous JavaScript and XML) is a Web development technology that uses many Web technologies on the client to create asynchronous Web applications. With Ajax, Web applications can send and retrieve data asynchronously (in the background) to and from the server without interfering with the display and behavior of existing pages. By separating the data exchange layer from the presentation layer, Ajax allows Web pages and extended Web applications to change content dynamically without reloading the entire page. In fact, XML is now commonly replaced with JSON because JavaScript has the advantage of native support for JSON.
The XMLHttpRequest API is often used for asynchronous communication. There is also the recently popular FETCH API.
17. What are the pros and cons of using Ajax?
advantages
Better interactivity. New content from the server can change dynamically without reloading the entire page. Reduce connections to the server because scripts and styles need to be requested only once. State can be maintained on a page. JavaScript variables and DOM state are preserved because the main container page has not been reloaded. Basically includes most of the benefits of SPA.Copy the code
disadvantages
Dynamic web pages are hard to bookmark. This does not work if JavaScript is already disabled in the browser. Some web crawlers do not execute JavaScript and do not see JavaScript loaded content. Basically including most of the disadvantages of SPA.Copy the code
18. Please specifyJSONP
How does it work? Why isn’t it trueAjax
?
JSONP (JSON with padding) is a common way to get around cross-domain restrictions in Web browsers because Ajax does not allow cross-domain requests.
JSONP sends cross-domain requests with
<! -- https://mydomain.com --> <script>function printData(data) {
console.log(`My name is ${data.name}! `); } </script> <script src="https://example.com?callback=printData"></script>
printData({ name: 'Yang Shun' });
Copy the code
The client must have the printData function in its global scope, and it will be executed by the client when it receives a response from across domains.
JSONP may have some security implications. Because JSONP is a pure JavaScript implementation, it can do everything JavaScript can, so you need to trust the provider of the JSONP data.
In a world where cross-source resource sharing (CORS) is the dominant method of recommendation, JSONP has come to be seen as a hack.
19. Please explain the variable escalation.
Variable promotion, or reactive, is the term used to explain the behavior of variable declarations in code. Variables declared or initialized with the var keyword “elevate” the declaration statement to the top of the current scope. However, only the declaration will trigger the promotion, and the assignment statement (if any) will remain unchanged. Let’s illustrate this with a couple of examples.
// Use var to promote console.log(foo); // undefined var foo = 1; console.log(foo); / / 1 / /let/const does not promote console.log(bar); // ReferenceError: bar is not definedletbar = 2; console.log(bar); // 2 Function declarations promote the function body, but function expressions (written as declared variables) only the variable declarations are promoted. // Function declaration console.log(foo); // [Function: foo] foo(); //'FOOOOO'
function foo() {
console.log('FOOOOO'); } console.log(foo); // [Function: foo] // Function expression console.log(bar); // undefined bar(); // Uncaught TypeError: bar is not afunction
var bar = function() {
console.log('BARRRR');
};
console.log(bar); // [Function: bar]
Copy the code
20. Describe the event bubbling.
When an event is fired on a DOM element, if there is an event listener, it will try to handle the event, and then the event bubbles up to its parent element and the same thing happens. Finally, the event reaches the ancestor element. Event bubbles are the principle that implements event delegation.
21.”attribute
“And”property
What’s the difference?
“Attribute” is defined in HTML and “property” is defined in the DOM. To illustrate the difference, suppose we have a text box in HTML:
<input type="text" value="Hello">。
const input = document.querySelector('input');
console.log(input.getAttribute('value')); // Hello console.log(input.value); // Hello but type "World!" in the text box : after the console. The log (input. The getAttribute ('value')); // Hello
console.log(input.value); // Hello World!
Copy the code
22. Why expandJavaScript
Built-in objects are bad, right?
Extending JavaScript built-in (native) objects means adding properties or methods to their Prototype. While that sounds great, it’s actually dangerous. Imagine that your code uses libraries that extend array. prototype by adding the same Contains method. If the two methods don’t behave the same, then these implementations will overwrite each other and your code won’t work.
The only use scenario for extending built-in objects is to create polyfill, essentially providing your own implementation of a method that was missing from older browsers, as defined by the JavaScript specification.
23.document
In theload
Events andDOMContentLoaded
What is the difference between events?
The DOMContentLoaded event is fired after the initial HTML document has been fully loaded and parsed, without waiting for the stylesheet, image, and subframe to complete loading.
The Window load event is triggered only after the DOM and all associated resources have been loaded.
24.= =
and= = =
What is the difference between?
== is the abstract equality operator, while === is the strict equality operator. The == operator is compared after the necessary type conversion. The === operator does not cast, so if two values are not of the same type, it returns false. When == is used, something special can happen, such as:
1 = ='1'; // true1 = = [1]; //true1 = =true; // true0 = =' '; // true0 = ='0'; // true0 = =false; // trueMy recommendation is never to use the == operator, except to facilitate comparisons with null or undefined, where a == null returns if a is null or undefinedtrue. var a = null; console.log(a == null); //true
console.log(a == undefined); // true
Copy the code
25. Please explain aboutJavaScript
Is the same origin policy.
The same origin policy prevents JavaScript from making cross-domain requests. A source is defined as a combination of URI, host name, and port number. This policy prevents malicious scripts on a page from accessing sensitive data on another page through the document object model on that page.
26. Please validate the following statement:
duplicate([1, 2, 3, 4, 5]); / /,2,3,4,5,1,2,3,4,5 [1]
function duplicate(arr) {
returnarr.concat(arr); } duplicate([1, 2, 3, 4, 5]); / /,2,3,4,5,1,2,3,4,5 [1]Copy the code
27. Describe the “in a ternary expression.Three yuan
What does the word stand for?
“Ternary” accepts three operands: a judgment condition, then expression, and else expression. Ternary expressions are not javascript-specific, and I don’t know why the problem came up here.
28. What is”use strict
“; ? What are the advantages and disadvantages of using it?
‘Use strict’ is a statement used to enable strict mode for an entire script or for a single function. Strict mode is optional as a way to limit variants of JavaScript.
Advantages:
Global variables can no longer be accidentally created. Causes an assignment operator that causes silently fail (i.e., no error and no effect) to throw an exception. An exception is thrown when an attempt is made to remove a non-deletable property (previously this had no effect). The parameter name of the function is required to be unique. Globally, the value of this is undefined. Some common coding errors are caught and exceptions are thrown. Disable confusing or poor features.Copy the code
Disadvantages:
Missing features that many developers have become accustomed to. Unable to access function.caller and function.arguments. Scripts written in different strict modes can cause problems when combined. Overall, I think the pros outweigh the cons, and I never use features that are disabled in strict mode, so I recommend using strict mode.Copy the code
29. Create a loop that iterates from 1 to a multiple of 100 and outputs”fizz
“, output “buzz” when multiples of 5, output “buzz” when multiples of 3 and 5fizzbuzz
“.
for (let i = 1; i <= 100; i++) {
let f = i % 3 == 0,
b = i % 5 == 0;
console.log(f ? (b ? 'FizzBuzz' : 'Fizz') : b ? 'Buzz' : i);
}
Copy the code
I don’t recommend that you write this code in your interview. Just write it clearly. For more quirky FizzBuzz implementations, check out the reference links below.
30. Why not use global scopes?
Every script has access to the global scope, and if everyone uses the global namespace to define their own variables, there are bound to be conflicts. Use the module pattern (IIFE) to encapsulate variables in a local namespace.
31. Why use itload
Event? Are there any downsides to this event? Do you know of any alternatives and why you use them?
The Load event is triggered after the document is loaded. At this point, all objects in the document are in the DOM, and all images, scripts, links, and subframes have been loaded.
The DOM event DOMContentLoaded will fire after the DOM build of the page is complete, but do not wait for other resources to finish loading. This event is preferred if the entire page does not need to be loaded before initialization.
32. Explain what a single page app is and how to make it SEO friendly.
Today, Web developers refer to the products they build as Web applications, not websites. While there is no strict distinction between the two terms, web applications tend to be highly interactive and dynamic, allowing users to perform operations and receive responses to their operations. In the past, the browser received HTML from the server and rendered it. When the user navigates to another URL, a full page refresh is required, and the server sends the new HTML for the new page. This is called server-side rendering.
However, in modern spas, client-side rendering takes its place. The browser loads the initial page, scripts (frames, libraries, application code) and style sheets for the entire application from the server. Page refresh is not triggered when the user navigates to another page. The PAGE URL is updated through the HTML5 History API. The browser retrieves the data needed for a new page from the server via an AJAX request, usually in JSON format. SPA then dynamically updates the page with JavaScript that was downloaded when the original page loaded. This model is similar to how native mobile apps work.
Benefits:
The user perception response is faster, and the user no longer sees the blank screen caused by page refresh when switching pages. Fewer HTTP requests are made to the server because the same resource does not have to be downloaded again for each page load. Separation of concerns between client and server. New clients can be created for different platforms (e.g. mobile phones, chatbots, smartwatches) without changing the server code. As long as the API is not modified, the code on the client and server can be modified separately.Copy the code
The bad:
The initial page load time is long due to the framework, application code, and resources required to load multiple pages. The server also needs to do the extra work of configuring all the request routes to a single entry point, and then the client takes over the route. SPA relies on JavaScript to render content, but not all search engines execute JavaScript during crawling and they may see empty content on your page. This inadvertently hurts your app's search engine optimization (SEO). However, when you build your app, in most cases SEO is not the most important factor, because not everything needs to be indexed by a search engine. To address this, you can either render your application on the server side or use a service like Prerender to "render your javascript in the browser, save static HTML, and return it to the crawler."Copy the code
33. You rightPromises
And itspolyfill
What is your level of mastery?
Learn how it works. A Promise is an object that may produce a result at some point in the future: the result of a successful operation or the cause of a failure (such as a network error). A Promise may be in one of three states: fulfilled, Rejected, or pending. A user can add a callback function to a Promise to handle the result of a successful operation or the cause of a failure.
Some common polyfills are $.deferred, Q, and Bluebird, but not all polyfills meet the specification. ES2015 supports Promises. Polyfills are not always needed now.
34. What are the pros and cons of promises instead of callback functions?
Pros: Avoid the inferno of unreadable callbacks. Sequential asynchronous code written using.then() is simple and readable. Writing parallel asynchronous code with promise.all () is easy. Cons: Slightly increased code complexity (this is debatable). In older browsers that don't support ES2015, you need to introduce Polyfill to use it.Copy the code
35. What tools and tricks do you use to debug JavaScript code?
React and Redux React Devtools Redux Devtools Vue Vue Devtools JavaScript Chrome Devtools debugger uses the balm console.log for debuggingCopy the code
36. What statements do you use to iterate over properties of objects and elements of arrays?
Object:
1. The for loop:for (var property inobj) { console.log(property); }. However, this also iterates through its inherited properties, and you need to add the obj.hasOwnProperty(Property) check before using it. 2. The Object. The keys () : the Object. The keys (obj). ForEach (function(property) { ... }). The object.keys () method returns an array of the given Object's own enumerable properties. 3. Object. GetOwnPropertyNames () : the Object getOwnPropertyNames (obj). ForEach (function(property) { ... }). Object. GetOwnPropertyNames () method returns a specified by the Object of all its attributes of the attribute name (including not enumerated attribute but does not include Symbol value as the name of the attribute) consisting of an array. For loops:for(var i = 0; i < arr.length; I++). A common mistake here is that var is function scoped rather than block-level scoped, and most of the time you want to iterate over variables in block-level scoped. ES2015 introduces block-level scopedletIt is recommended to use it. So it becomes:for (leti = 0; i < arr.length; I++). 5. The forEach: arr. ForEach (function(el, index) { ... }). This statement structure is sometimes more compact, because you don't have to use index if all you need is array elements. There are also every and some methods that let you terminate traversal early. For the most part, I prefer the.foreach method, but it depends on what you want to do.forLoops have greater flexibility, such as usagebreakTerminate the loop early, or increase the number of steps by more than one.Copy the code
36. Explain the difference between mutable and immutable objects.
What are examples of immutable objects in JavaScript? What are the advantages and disadvantages of immutability? How do you implement immutability in your own code? Mutable objects can be changed after creation.
Immutable objects cannot be changed after they are created.
In JavaScript, strings and numbers are Immutable by design. Immutable means keeping an object’s state unchanged, which has the advantage of making development easier, traceable, and test-friendly, reducing any possible side effects. However, whenever you want to add something to an Immutable object, it must first copy the existing value into a new instance, then add content to the new instance, and then return the new instance. This is bound to require more memory and computation than mutable objects. For example: Construct a pure function
const student1 = {
school: 'Baidu',
name: 'HOU Ce',
birthdate: '1995-12-15'}; const changeStudent = (student, newName, newBday) => {return{... Student, // use destruct name: newName, // override the name attribute birthDate: newBday, // override the birthdate attribute}; }; const student2 = changeStudent(student1,'YAN Haijing'.'1990-11-10');
// both students will have the name properties
console.log(student1, student2);
// Object {school: "Baidu", name: "HOU Ce", birthdate: "1995-12-15"}
// Object {school: "Baidu", name: "YAN Haijing", birthdate: "1990-11-10"}
Copy the code
37. Explain the difference between synchronous and asynchronous functions.
Synchronous functions block and asynchronous functions do not. In a synchronous function, the next sentence is executed after the statement is complete. In this case, the program can be evaluated precisely in terms of the order of statements, and if one of the statements takes a long time, the program’s execution will stall for a long time.
Asynchronous functions usually take a callback as an argument and continue on the next line immediately after calling the asynchronous function. The callback function is called only when the asynchronous operation is complete and the call stack is empty. Heavy load operations, such as loading data from a Web server or querying a database, should be done asynchronously so that the main thread can continue to perform other operations without blocking until the time-consuming operation is complete (in the browser, the interface would get stuck).
38. What is an event loop? What is the difference between a call stack and a task queue?
The event loop is a single-threaded loop that monitors the call stack and checks to see if any work is about to complete in the task queue. If the call stack is empty and there is a callback function in the task queue, the callback function is dequeued and pushed to the call stack for execution.
39. Please explainfunction foo() {}
andvar foo = function() {}
betweenfoo
The difference in the usage of.
The former is a function declaration, the latter is a function expression. The key difference is that a function declaration causes the body of a function to promote (with the same promoted behavior as a variable), but the body of a function expression does not. For more explanation of variable promotion, see the question on variable promotion above. If you try to call the function expression before defining it, you will get an Uncaught TypeError: XXX is not a function error.
The function declares foo(); //'FOOOOO'
function foo() {
console.log('FOOOOO'); } function expression foo(); // Uncaught TypeError: foo is not afunction
var foo = function() {
console.log('FOOOOO');
};
Copy the code
40. Uselet
,var
andconst
What’s the difference between creating a variable?
The scope of a variable declared with VAR is its current execution context, which can be a nested function or a variable declared outside of any function. Let and const are block-level scoped, meaning they can only be accessed within the nearest set of curly braces (function, if-else code block, or for loop).
function foo() {// All variables are accessible in the function var bar ='bar';
let baz = 'baz';
const qux = 'qux';
console.log(bar); // bar
console.log(baz); // baz
console.log(qux); // qux
}
console.log(bar); // ReferenceError: bar is not defined
console.log(baz); // ReferenceError: baz is not defined
console.log(qux); // ReferenceError: qux is not defined
if (true) {
var bar = 'bar';
let baz = 'baz';
const qux = 'qux'; } // All variables declared with var can be console.log(bar) in function scope; // bar //letConsole. log(baz) is not accessible outside the block in which they are defined; // ReferenceError: baz is not defined console.log(qux); // ReferenceError: Qux is not defined var will promote the variable, which means that the variable can be used before the declaration.letAnd const do not promote the variable. Using const in advance raises an error. console.log(foo); // undefined var foo ='foo';
console.log(baz); // ReferenceError: can't access lexical declaration 'baz' before initialization let baz = 'baz'; console.log(bar); // ReferenceError: can't access lexical declaration 'bar' before initialization
const bar = 'bar'; Repeating a declaration with var does not return an error, butletAnd const. var foo ='foo';
var foo = 'bar';
console.log(foo); // "bar"
let baz = 'baz';
let baz = 'qux'; // Uncaught SyntaxError: Identifier 'baz' has already been declared
letDiffers from const in that:letMultiple assignments are allowed, const only once. // This will not report an error.let foo = 'foo';
foo = 'bar'; // This will cause an error. const baz ='baz';
baz = 'qux';
Copy the code
41. Higher-order functions(who - order)
What is the definition of?
Higher-order functions are functions that take one or more functions as arguments, are used for data processing, and may return the function as a result. Higher-order functions are used to abstract operations that are repeated. A typical example is map, which takes an array and a function as arguments. Map uses this function to convert each element in the array and returns a new array containing the converted elements. Other common examples in JavaScript are forEach, filter, and reduce. Higher-order functions are used not only when you need to manipulate arrays, but also when many functions return new functions. Function.prototype.bind is an example.
Map example: Suppose we have an array of names and we need to convert each character to uppercase. const names = ['irish'.'daisy'.'anna']; Don't use higher-order functions method is this: const transformNamesToUppercase =function(names) {
const results = [];
for (let i = 0; i < names.length; i++) {
results.push(names[i].toUpperCase());
}
returnresults; }; transformNamesToUppercase(names); / / /'IRISH'.'DAISY'.'ANNA'] is used. The map (transformerFn) make the code more concise const transformNamesToUppercase =function(names) {
returnnames.map(name => name.toUpperCase()); }; transformNamesToUppercase(names); / / /'IRISH'.'DAISY'.'ANNA']
Copy the code
42. Please give a deconstruction(destructuring)
Object or array examples.
Destructuring is a new feature in ES6 that provides a succinct and convenient way to extract the values of objects or arrays and put them into different variables.
Const foo = ['one'.'two'.'three'];
const [one, two, three] = foo;
console.log(one); // "one"
console.log(two); // "two"
console.log(three); // "three"// Swap variableslet a = 1;
letb = 3; [a, b] = [b, a]; console.log(a); // 3 console.log(b); Const o = {p: 42, q:true };
const { p, q } = o;
console.log(p); // 42
console.log(q); // true
Copy the code
43.ES6
Can you give an example of a template string that provides great flexibility for generating strings?
Template literals are string literals that allow expressions to be embedded. You can use multi-line strings and string interpolation.
grammar
`string text`
`string text line 1 string text line 2`
`string text ${expression} string text`;
tag`string text ${expression}string text`; Example console.log(' string text line 1 string text line 2 '); //"string text line 1 string text line 2"
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}. `); //"Fifteen is 15 and\nnot 20."//show takes the rest argument as follows:let name = 'Joe'Age = 20, message = show${name}The age is${age}. `;functionshow(stringArr, ... values) {let output = ' ';
let index = 0;
for (; index < values.length; index++) {
output += stringArr[index] + values[index];
}
output += stringArr[index];
return output;
}
message; //"Let me introduce: Zhang SAN's age is 20."
Copy the code
44. Can you give an example of a Curry function? What are its benefits?
Currying is a mode in which a function with multiple arguments is broken into functions that, when called in series, will accumulate all required arguments one at a time. This technique helps write functional style code, making it more readable and compact. It is worth noting that for a function to be curried, it needs to start with a function and then decompose into a series of functions, each of which takes one argument.
function curry(fn) {
if (fn.length === 0) {
return fn;
}
function _curried(depth, args) {
return function(newArgument) {
if (depth - 1 === 0) {
returnfn(... args, newArgument); }return _curried(depth - 1, [...args, newArgument]);
};
}
return _curried(fn.length, []);
}
function add(a, b) {
return a + b;
}
var curriedAdd = curry(add);
var addFive = curriedAdd(5);
var result = [0, 1, 2, 3, 4, 5].map(addFive); // [5, 6, 7, 8, 9, 10]
Copy the code
45. What are the benefits of using the extended operator (spread), and how does it differ from using residual argument statements (REST)?
ES6’s extension operators are useful when coding function generics, because we can easily create copies of arrays and objects without using Object.create, slice, or other libraries. This language feature is often used in Redux and rx.js projects.
function putDookieInAnyArray(arr) {
return [...arr, 'dookie'];
}
const result = putDookieInAnyArray(['I'.'really'."don't".'like']); / / /"I"."really"."don't"."like"."dookie"]
const person = {
name: 'Todd', age: 29, }; const copyOfTodd = { ... person };Copy the code
The remaining argument statement in ES6 provides a shorthand that allows us to represent an indefinite number of arguments as an array. It’s like the opposite of the extension operator syntax, gathering data into arrays rather than deconstructing them. Residual argument statements play a big role in destructuring the assignment of function arguments, arrays, and objects.
functionaddFiveToABunchOfNumbers(... numbers) {returnnumbers.map(x => x + 5); } const result = addFiveToABunchOfNumbers(4, 5, 6, 7, 8, 9, 10); // [9, 10, 11, 12, 13, 14, 15] const [a, b, ...rest] = [1, 2, 3, 4]; // a: 1, b: 2, rest: [3, 4] const { e, f, ... others } = { e: 1, f: 2, g: 3, h: 4, }; // e: 1, f: 2, others: { g: 3, h: 4 }Copy the code
46. How do I share code between files?
This depends on the environment in which the JavaScript is executed.
On the client side (browser environment), all scripts can reference variables or functions as long as they are declared in the global scope (window). Alternatively, adopt asynchronous Module Definition (AMD) with RequireJS for more modular approaches.
On the server (Node.js), the common approach is to use CommonJS. Each file is treated as a module, and you can export variables and functions by attaching them to module.exports objects.
ES2015 defines a module syntax designed to replace AMD and CommonJS. This will eventually be supported in browsers and Node environments.
47. When are static class members used?
A static class member (property or method) is not bound to a specific instance of a class and has the same value no matter which instance references it. Static properties are usually configuration variables, while static methods are usually purely utility functions that do not depend on the state of the instance.
If there are any errors, please correct them in the comments section. If this article has helped you, please like 👍 and follow us at 😀.