12 JavaScript Concepts That Boost Your Development Skills

JavaScript is a complex language. If you are a JavaScript developer at any level, it is important to understand the basics. This article addresses 12 concepts that are important for any JS developer to understand, but by no means cover the full extent of what a JS developer needs to know.

1. Assign a variable with a value compared to a reference

Understanding how to assign variables in JavaScript is essential for writing bug-free JavaScript code. If you do not understand this, you can easily write code that inadvertently changes the values.

JavaScript always assigns variables by value. But this part is very important: when the assigned value is one of the five main types of JavaScript (ie Boolean, null, undefined, String and Number) the actual value is assigned. However, when the assigned value of an array is a function, or object, a reference is assigned to the object in memory.

Example; In the following code, var2 is equal to var1. Since var1 is the main type (String), var2 is set to the value of the strings var1 and can be thought of as quite different from var1 at this point. Accordingly, var2 redistribution has no effect on var1

  1. let var1 = 'My string';  
  2. let var2 = var1;var2 = 'My new string';console.log(var1);  
  3. // 'My string'  
  4. console.log(var2);  
  5. // 'My new string'  

Let's compare this with object allocation

  1. let var1 = { name: 'Jim' }  
  2. let var2 = var1;var2.name = 'John';console.log(var1);  
  3. // { name: 'John' }  
  4. console.log(var2);  
  5. // { name: 'John' }  

You may see how it can cause problems if you expect it to behave like assigning primary variables! This can be bad, especially when you create a function that inadvertently changes an object.

2. Closures

Closures are an important JavaScript template for private access to a variable. In this example, createGreeter returns an anonymous function that has access to greeting, "Hello". For all future uses, sayHello will have access to this greeting!

  1. function createGreeter(greeting) {  
  2.   return function(name) {  
  3.     console.log(greeting + ', ' + name);  
  4.   }  
  5. }const sayHello = createGreeter('Hello');  
  6. sayHello('Joe');  
  7. // Hello, Joe  

In a more realistic scenario, consider an initial apiConnect function (apiKey) that returns some of the methods that use the API key. In this case, apiKey needs to be prepared only once and does not need to be done again.

  1. function apiConnect(apiKey) {  
  2.   function get(route) {  
  3.     return fetch(`${route}?key=${apiKey}`);  
  4.   }  function post(route, params) {  
  5.     return fetch(route, {  
  6.       method: 'POST',  
  7.       body: JSON.stringify(params),  
  8.         headers: {  
  9.           'Authorization': `Bearer ${apiKey}`  
  10.         }  
  11.       })  
  12.   }  return { get, post }  
  13. }const api = apiConnect('my-secret-key');// No need to include the apiKey anymore  
  14. api.get('http://www.example.com/get-endpoint');  
  15. api.post('http://www.example.com/post-endpoint', { name: 'Joe' });  

3. Destructuring

This is a common way to extract properties from objects.

  1. const obj = {  
  2.   name: 'Joe',  
  3.   food: 'cake'  
  4. }const { name, food } = obj;console.log(name, food);  
  5. // 'Joe' 'cake'  

If you want to extract properties by another name, you can specify them using the following format.

  1. const obj = {  
  2.   name: 'Joe',  
  3.   food: 'cake'  
  4. }const { name: myName, food: myFood } = obj;console.log(myName, myFood);  
  5. // 'Joe' 'cake'  

In the following example, this method is used to pass the person object to the introduce function. In other words, this method can be used directly to send the extracted parameters to a function. If you are familiar with React, you have probably seen it before!

  1. const person = {  
  2.   name: 'Eddie',  
  3.   age: 24  
  4. }function introduce({ name, age }) {  
  5.   console.log(`I'm ${name} and I'm ${age} years old!`);  
  6. }console.log(introduce(person));  
  7. // "I'm Eddie and I'm 24 years old!"  

4. Spread syntax

The spread operator is a relatively simple concept in JavaScript. In the following example, Math.max cannot be applied to the arr array, because it cannot array as an argument; this method takes unique elements as arrays. The spread bar (...) is used to capture unique elements of an array.

  1. const arr = [4, 6, -1, 3, 10, 4];  
  2. const max = Math.max(...arr);  
  3. console.log(max);  
  4. // 10  

5. Syntax Rest

Let's talk about JavaScript rest syntax. You can use it to put any number of arguments passed to the function in an array.

  1. function myFunc(...args) {  
  2.   console.log(args[0] + args[1]);  
  3. }myFunc(1, 2, 3, 4);  
  4. // 3  

6. Array methods

JavaScript array methods can often provide incredible and beautiful ways to do the data conversion you need.

Here we cover one of the different array methods, which is organized with similar methods that are sometimes combined.

1. map, filter, reduce

There is some confusion about the methods of the map, filter, and reduce JavaScript array. There are handy methods for converting an array or returning a value together.

map: Returns an array in which each element is converted to an item specified by the function.

  1. const arr = [1, 2, 3, 4, 5, 6];  
  2. const mapped = arr.map(el => el + 20);console.log(mapped);  
  3. // [21, 22, 23, 24, 25, 26]  

filter: Returns an array of elements that returns the true function.

Reduce: Summarizes the values as specified in the function.

  1. const arr = [1, 2, 3, 4, 5, 6];  
  2. const reduced = arr.reduce((total, current) => total + current);console.log(reduced);  
  3. // 21  

7. Generators

Do not be afraid of *. The generator function specifies what the yield value is the next time the next () is called. You can have a limited number of yields after next () returns the undefined value, or returns an unlimited amount of values using a loop.

  1. function* greeter() {  
  2.   yield 'Hi';  
  3.   yield 'How are you?';  
  4.   yield 'Bye';  
  5. }const greet = greeter();console.log(greet.next().value);  
  6. // 'Hi'  
  7. console.log(greet.next().value);  
  8. // 'How are you?'  
  9. console.log(greet.next().value);  
  10. // 'Bye'  
  11. console.log(greet.next().value);  
  12. // undefined  

And use the generator for unlimited values:

  1. function* idCreator() {  
  2.   let i = 0;  
  3.   while (true)  
  4.     yield i++;  
  5. }const ids = idCreator();console.log(ids.next().value);  
  6. // 0  
  7. console.log(ids.next().value);  
  8. // 1  
  9. console.log(ids.next().value);  
  10. // 2  
  11. // etc...  

8. Identification operator (===) compared to equality operator (==)

Be sure to know the difference between the identification operator (===) and the parity operator (==) in JavaScript. The == operator performs a type conversion before comparing values, while the === operator does no type conversion before comparing.

  1. console.log(0 == '0');  
  2. // true  
  3. console.log(0 === '0');  
  4. // false  

9. Object comparison

A mistake most newcomers make is direct comparison of objects. Variables refer to references to objects in memory, not to the objects themselves. One way to compare them is to convert objects to JSON strings. This has one drawback: Object property ordering is not guaranteed. A safer way to compare objects is to use a library that specializes in deep comparison of objects, such as isEqual.

The following objects appear to be equal but point to different references.

  1. const joe1 = { name: 'Joe' };  
  2. const joe2 = { name: 'Joe' };console.log(joe1 === joe2);  
  3. // false  

Instead, the following code is evaluated correctly because one object is equal to another object and therefore refers to the same reference (there is only one object in memory).

  1. const joe1 = { name: 'Joe' };  
  2. const joe2 = joe1;  
  3. console.log(joe1 === joe2);  
  4. // true  

Be sure to read the value comparison with reference section above to fully understand the setting of a variable equal to another variable that points to an object in memory.

10. Callback functions

Many people are afraid of JavaScript callback functions! But they are simple. Let's take an example. The console.log function is sent to myFunc as a callback. Runs when setTimeout is complete. That's all there is to it!

  1. function myFunc(text, callback) {  
  2.   setTimeout(function() {  
  3.     callback(text);  
  4.   }, 2000);  
  5. }myFunc('Hello wor  

11. Promises

Once you understand JavaScript callbacks, you will soon find yourself in nested callbacks. This is where Promises comes in handy. Put your async logic in a Promise and resolve success, rejection or failure. Use "then" to manage success and catch to manage failure.

  1. const myPromise = new Promise(function(res, rej) {  
  2.   setTimeout(function(){  
  3.     if (Math.random() < 0.9) {  
  4.       return res('Hooray!');  
  5.     }  
  6.     return rej('Oh no!');  
  7.   }, 1000);  
  8. });myPromise  
  9.   .then(function(data) {  
  10.     console.log('Success: ' + data);  
  11.    })  
  12.    .catch(function(err) {  
  13.     console.log('Error: ' + err);  
  14.    });  
  15.      
  16. // If Math.random() returns less than 0.9 the following is logged:  
  17. // "Success: Hooray!"  
  18. // If Math.random() returns 0.9 or greater the following is logged:  
  19. // "Error: On no!"  

12. Async Await

When you get to JavaScript promises, you may want to ask for async await. In the following example, we create an async function and await the greeter promise inside it.

  1. const greeter = new Promise((res, rej) => {  
  2.   setTimeout(() => res('Hello world!'), 2000);  
  3. })async function myFunc() {  
  4.   const greeting = await greeter;  
  5.   console.log(greeting);  
  6. }myFunc();  
  7. // 'Hello world!'  

Conclusion

If you do not know any of these 12 concepts, you have probably grown at least a little bit of JavaScript knowledge and gained insight into each one. And if you know all of them, I hope this is an opportunity to practice and grow your knowledge. Good luck!


User:sinahabibi
1/25/2021
Visit:170
Java Script

Learn JavaScript Learn JavaScript Tips on JavaScript What you need to know about JavaScript Benefits of using JavaScript Mastery of JavaScript Strengthen your JavaScript skills Improve your JavaScript development skills Learn JavaScript concepts
You must be logged in to post a comment