7 Basic Javascript Concepts You Can’t Ignore

by xthemes content creator
17 minutes read

Article courtesy of author Son Duong

Basic Javascript concepts you need to know

1. Commitments

The reference to Javascript refers to the concept of asynchronous programming. So how to run the application on the right thread you want? The callback concept was born.

However, when you use callback indiscriminately, it leads to callback hell. It’s a very bad smell, making source code hard to read, hard to maintain, and prone to bugs.

tao cv online cn

To solve the problem of callback hell, people came up with Promises.

A Promise is a special mechanism in JavaScript that helps you perform asynchronous tasks without callback hell or pyramid of doom.

Promises are at the heart of the world of Javascript asynchronous programming. Understanding how it works and using it correctly is essential to building modern core javascript applications.

I’ll take an example of Callback hell:

api.getUser('pikalong', function(err, user) {
  if (err) throw err
  api.getPostsOfUser(user, function(err, posts) {
    if (err) throw err
    api.getCommentsOfPosts(posts, function(err, comments) {
      // vân vân và mây mây...
    })
  })
})

And use Promise to handle callback hell like this:

api.getUser('pikalong')
  .then(user => api.getPostsOfUser(user))
  .then(posts => api.getCommentsOfPosts(posts))
  .catch(err => { throw err })

Have you ever seen more handsome code!

2. Async/Await

Although writing code using promises makes the source code cleaner. However, if you are not careful, you can still be promised hell. “Avoid the melon husk and welcome the coconut husk”.

Additionally, if you are familiar with sequential programming languages ​​like PHP, Java, etc., accessing Javascript will be torture.

Thus, Async/Await was born. The Async/Await keyword helps Javascript source code to run sequentially from top to bottom. Thanks to it, you can write asynchronous code in a synchronous way.

Here is an Async/Await example:

async function() {
  try {
    const user = await api.getUser('pikalong')
    const posts = await api.getPostsOfUser(user)
    const comments = await api.getCommentsOfPosts(posts)

    console.log(comments)
  } catch (err) {
    console.log(err)
  }
}

It should be noted that the return result of an async function is always a Promise.

Both Promises and Async/Await are now supported by all modern browsers (except IE11). On the server side (Nodejs), both Promise and Async/Await are supported by the latest version of Nodejs.

3. Get it

To make a request from the client to the server to get data. You have many ways, using Ajax for example. Alternatively, you can also use fetch().

A modern application, perhaps indispensable connection to the server. Therefore, fetch() used by many.

Fetch API is a simple API for sending and receiving requests using js. Fetch() similar to XMLHttpRequest, but more modern fetch() returning the Promise.

For your use fetch() combined with Async / Await or Promise to make the code “cleaner”.

To make it easier to imagine, I take a simple example as follows:

async function getRedditJSON () {
  const response = await fetch('https://www.reddit.com/.json')

  return response.json()
}

getRedditJSON().then((data) => {
  console.log(data)
})

JavaScript Ho Chi Minh jobs for you!

4. Classes and Objects

If you used to mention Javascript but want to write object-oriented, it’s fun. But now it’s different. Many javascript frameworks are born based on components like ReactJs, VueJ… In particular, the existence of TypeScript brought the concepts of Interface, static type checking to Javascript.

With TypeScript, you can now write cleaner code, applying the SOLID philosophy to your source code. If you want to know how to apply the SOLID philosophy in Javscript, read this article: SOLID in Node.js

Because of this you need to understand and master the concepts of Classes/Objects like Java languages.

import React from 'react';

export interface SampleComponentProps {
  firstword: string,
  secondword: string
}

export interface SampleComponentState {
  phrase: string
}

class SampleComponent extends 
React.Component<SampleComponentProps, SampleComponentState> {
  readonly state: SampleComponentState = {
    phrase: ''
  }

  constructor(props: SampleComponentProps) {
    super(props)
    this.state = {
      phrase: `${props.firstword} ${props.secondword}`
    }
  }

  render () {
    const { phrase } = this.state
    return (
      <div>
        <p>{phrase}</p>
      </div>
    )
  }
}

export default SampleComponent;

Through the example above, you learned about components, Classes, Objects, Constructors, and TypeScript interfaces.

5. Import/export

As I said above, now more and more Javascript Frameworks are born and popular based on components. Commonly Facebook’s ReactJS, VueJS…

And to use the component in the project, you need to use multiple Import/Export. Although, these two concepts are very easy. But don’t be subjective and learn to skim. If you use it properly, Import/Export can greatly improve application performance and size.

6. Understand the keyword “It” correctly.

When you learn web application programming, you will understand the importance of asynchronous programming.

In the asynchronous world, the context of the executable code is constantly changing. As a developer, asynchronous code is much easier to understand when you understand how the “this” keyword works.

Do you have a clear understanding of how the “It” keyword works? If not, I recommend you to read the following articles:

7. Events and Event Listeners

What makes a web application unique is that it is always listening and responding to user interactions. There are many ways to handle this problem, which is where the event-driven design style was born to handle event data and responsive action.

For example, the MVC pattern with 2-way databinding has been around for a long time. In this design, the Model will be updated using the View via the controller. When the Model changes, the entire View changes as well and vice versa.

With this design, writing interface design code is really easy. However, the disadvantage is that it is difficult to debug when the interface is complex.

The event-driven philosophy was born to solve that. In this philosophy, elements in the View only update when the action occurs, and only update itself without updating the entire View.

It will be lame, when you learn about Javascript without knowing about Event, Event Listeners. When you learn about basic Javascript, you will see a lot of Events. Like this:

var myEl = document.getElementById('myelement');

myEl.addEventListener('click', function() {
    alert('Hello world');
}, false);

myEl.addEventListener('click', function() {
    alert('Hello world again!!!');
}, false);

#Conclusion

The above are very important basic concepts of Javascript. Therefore, I sincerely recommend that you spend some time to thoroughly understand these concepts.

Javascript is a hard language to learn, but once you know it, it’s great.

The future of javascript is very open, so I hope you enjoy this language.

The original article was posted on vntalking.com

See more:

Find the latest IT jobs on TopDev

Related Posts

Leave a Comment