Translator: Front-end wisdom
Original text: hackernoon.com/12-javascri…
Click “like” and then look, wechat search [Big Move the world] pay attention to this person without dACHang background, but with a positive attitude upward. In this paper, making github.com/qq449245884… Has been included, the article has been categorized, also organized a lot of my documentation, and tutorial materials.
Everyone said there was no project on your resume, so I found one and gave it away【 Construction tutorial 】.
JavaScript is a complex language. If you’re an advanced or junior JavaScript developer, it’s important to understand the basic concepts. This article introduces 12 concepts that are critical to JavaScript, but by no means all that a JavaScript developer needs to know.
1. Variable assignment (value vs reference)
Understanding how JavaScript assigns values to variables can help reduce unnecessary bugs. If you don’t understand this, you can easily write code that inadvertently changes values.
JavaScript always assigns values to variables by value. This part is important: the actual value is assigned when the specified value is one of JavaScript’s five basic types (that is, Boolean, NULL, undefined, String, and Number). However, when the specified value is Array, Function, or Object, a reference to an in-memory Object is assigned to the variable.
In the following code snippet, var2 is assigned using var1. Because var1 is a primitive type (String), the value of var2 is equal to the String value of var1 and can be considered completely different from var1 at this point. Therefore, reassigning var2 has no effect on var1.
let var1 = 'My string';
let var2 = var1;
var2 = 'My new string';
console.log(var1);
// 'My string'
console.log(var2);
// 'My new string'
Copy the code
Next, compare with object assignment.
let var1 = { name: 'Jim' }
let var2 = var1;
var2.name = 'John';
console.log(var1);
// { name: 'John' }
console.log(var2);
// { name: 'John' }
Copy the code
If you expect it to behave like a primitive assignment, you’ll probably have a problem! If you create a function that unintentionally changes an object, unexpected behavior can occur.
2. The closure
Closures are an important JavaScript pattern that allows private access to variables. In this case, createGreeter returns an anonymous function that accesses the parameter Greeting (in this case, “Hello”). On subsequent calls, sayHello will have access to this greeting!
function createGreeter(greeting) {
return function(name) {
console.log(greeting + ', ' + name);
}
}
const sayHello = createGreeter('Hello');
sayHello('Joe');
// Hello, Joe
Copy the code
In a more realistic scenario, you might imagine an initial function, apiConnect(apiKey), that returns methods that use API keys. In this case, the apiKey needs to be supplied only once.
function apiConnect(apiKey) { function get(route) { return fetch(`${route}? key=${apiKey}`); } function post(route, params) { return fetch(route, { method: 'POST', body: JSON.stringify(params), headers: { 'Authorization': `Bearer ${apiKey}` } }) } return { get, post } } const api = apiConnect('my-secret-key'); // No need to include the apiKey anymore api.get('http://www.example.com/get-endpoint'); api.post('http://www.example.com/post-endpoint', { name: 'Joe' });Copy the code
3. The deconstruction
JavaScript parameter deconstruction is a common way to extract the desired properties from an object.
const obj = {
name: 'Joe',
food: 'cake'
}
const { name, food } = obj;
console.log(name, food);
// 'Joe' 'cake'
Copy the code
If you want to extract an attribute by another name, you can do this:
const obj = {
name: 'Joe',
food: 'cake'
}
const { name: myName, food: myFood } = obj;
console.log(myName, myFood);
// 'Joe' 'cake'
Copy the code
Deconstruction is also often used directly to extract arguments passed to a function. If you’re familiar with React, you’ve probably seen this:
const person = { name: 'Eddie', age: 24 } function introduce({ name, age }) { console.log(`I'm ${name} and I'm ${age} years old! `); } console.log(introduce(person)); // "I'm Eddie and I'm 24 years old!"Copy the code
4. Expand the calculation
One of the most commonly used features of ES6 is expansion (…) In the following example, math.max cannot be applied to arR arrays because it does not take arrays as arguments, but it can pass individual elements as arguments. Expansion operator… Can be used to extract individual elements of an array.
const arr = [4, 6, -1, 3, 10, 4]; const max = Math.max(... arr); console.log(max); / / 10Copy the code
5. Remaining parameters
The residual argument syntax looks the same as the expansion syntax, except that the expansion syntax is for structuring arrays and objects; Residual arguments, on the other hand, are the opposite of the expansion operator, collecting multiple elements into an array.
function myFunc(... args) { console.log(args[0] + args[1]); } myFunc(1, 2, 3, 4); / / 3Copy the code
Rest Parameters and Arguments are different
- Arguments is a pseudo-array containing all arguments
- The rest of the arguments are standard arrays, and you can use array methods
6. Array methods
JavaScript array methods can often provide an incredibly elegant way to perform the required data transformations. As a StackOverflow contributor, I often see questions about how to manipulate arrays of objects in a certain way, and this is often the perfect use case for array methods.
Map, Filter, and Reduce
The JavaScript array methods Map, filter, and Reduce are easily confused, all of which are useful methods for converting arrays or returning aggregate values.
Map: Returns an array in which each element has been converted using the specified function.
const arr = [1, 2, 3, 4, 5, 6];
const mapped = arr.map(el => el + 20);
console.log(mapped);
// [21, 22, 23, 24, 25, 26]
Copy the code
Filter: Returns an array of elements that will be included only if the specified function returns true.
const arr = [1, 2, 3, 4, 5, 6]; const filtered = arr.filter(el => el === 2 || el === 4); console.log(filtered); / / (2, 4]Copy the code
Reduce: sums the value specified in the function
const arr = [1, 2, 3, 4, 5, 6]; const reduced = arr.reduce((total, current) => total + current); console.log(reduced); / / 21Copy the code
find, findIndex, indexOf
Find: Returns the first instance that matches the specified condition.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const found = arr.find(el => el > 5); console.log(found); / / 6Copy the code
Again, notice that although all elements after 5 satisfy the condition, only the first matching element is returned. When you find a match, you usually break the for loop, which is actually very useful in this case.
FindIndex: This is almost identical to find, but instead of returning the first matched element, it returns the index of the first matched element.
const arr = ['Nick', 'Frank', 'Joe', 'Frank']; const foundIndex = arr.findIndex(el => el === 'Frank'); console.log(foundIndex); / / 1Copy the code
IndexOf: Almost identical to findIndex, but instead of taking a function as an argument, it takes a simple value. Use this method when you need simpler logic and don’t need to use functions to check for matches.
const arr = ['Nick', 'Frank', 'Joe', 'Frank']; const foundIndex = arr.indexOf('Frank'); console.log(foundIndex); / / 1Copy the code
push, pop, shift, unshift
Push: This is a relatively simple method that adds an item to the end of an array. It modifies the array in place, and the function itself returns items added to the array.
let arr = [1, 2, 3, 4]; const pushed = arr.push(5); console.log(arr); // [1, 2, 3, 4, 5] console.log(pushed); / / 5Copy the code
Pop: This will remove the last item from the array. Again, it modifies the array in place, and the function itself returns the items removed from the array.
let arr = [1, 2, 3, 4]; const popped = arr.pop(); console.log(arr); // [1, 2, 3] console.log(popped); / / 4Copy the code
Shift: Removes the first item from the array. Again, it modifies the array in place. The function itself returns the item removed from the array.
let arr = [1, 2, 3, 4]; const shifted = arr.shift(); console.log(arr); // [2, 3, 4] console.log(shifted); / / 1Copy the code
Unshift: Adds one or more elements to the beginning of an array. Again, it modifies the array in place. Unlike many other methods, the function itself returns the new length of the array.
let arr = [1, 2, 3, 4]; const unshifted = arr.unshift(5, 6, 7); console.log(arr); // [5, 6, 7, 1, 2, 3, 4] console.log(unshifted); / / 7Copy the code
splice, slice
**splice: ** Changes the contents of the array by deleting or replacing existing elements and/or adding new elements. This method modifies the array itself.
The following code example says: Delete 0 elements at position 1 and insert B.
let arr = ['a', 'c', 'd', 'e'];
arr.splice(1, 0, 'b')
Copy the code
Slice: Returns a shallow copy of the array from the specified start position and the specified end position. If no end position is specified, the rest of the array is returned. Importantly, this method does not modify the array, but returns the desired subset.
let arr = ['a', 'b', 'c', 'd', 'e'];
const sliced = arr.slice(2, 4);
console.log(sliced);
// ['c', 'd']
console.log(arr);
// ['a', 'b', 'c', 'd', 'e']
Copy the code
sort
**sort: ** Sorts the array according to the provided function. This method modifies the array in place. If the function returns a negative number or 0, the order remains the same. If a positive number is returned, the element order is swapped.
let arr = [1, 7, 3, -1, 5, 7, 2];
const sorter = (firstEl, secondEl) => firstEl - secondEl;
arr.sort(sorter);
console.log(arr);
// [-1, 1, 2, 3, 5, 7, 7]
Copy the code
7. Generators
Generators are a special behavior, actually a design pattern, where we iterate over an ordered set of values by calling the **next() method. Imagine, for example, traversing an array [1,2,3,4,5] using a traverser. The first call to next() returns 1, the second call to next() returns 2, and so on. When all the values in the array are returned, calling the next()** method returns null or false or any other possible value to indicate that all elements in the array have been traversed.
function* greeter() { yield 'Hi'; yield 'How are you? '; yield 'Bye'; } const greet = greeter(); console.log(greet.next().value); // 'Hi' console.log(greet.next().value); // 'How are you? ' console.log(greet.next().value); // 'Bye' console.log(greet.next().value); // undefinedCopy the code
Use the generator to generate an infinite number of values:
function* idCreator() {
let i = 0;
while (true)
yield i++;
}
const ids = idCreator();
console.log(ids.next().value);
// 0
console.log(ids.next().value);
// 1
console.log(ids.next().value);
// 2
// etc...
Copy the code
8. Identity operator (===) and equality operator (==)
It’s important to know the difference between the identity operator (===) and the equality operator (==) in JavaScript! The == operator does no casting before comparing values, while the === operator does no casting before comparing values.
console.log(0 == '0');
// true
console.log(0 === '0');
// false
Copy the code
9. Object comparison
The mistake I see new to JavaScript making is comparing objects directly. A variable points to a reference to an object in memory, not the object itself! One way to actually compare them is to convert the object to a JSON string. This has one drawback: object attribute order is not guaranteed! A safer way to compare objects is to introduce libraries dedicated to deep object comparisons (for example, lodash’s isEqual).
The objects below look equal, but they actually point to different references.
const joe1 = { name: 'Joe' };
const joe2 = { name: 'Joe' };
console.log(joe1 === joe2);
// false
Copy the code
Instead, the following evaluates to true because one object is set to be equal to the other and therefore points to the same reference (there is only one object in memory).
const joe1 = { name: 'Joe' };
const joe2 = joe1;
console.log(joe1 === joe2);
// true
Copy the code
Instead, the following evaluates to true because one object is set to equal the other and therefore points to the same reference (there is only one object in memory).
const joe1 = { name: 'Joe' };
const joe2 = joe1;
console.log(joe1 === joe2);
// true
Copy the code
10. Callback functions
Many people are intimidated by JavaScript callbacks! They’re very simple. Let me give you an example. The console.log function is passed to myFunc as a callback. It executes when setTimeout completes.
function myFunc(text, callback) { setTimeout(function() { callback(text); }, 2000); } myFunc('Hello world! ', console.log); // 'Hello world! 'Copy the code
11. Promises
Once you understand JavaScript callbacks, you can quickly find yourself in callback hell. At this point, you can use promises, wrapping asynchronous logic in promises, using “then” to handle success in resolve or reject, and using catch to handle exceptions.
Const myPromise = new Promise(function(res, rej) {setTimeout(function(){if (math.random () < 0.9) {return res('Hooray! '); } return rej('Oh no! '); }, 1000); }); myPromise .then(function(data) { console.log('Success: ' + data); }) .catch(function(err) { console.log('Error: ' + err); }); If Math. Random () returns less than 0.9 the following is logged: // "Success: Hooray!" // If Math. Random () returns 0.9 or the following is logged: // "Error: On no!"Copy the code
12. Async/Await
After mastering the use of promises, you might also like async await, which is just a “syntactic sugar” based on promises. In the following example, we create an async function and await greeter Promise.
const greeter = new Promise((res, rej) => { setTimeout(() => res('Hello world! '), 2000); }) async function myFunc() { const greeting = await greeter; console.log(greeting); } myFunc(); // 'Hello world! 'Copy the code
Your likes are my motivation to keep sharing good things.
communication
This article is updated every week, you can search wechat “big move the world” for the first time to read and urge more (one or two earlier than the blog hey), this article GitHub github.com/qq449245884… It has been included and sorted out a lot of my documents. Welcome Star and perfect. You can refer to the examination points for review in the interview.