Boolean
, null
, undefined
, String
and Number
), always works with the value of this entity. That is, the value is written to the corresponding variable. If we are talking about an object (for example, these are Object
, Array
, Function
types), then when assigning it to a variable, a reference to it is written to it, the address where it is located in memory.var1
variable. After that, the variable var2
recorded the value of the variable var1
. Since the variable var1
is of the primitive type ( String
), then a copy of the string present in var1
var2
be written to var1
. This allows you to treat var2
as a variable that is completely independent of var1
, although it stores the same value as var1
. Writing var2
new value does not affect var1
. let var1 = 'My string'; let var2 = var1; var2 = 'My new string'; console.log(var1); // 'My string' console.log(var2); // 'My new string'
let var1 = { name: 'Jim' } let var2 = var1; var2.name = 'John'; console.log(var1); // { name: 'John' } console.log(var2); // { name: 'John' }
var2
variable, and what happens to it is reflected in the var1
variable as they store a reference to the same object. It is easy to imagine what this might lead to in real code if someone decides that the variables that store objects behave in the same way as variables that store values of primitive types. This is especially unpleasant, for example, in cases where a function is created that is designed to work with the object value passed to it, and this function unintentionally changes this value.createGreeter()
function returns an anonymous function that has access to the greeting
argument provided to the source function, which contains the string Hello
. The link to this anonymous function is written to the variable sayHello
. After this, how many times we call the sayHello()
function, it will always have access to the value of greeting
. In this case, access to greeting
will be only for an anonymous function, the link to which is recorded in sayHello
. function createGreeter(greeting) { return function(name) { console.log(greeting + ', ' + name); } } const sayHello = createGreeter('Hello'); sayHello('Joe'); // Hello, Joe
apiConnect()
), which, when first called, is passed the API access key. This function, in turn, returns an object containing several methods that use the API access key passed to apiConnect()
. In this case, the key is stored in the closure and it is no longer necessary to mention it when calling these methods. 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'); // API api.get('http://www.example.com/get-endpoint'); api.post('http://www.example.com/post-endpoint', { name: 'Joe' });
const obj = { name: 'Joe', food: 'cake' } const { name, food } = obj; console.log(name, food); // 'Joe' 'cake'
const obj = { name: 'Joe', food: 'cake' } const { name: myName, food: myFood } = obj; console.log(myName, myFood); // 'Joe' 'cake'
person
object to the introduce()
function. This is an example of how this construct is used when declaring a function to extract data from the object passed to it with parameters. By the way, if you are familiar with React, then you probably have already 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!"
Math.max()
method for this, but it cannot work with arrays. It takes independent numerical values as arguments. In order to extract its elements from an array, we use the spread operator, which looks like three points. const arr = [4, 6, -1, 3, 10, 4]; const max = Math.max(...arr); console.log(max); // 10
function myFunc(...args) { console.log(args[0] + args[1]); } myFunc(1, 2, 3, 4); // 3
map()
, filter()
and reduce()
allow you to transform arrays or reduce arrays to a single value (which can be an object).map()
method returns a new array containing the transformed values of the array being processed. How exactly they will be transformed is specified in the function passed to this method. const arr = [1, 2, 3, 4, 5, 6]; const mapped = arr.map(el => el + 20); console.log(mapped); // [21, 22, 23, 24, 25, 26]
filter()
method returns an array of elements, checking which values the function passed to this method returned true
. const arr = [1, 2, 3, 4, 5, 6]; const filtered = arr.filter(el => el === 2 || el === 4); console.log(filtered); // [2, 4]
reduce()
method returns a value that represents the result of processing all the elements of the array. const arr = [1, 2, 3, 4, 5, 6]; const reduced = arr.reduce((total, current) => total + current); console.log(reduced); // 21
find()
, findIndex()
and indexOf()
easy to confuse with each other. Below are explanations to help you understand their features.find()
method returns the first element of the array that matches the specified criteria. This method, having found the first suitable element, does not continue searching the array. const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const found = arr.find(el => el > 5); console.log(found); // 6
for
loops, such loops, when a necessary element is detected in the array, are interrupted using the break
instruction.findIndex()
method is very similar to find()
, but instead of returning the first matching element of the array, it returns the index of such an element. To better understand this method, take a look at the following example, which uses an array of string values. const arr = ['Nick', 'Frank', 'Joe', 'Frank']; const foundIndex = arr.findIndex(el => el === 'Frank'); console.log(foundIndex); // 1
indexOf()
method is very similar to the findIndex()
method, but it takes as an argument not a function, but an ordinary value. You can use it if you do not need complex logic when searching for the desired element of the array. const arr = ['Nick', 'Frank', 'Joe', 'Frank']; const foundIndex = arr.indexOf('Frank'); console.log(foundIndex); // 1
push()
, pop()
, shift()
and unshift()
are used to add new elements to arrays and to extract elements already existing in them from arrays. In this case, the work is performed with elements located at the beginning or at the end of the array.push()
method allows you to add elements to the end of an array. It modifies the array, and, upon completion of the work, returns the element 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); // 5
pop()
method removes the last element from an array. It modifies the array and returns the element removed from it. let arr = [1, 2, 3, 4]; const popped = arr.pop(); console.log(arr); // [1, 2, 3] console.log(popped); // 4
shift()
method removes the first element from the array and returns it. It also modifies the array for which it is called. let arr = [1, 2, 3, 4]; const shifted = arr.shift(); console.log(arr); // [2, 3, 4] console.log(shifted); // 1
unshift()
method adds one or more elements to the beginning of the array. It, again, modifies the array. At the same time, unlike the three other methods considered here, it 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); // 7
splice()
method changes the contents of an array, deleting existing elements or replacing them with other elements. He can also add new elements to the array. This method modifies the array.1
, delete 0
elements and add an element containing b
. let arr = ['a', 'c', 'd', 'e']; arr.splice(1, 0, 'b')
slice()
method returns a shallow copy of the array containing its elements, starting at the specified starting position and ending at the position preceding the specified ending position. If, when calling it, only the initial position is specified, it will return the entire array starting from this position. This method does not modify the array. It only returns the part of this array described when it is called. 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']
sort()
method sorts an array according to the condition specified by the function passed to it. This function takes two elements of the array (for example, they can be represented as parameters a
and b
), and comparing them returns if the elements are not to be interchanged, 0 if a
needs to be put at a lower index than b
is a negative number, and if b
to be put at a lower index than a
is a positive number. 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]
next()
method. Generators can be designed to return a limited number of values. If a similar generator returned all such values, then the next call to next()
will return undefined
. Generators designed to return an unlimited number of values using cycles can also be created. 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); // undefined
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 // ...
==
) and strict equality ( ===
) operators. The fact is that the operator ==
, before comparing values, performs the conversion of their types (which can lead to strange, at first glance, consequences), and the operator ===
does not perform type conversion. console.log(0 == '0'); // true console.log(0 === '0'); // false
const joe1 = { name: 'Joe' }; const joe2 = { name: 'Joe' }; console.log(joe1 === joe2); // false
joe1
is equal to joe2
since both variables store a reference to the same object. const joe1 = { name: 'Joe' }; const joe2 = joe1; console.log(joe1 === joe2); // true
console.log
function (exactly like this - without parentheses) is passed to the myFunc()
function as a callback function. This function sets the timer, upon triggering of which console.log()
is called and the string passed to the myFunc()
function is output to the console. function myFunc(text, callback) { setTimeout(function() { callback(text); }, 2000); } myFunc('Hello world!', console.log); // 'Hello world!'
then()
method, and for error handling, the catch()
method. 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); }); // Math.random() , , 0.9, : // "Success: Hooray!" // Math.random() , , 0.9, 0.9, : // "Error: On no!"
async
, an asynchronous function, and in it, using the await
keyword, we organize the waiting for the promise to greeter
. const greeter = new Promise((res, rej) => { setTimeout(() => res('Hello world!'), 2000); }) async function myFunc() { const greeting = await greeter; console.log(greeting); } myFunc(); // 'Hello world!'
Source: https://habr.com/ru/post/441566/
All Articles