JavaScript 101

The Fundamentals You Need to Know

JavaScript 101

Introduction

JavaScript is a versatile and powerful programming language that is essential for building modern web applications. Whether you're a beginner or an experienced developer, having a strong understanding of JavaScript fundamentals is crucial. In this blog post, we'll explore some key concepts in JavaScript, including variable declarations (let, const, var), callback functions, asynchronous programming with Promises and async/await, and array methods like filter and map. By the end of this post, you'll have a solid understanding of these fundamental concepts, which will help you write cleaner, more efficient JavaScript code. Let's dive in!

Understanding let, const, and var

In JavaScript, let, const, and var are used to declare variables, but they have some differences in how they behave.

let:

  • Use let when you want to declare a variable that can be reassigned later.

  • Variables declared with let are block-scoped, which means they only exist within the block of code where they are defined.

  • Example:

      let age = 30;
      if (true) {
          let age = 40;
          console.log(age); // Output: 40
      }
      console.log(age); // Output: 30
    

const:

  • Use const when you want to declare a variable that will not be reassigned.

  • Variables declared with const are also block-scoped.

  • Example:

      const pi = 3.14159;
      pi = 3.14; // This will cause an error
    

var:

  • var was traditionally used to declare variables in JavaScript before let and const were introduced.

  • Variables declared with var are function-scoped, meaning they are accessible throughout the entire function in which they are declared.

  • Example:

      var count = 10;
      if (true) {
          var count = 20;
          console.log(count); // Output: 20
      }
      console.log(count); // Output: 20
    

In general, it's recommended to use let and const instead of var because they provide better scoping rules and help prevent bugs in your code. Use let when you need to reassign a variable, and use const when you want to declare a variable that won't change.

Understanding Loops

Loop are used in programming to repeat a block of code until a certain condition is met. In JavaScript, there are several types of loop, but the most common ones are for loop, while loop, and do-while loop. Let's explore each of these:

1. for loop:

  • The for loop is used to repeat a block of code a certain number of times.

  • It consists of three parts: initialisation, condition, and iteration.

  • Example:

      for (let i = 0; i < 5; i++) {
          console.log(i); // Outputs 0, 1, 2, 3, 4
      }
    
      // i = 0 -> Initialisation 
      // i < 5 -> Condition
      // i++ -> Iteration
    

2. while loop:

  • The while loop repeats a block of code while a specified condition is true.

  • It's important to ensure that the condition will eventually become false to avoid an infinite loop.

  • Example:

      let i = 0; // Initialisation
      while (i <= 5) { // Condition
          console.log(i); // Outputs 0, 1, 2, 3, 4, 5
          i++; // Iteration
      }
    
      // Note: Condition become false if value of i > 5.
    

3. do-while loop:

  • The do-while loop is similar to the while loop, but it always executes the block of code at least once before checking the condition.

  • Example:

      let i = 0; // Initialisation
      do {
          console.log(i); // Outputs 0
          i++; // Iteration
      } while (i < 0); // Condition
    
      // It will execute `do` block first before checking condtion.
    

Loop are useful for iterating over arrays, processing lists of data, and performing repetitive tasks. However, it's important to use them carefully to avoid infinite loops and excessive resource consumption.

Understanding Functions

Functions are blocks of code that perform a specific task and can be reused throughout your code. They help make your code more readable and easier to maintain. Here's how you can create and use functions:

1. Defining a Function:

  • You can define a function using the function keyword followed by the name and a pair of parentheses ( ) containing any parameters that function may accept.

  • Example:

      // function name: greet and parameter: name
      function greet(name) {
          console.log(`Hello, ${name}!`);
      }
    

2. Calling a Function:

  • To call a function, simply use its name followed by a pair of parentheses ( ).

  • Example:

      greet("Dhiraj"); // Outputs: Hello, Dhiraj!
    

3. Returning Values:

  • Functions can also return a value using the return keyword. This allows you to use the result of the function elsewhere in your code.

  • If a return statement is not present in a function, the function will still execute its code but will not return any value. In languages like JavaScript, functions without an explicit return statement will return undefined by default.

  • Example:

      function add(a, b) {
          return a + b;
      }
      let sum = add(3, 5);
      console.log(sum); // Outputs: 8
    

4. Function Expressions:

  • In addition to the function declaration, you can also create functions using function expressions.

  • Example:

      const multiply = function(a, b) {
          return a * b;
      };
      let product = multiply(4, 6);
      console.log(product); // Outputs: 24
    

5. Arrow Functions (ES6):

  • Arrow functions provide a more concise syntax for writing functions, especially for simple, one-line functions.

  • Example:

      const square = (x) => x * x;
      console.log(square(5)); // Outputs: 25
    

Functions are a fundamental part of JavaScript programming and are essential for building complex applications. They allow you to encapsulate logic, improve code reusability, and make your code more organised.

6. Callback Functions:

A callback function is a function that is passed as an argument to another function and is executed after some operation has been completed. Callback functions are often used to handle asynchronous tasks, such as fetching data from a server or responding to user input. Here's a basic example to illustrate how callback functions work:

function fetchData(callback) {
    // Simulate fetching data from a server
    setTimeout(() => {
        const data = { name: "Dhiraj", age: 24 };
        callback(data); // Call the callback function with the fetched data
    }, 2000);
}

function displayData(data) {
    console.log(`Name: ${data.name}, Age: ${data.age}`);
}

fetchData(displayData);

In this example, the fetchData function simulates fetching data from a server asynchronously using setTimeout. It takes a callback function (displayData) as an argument and calls this function with the fetched data once the operation is completed. The displayData function then logs the data to the console.

Callback functions are essential in JavaScript for handling asynchronous tasks and are a fundamental concept in event-driven programming. They allow you to write code that can respond to events and handle asynchronous operations in a more flexible and efficient manner.

Async, Await, and Promises

Asynchronous operations are commonly handled using promises and the async and await keywords. Promises are objects that represent the eventual completion or failure of an asynchronous operation, while async and await are used to write asynchronous code that looks and behaves synchronous. Here's how you can use them:

1. Promises:

  • Promises are created using the Promise constructor, which takes a function with resolve and reject parameters.

  • Example:

      function fetchData() {
          return new Promise((resolve, reject) => {
              setTimeout(() => {
                  const data = { name: "Dhiraj", age: 24 };
                  resolve(data);
              }, 2000);
          });
      }
    
      fetchData().then(data => {
          console.log(`Name: ${data.name}, Age: ${data.age}`);
      });
    

2. async and await:

  • The async keyword is used to define a function as asynchronous, which allows the use of await inside it.

  • await keyword is used to pause the execution of an asynchronous function until a promise is resolved or rejected, and it returns the resolved value or throws the rejected value.

  • Example:

      async function fetchData() {
          return new Promise((resolve, reject) => {
              setTimeout(() => {
                  const data = { name: "Dhiraj", age: 24 };
                  resolve(data);
              }, 2000);
          });
      }
    
      async function displayData() {
          const data = await fetchData();
          console.log(`Name: ${data.name}, Age: ${data.age}`);
      }
    
      displayData();
    

In this example, the fetchData function returns a promise that resolves after 2 seconds. The displayData function is an asynchronous function that uses await to wait for the fetchData promise to resolve before displaying the data.

Using promises, async, and await allows you to write asynchronous code in a more readable and maintainable way, making it easier to handle complex asynchronous operations.

Basic Array Methods: filter, map

JavaScript provides several powerful array methods that make it easier to work with arrays. Commonly used methods are filter, map. Let's explore how these can be used:

1. filter Method:

  • The filter method returns a new array with all elements that pass the test implemented by the provided function.

  • Example:

      const numbers = [1, 2, 3, 4, 5, 6];
      const evenNumbers = numbers.filter(num => num % 2 === 0);
      console.log(evenNumbers); // Output: [2, 4, 6]
    

2. map Method:

  • The map method returns a new array by applying a function to each element of the original array.

  • Example:

      const numbers = [1, 2, 3, 4, 5];
      const doubledNumbers = numbers.map(num => num * 2);
      console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
    

In these examples, arrow functions are used to define the callback functions passed to the filter and map methods. Arrow functions are a more concise way to write functions and are particularly useful when working with array methods that require callback functions.

Conclusion

In this blog post, we've covered some fundamental concepts in JavaScript that every developer should be familiar with. We started by explaining the differences between let, const, and var, highlighting their respective use cases and scoping rules.

Next, we explored the concept of callback functions, which are essential for handling asynchronous operations and event-driven programming in JavaScript. We saw how callback functions can be passed as arguments to other functions and executed at a later time.

Then, we delved into the world of asynchronous programming with Promises, async, and await. Promises provide a way to handle asynchronous operations more elegantly, while async and await make asynchronous code look more synchronous and easier to read.

Finally, we discussed some powerful array methods like filter and map, which provide a concise syntax for writing functions.

By understanding these concepts and techniques, you'll be better equipped to write clean, efficient, and maintainable JavaScript code. Keep practicing and exploring new features to become a more proficient JavaScript developer.