JavaScript Topics Before ReactJS

1. Variables and Data Types

a). let, const and var:

Understanding the differences and appropriate use cases

  • var: The traditional way to declare variables in JavaScript, which has function-level scope and can be redeclared. Variables declared with var are hoisted, meaning they are initialized at the top of their scope. However, var is prone to issues with scope leakage due to its function-level scope, and thus is less commonly used in modern JavaScript.
  • let: Introduced in ES6, let provides block-level scope, meaning the variable is confined to the nearest enclosing block (like within a function or an if block). Unlike var, variables declared with let cannot be redeclared but can be reassigned.
  • const: Also introduced in ES6, const works like let with block-level scope but is used to declare variables that cannot be reassigned after their initial value is set. However, while the variable itself cannot be reassigned, if the value is an object or an array, its properties or elements can still be modified.
b). Primitive Types:

String, Number, Boolean, Null, Undefined, Symbol

  • String: Represents a sequence of characters, such as “hello” or ‘world’. Strings in JavaScript are immutable, meaning once a string is created, it cannot be changed, though you can create new strings based on modifications.
  • Number: Represents numeric values, both integers and floating-point numbers (e.g., 42, 3.14). JavaScript only has one number type.
  • Boolean: Represents a logical entity and can have only two values: true or false. These are often used in conditional statements.
  • Null: Represents an intentional absence of any object value. It is often assigned to a variable to indicate that it does not point to any object.
  • Undefined: Represents a variable that has been declared but not yet assigned a value. This often indicates a lack of initialization.
  • Symbol: Introduced in ES6, a Symbol is a unique and immutable primitive value that can be used as the key for object properties.
c). Complex Types:

Object and Arrays

  • Object: An object is a collection of key-value pairs, where each key (also called a property) maps to a value (which can be a primitive type, array, or another object). Objects are used to group related data and functionality together.
    • e.g. { name: “John”, age: 30 }
  • Array: An array is an ordered list of values (known as elements), which can be of any type
    • e.g., [1, “two”, true]
  • Arrays come with many built-in methods for adding, removing, or manipulating their elements.

2. Functions

a). Functional Declaration and Expressions

Traditional Functions vs Arrow Functions

  • Function Declaration: A named function that is defined using the function keyword. It can be called before its definition due to hoisting. (e.g., function greet() { console.log(“Hello”); }).
  • Function Expression: A function defined within an expression, typically assigned to a variable. Unlike function declarations, function expressions are not hoisted.
    • e.g., const greet = function() { console.log(“Hello”); };
  • Arrow Function: A more concise way to write function expressions introduced in ES6. Arrow functions have a lexical this, meaning they do not bind their own this but inherit it from the parent scope. They are often used for shorter functions.
    • e.g., const greet = () => console.log(“Hello”);
b). Callback Functions

Functions passed as arguments to other functions

A callback function is a function passed as an argument to another function, which is then executed inside the outer function. This is a common pattern in asynchronous operations such as handling events or making API calls.

e.g.: setTimeout(() => console.log(“Time’s up!”), 1000);

c). Higher-Order Functions

Functions that return other functions or take them as arguments

A higher-order function is a function that accepts another function as an argument or returns a function as its result. They are a powerful feature of functional programming. Common higher-order functions include:

  • map: Applies a given function to each element of an array and returns a new array with the results.
  • filter: Filters out elements of an array based on a condition, returning only the elements that pass the condition.
  • reduce: Reduces an array to a single value by applying a function to each element, often used for summing or combining data.

3. ES6+ Features

a). Template Literals

Using backticks for string interpolation: Template literals, introduced in ES6, allow for embedding variables and expressions into strings using backticks (`) and ${} syntax. This replaces the need for concatenation.

For Example:

let name = “John”;

console.log(`Hello, ${name}!`);

b). Destructuring

Extracting values from arrays or properties from objects.

Destructuring allows you to unpack values from arrays or properties from objects into distinct variables.

For example:

const [x, y] = [10, 20]; // Array restructuring

const {name, age} = {name: “John”, age: 30}; // Object destructuring

c). Spread and Rest Operators

… for expanding or collecting elements

The spread operator (…) is used to expand elements from an array or object into individual elements.

Example:

let arr = [1, 2, 3];

let newArr = […arr, 4, 5];

// [1, 2, 3, 4, 5]

 

The rest operator (…) is used to collect arguments into an array or object.

Example:

function sum(…numbers) {

         return numbers.reduce((acc, num) => acc + num, 0);

}

d). Modules

import and export for modular code

ES6 introduced the ability to split code into modules, allowing functions, objects, or values to be imported and exported between files.

Example:

// Exporting

export const PI = 3.14;

// Importing

import { PI } from ‘./math.js’;

 

4. Asynchronous JavaScript

a). Promises

Handling asynchronous operations

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It can be in one of three states: pending, fulfilled, or rejected. Promises allow you to chain asynchronous tasks in a readable way using .then() and .catch().

Example:

fetch(url) .then(response => response.json())

.then(data => console.log(data))

.catch(error => console.error(error));

b). Async/Await

Syntactic sugar for working with promises.

Async/Await simplifies working with promises by allowing you to write asynchronous code that looks synchronous. It relies on async functions, and await is used to pause execution until a promise is resolved.

Example:

async function fetchData() {

try {

       const response = await fetch(URL);

       const data = await response.json();

       console.log(data);

}

catch (error) {

       console.error(error);

}}

c). Fetch API

Making network requests

The Fetch API is a modern way to make network requests in JavaScript, returning a promise that resolves with the response data. It is a more powerful and flexible replacement for the older XMLHttpRequest method.

Example:

fetch(‘https://api.example.com/data’)

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.error(‘Error:’, error));

5. DOM Manipulation

a). Selecting Elements

document.querySelector, document.getElementById, etc.

You can select elements from the DOM (Document Object Model) using various methods:

  • document.querySelector: Selects the first matching element (e.g., document.querySelector(‘.class’)).
  • document.querySelectorAll: Selects all matching elements (e.g., document.querySelectorAll(‘div’)).
  • document.getElementById: Selects an element by its ID (e.g., document.getElementById(‘myId’)).
b). Event Handling

Adding event listeners and handling events

You can add event listeners to elements to handle user actions (e.g., clicks, key presses):

Example:

document.getElementById(‘myButton’).addEventListener(‘click’, function() { alert(‘Button clicked!’); });

c). Updating the DOM

Changing the content and structure of the DOM

JavaScript allows you to modify the DOM by changing element content, adding/removing elements, or updating attributes:

Example:

document.getElementById(‘myText’).textContent = ‘New Text’;

6. Object-Oriented Programming (OOP)

a). Classes and Objects: Creating and using classes

In JavaScript, a class is a blueprint for creating objects, introduced in ES6.

Example:

class Person {

     constructor(name, age) {

                  this.name = name;

                  this.age = age;

}

greet() {

     console.log(`Hello, my name is ${this.name}`);

}

}

const john = new Person(‘John’, 30);

john.greet();

b). Inheritance: Extending classes

Inheritance allows a class to inherit properties and methods from another class, using the extends keyword:

Example:

class Student extends Person {

      constructor(name, age, grade) {

                   super(name, age);

                   this.grade = grade;

}}

c). this Keyword: Understanding the context of this

The this keyword refers to the context in which a function is executed. In object-oriented programming, it typically refers to the instance of the object that the method is called on. In arrow functions, this is lexically bound, meaning it refers to the context in which the arrow function was defined.

7. Error Handling

a) Try/Catch: Handling exceptions

The try/catch block allows you to handle errors that occur during execution. If an error is thrown in the try block, execution jumps to the catch block:

Example:

try {

  // Code that may throw an error }

catch (error) {

           console.log(‘Error occurred:’, error.message);

}

b). Throwing Errors: Creating custom error messages

You can use the throw keyword to manually throw an error in your code, typically in combination with try/catch to handle specific scenarios:

Example:

throw new Error(‘Something went wrong);

8. Miscellaneous

a) Closures: Functions that remember their lexical scope

A closure is a function that has access to variables from its outer scope, even after the outer function has returned. This enables functions to “remember” the environment they were created in:

function outer() {

               let count = 0;

               return function inner() {

                       count++;

                       return count; };

}

const increment = outer();

console.log(increment()); // 1

console.log(increment()); // 2

b). Hoisting: Understanding variable and function hoisting

Hoisting refers to JavaScript’s behavior of moving declarations (but not initializations) to the top of their scope before code execution. This is why you can call functions declared using function before their definition. However, variables declared with let or const are not hoisted in the same way as var.

b). Scope: Block, function, and global scope

Scope defines where variables and functions are accessible:

Block scope: Variables declared with let or const are only accessible within the block (e.g., if, for).

Function scope: Variables declared with var are function-scoped, meaning they are accessible throughout the entire function.

Global scope: Variables declared outside of any function or block are accessible globally throughout the entire script.

2 thoughts on “JavaScript Topics Before ReactJS”

Leave a Comment