JavaScript Concepts

JavaScript Concepts

Play this article

Hey Theređź‘‹, Javascript is everywhere. Millions of web pages are built on JS.

Let's discuss some basic concepts of javascript which are important to learn for any javascript developer.

Scope

Scope determines the accessibility of variables, objects and functions.

In Javascript, a variable has 3 types of scope:

  • Block Scope

      var weatherToday = "Cool";
      const weather = () => console.log(weatherToday); // Cool
      weather();
      console.log(weatherToday); // Cool
    
  • Function Scope

      // Variables defined inside a function are not accessible (visible) from outside the function.
       function myFunction() {
        var carName = "Volvo";   // Function Scope
      }
    
  • Global Scope

      // Global variables can be accessed from anywhere in a JavaScript program.
    
      var x = 2;
    

Hoisting

Hoisting in Javascript is a behavior in which a function or variable can be used before declaration.

In terms of variable and constant keyword var is hoisted, and let and const does not allow hoisting.

test = 6;
// using test before declaring
console.log(test);
var test;

Closures

Closure means that an inner function always has access to the variable of its outer function, even after the outer function has returned.

cons first = () => {
   let greet = "Hello";
   const second = () => console.log(greet);
   return second;
}

const newFun = first(); //Hello

Callbacks

A callback function can be defined as a function passed into another function as a parameter.

//function
function greet (name, callback) {
console.log('Hi' + ' ' + name);
callback();
}
//callback function
function callMe() {
   console.log('I am callback Function');
}
// passing function as an argument 
greet('Peter', callMe);

Promises

Promises are a good way to handle asynchronous operations.

  • It's used to find out if the asynchronous operation is completed or not.

  • A promise may have one of three states Pending, Fulfilled, or Rejected.


Async & Await

Stop and Wait until something is resolved.

  • We use the async keyword to represent that the function is asynchronous.

The async function returns a promise.

const showPost = async () => {
    const res = await fetch('https:xyz.com/post')
}
showPost();

Conclusion

I hope the information provided was helpful and informative. If you have any further questions or need clarification, feel free to leave a comment or reach out to me through Twitter or LinkedIn. It would be great to connect and continue the conversation.

đź‘‹Thank you for taking the time to read this article. See You next time!

Don't forget to Subscribe to My Newsletter.

Did you find this article valuable?

Support Prathamesh Patil by becoming a sponsor. Any amount is appreciated!