AltSchool Of Engineering Tinyuka’24 Month 4 Week 5

Ikoh SylvaIkoh Sylva
9 min read

This week, we kicked off class with our usual revision of the previous session. If you missed it, feel free to check it out here! After that, we dove into Nullish Coalescing. Ready to explore? Let’s jump in!

Nullish Coalescing in JavaScript

The nullish coalescing operator (??) offers a streamlined way to handle values that may be null or undefined. It allows you to specify a default value when the primary value is not available.

The operator returns the left-hand side operand if it is not null or undefined. If the left-hand side is either of those, it returns the right-hand side operand instead.

Syntax:

expression1 ?? expression2

Example:

let userInput = null;
let defaultValue = "Default Name";
let result = userInput ?? defaultValue; // "Default Name"

In this example, since userInput is null, the result will take on the value of defaultValue. If userInput had a valid value (e.g., a string), result would be that value instead. This operator simplifies the process of providing fallback values in your code.

Conditional Branching in JavaScript

Conditional branching allows you to execute different actions based on specific conditions in your code. Here’s how you can implement it using various statements:

  1. If Statement: The if statement evaluates a condition and executes a block of code if the condition is true.

Syntax:

if (condition) {
  // Code to execute if condition is true
}

Example:

let score = 85;
if (score > 80) {
  console.log("Great job!"); // Output: Great job!
}
  1. If-Else Statement: The else clause executes if the if condition is false.

Syntax:

if (condition) {
  // Code if condition is true
} else {
  // Code if condition is false
}

Example:

if (score > 80) {
  console.log("Great job!");
} else {
  console.log("Keep trying!");
}
  1. Else If Statement: Use else if to check multiple conditions in sequence.

Syntax:

if (condition1) {
  // Code if condition1 is true
} else if (condition2) {
  // Code if condition2 is true
} else {
  // Code if both conditions are false
}

Example:

if (score > 90) {
  console.log("Excellent!");
} else if (score > 80) {
  console.log("Great job!");
} else {
  console.log("You can improve!");
}
  1. Switch Statement: The switch statement can replace multiple if checks, providing a cleaner approach to comparing a single value against various cases.

Syntax:

switch (expression) {
  case x:
    // Code block for case x
    break;
  case y:
    // Code block for case y
    break;
  default:
    // Code block if no cases match
}

Example:

let fruit = "apple";
switch (fruit) {
  case "banana":
    console.log("Yellow fruit.");
    break;
  case "apple":
    console.log("Red fruit."); // Output: Red fruit.
    break;
  default:
    console.log("Unknown fruit.");
}
  1. Conditional Operator (?): Also known as the ternary operator, it allows you to assign values based on a condition in a concise way.

Syntax:

condition ? expressionIfTrue : expressionIfFalse

Example:

let age = 18;
let status = age >= 18 ? "Adult" : "Minor"; // status is "Adult"

Loops in JavaScript

Loops are essential for executing a block of code multiple times based on specific conditions. Here’s an overview of the main types of loops in JavaScript:

  1. While Loop: The while loop continues to execute a block of code as long as a specified condition remains true.

Syntax:

while (condition) {
  // Code block to be executed
}

Example:

let count = 0;
while (count < 5) {
  console.log(count); // Outputs: 0, 1, 2, 3, 4
  count++;
}
  1. For Loop: The for loop is structured with three main components: initialization, condition check, and increment.

Syntax:

for (initialization; condition; increment) {
  // Loop body
}

Example:

for (let i = 0; i < 5; i++) {
  console.log(i); // Outputs: 0, 1, 2, 3, 4
}
  • Initialization is executed once before the loop starts.
  • Condition Check determines if the loop continues.
  • Increment updates the loop variable after each iteration.
  1. For...Of Loop: The for...of loop is used to iterate over iterable data structures, such as arrays, strings, maps, and sets.

Syntax:

for (let item of iterable) {
  // Loop body
}

Example:

let fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
  console.log(fruit); // Outputs: apple, banana, cherry
}
  1. For...In Loop: The for...in loop is designed to iterate over the properties of an object.

Syntax:

for (let property in object) {
  // Loop body
}

Example:

let person = { name: "Alice", age: 25 };
for (let key in person) {
  console.log(`${key}: ${person[key]}`); // Outputs: name: Alice, age: 25
}

Functions in JavaScript

Functions are blocks of code designed to perform specific tasks, allowing for code reuse and organization. Here’s a look at different ways to define functions in JavaScript:

  1. Function Declaration: A function can be declared using the following syntax:

Syntax:

function functionName(parameter1, parameter2, ...parameterN) {
  // Code to be executed
}

Example:

function greet(name) {
  console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!

Key Points:

  • The function keyword starts the declaration.
  • The function name follows, with parameters in parentheses.
  • The function body is enclosed in curly braces.
  • To execute the function, call it by name followed by parentheses.
  1. Outer and Local Variables:

    • Outer Variable: A variable declared outside a function is accessible within that function. This is known as a global variable.

Example:

let outerVar = 10;
function modifyOuter() {
  outerVar += 5; // Modifies the outer variable
}
modifyOuter();
console.log(outerVar); // Output: 15
    • Local Variable: A variable declared inside a function is only accessible within that function.

Example:

function localExample() {
  let localVar = 20;
  console.log(localVar); // Output: 20
}
localExample();
// console.log(localVar); // Error: localVar is not defined
  1. Function Expressions: Functions can also be defined as expressions, typically assigned to a variable. This allows for more flexibility.

Syntax:

let functionName = function(parameters) {
  // Function body
};

Example:

let multiply = function(a, b) {
  return a * b;
};
console.log(multiply(2, 3)); // Output: 6
  1. Arrow Functions: Arrow functions provide a concise syntax for creating functions, often used for shorter function expressions.

Syntax:

const functionName = (parameters) => {
  // Function body
};

Example:

const add = (x, y) => x + y;
console.log(add(3, 4)); // Output: 7

Code Quality

Code quality refers to a collection of practices aimed at ensuring that your code is easy to read, maintain, and reliable. Here are some essential aspects of maintaining high code quality:

  1. Linters: Linters are tools that analyze your code for potential errors, stylistic issues, and adherence to coding standards. They help catch problems early in the development process.

Example: ESLint is a popular linter for JavaScript that can enforce coding standards and identify common errors.

  1. Formatters: Formatters automatically adjust the formatting of your code to meet specified style guidelines, enhancing readability and consistency across the codebase.

Example: Prettier is a widely used code formatter that ensures code is consistently styled according to defined rules.

  1. Standards: Establishing coding standards provides guidelines for writing code, promoting consistency and best practices among team members.

Example: Adopting standards such as the Airbnb JavaScript Style Guide can help maintain uniformity in code structure and style.

  1. Types: Using static type checkers like TypeScript can enhance code quality by catching type-related errors at compile time, reducing runtime issues.

Example: TypeScript allows developers to define and enforce data types, leading to more predictable and reliable code.

  1. Debugging in the Browser: Modern browsers offer built-in developer tools that facilitate debugging, allowing developers to inspect code, set breakpoints, and analyze application performance.

Example: The Chrome DevTools can help identify issues in JavaScript code and monitor network requests.

  1. Writing Tests: Implementing automated tests ensures that code functions as intended and helps catch regressions when changes are made. This contributes to overall code reliability.

Example: Using frameworks like Jest or Mocha enables developers to write unit tests for their functions, ensuring they behave correctly.

  1. Performance: Regularly assessing and optimizing code performance is crucial for enhancing user experience and application efficiency. This involves identifying bottlenecks and optimizing resource usage.

Example: Tools like Lighthouse can analyze web applications and provide insights into performance improvements.

Data Types in JavaScript

JavaScript supports various data types and structures, each with its own methods and functionalities. Here’s an overview of the key data types and related concepts:

  1. Primitive Data Types:

Numbers: Represents both integer and floating-point values.

Example: let num = 42;

BigInt: A type for representing whole numbers larger than Number.MAX_SAFE_INTEGER.

Example: let bigInt = 1234567890123456789012345678901234567890n;

Strings: Sequence of characters used for text.

Example: let greeting = "Hello, world!";

  1. Arrays and Array Methods: Arrays are list-like objects that can hold multiple values. They come with various built-in methods for manipulation.

Example:

let fruits = ["apple", "banana", "cherry"];
fruits.push("date"); // Adds "date" to the array
  1. Iterables: Iterables are objects that can be iterated over, such as arrays, strings, and maps.

Example: Using a for...of loop to iterate over an array.

  1. Map and Set:

    • Map: A collection of key-value pairs where keys can be any data type.

Example:

let map = new Map();
map.set("name", "Alice");
    • Set: A collection of unique values.

Example:

let uniqueNumbers = new Set([1, 2, 2, 3]); // Contains 1, 2, 3

  1. WeakMap and WeakSet:

    • WeakMap: Similar to Map, but keys are weakly referenced, allowing for garbage collection if there are no other references.

    • WeakSet: Similar to Set, but only holds weak references to its objects.

  2. Object Methods: Object.keys(), Object.values(), and Object.entries() are useful for working with object properties.

Example:

let obj = { name: "Alice", age: 25 };
console.log(Object.keys(obj)); // ["name", "age"]
  1. Destructuring Assignment: A syntax for unpacking values from arrays or properties from objects into distinct variables.

Example:

let point = [10, 20];
let [x, y] = point; // x = 10, y = 20
  1. Date and Time: JavaScript provides the Date object for handling dates and times.

Example:

let now = new Date();

  1. Intl API and Temporal: The Intl API provides language-sensitive functionalities, such as formatting dates and numbers.

    The Temporal API (proposed) aims to handle date and time more effectively and accurately.

  2. JSON Methods: JSON (JavaScript Object Notation) methods include JSON.stringify() to convert objects to JSON strings and JSON.parse() to convert JSON strings back to objects.

Example:

let jsonString = JSON.stringify({ name: "Alice" }); // '{"name":"Alice"}'

Thank you for taking the time to read this! Remember, putting these concepts into practice starts with just a single line of code. I’d love to hear your thoughts, so feel free to share in the comments below!

I’m Ikoh Sylva, a passionate cloud computing enthusiast with hands-on experience in AWS. I'm documenting my cloud journey from a beginner’s perspective, and I hope to inspire others along the way. If you find my content valuable, please like and follow my posts, and consider sharing this article with anyone embarking on their own cloud journey.

Let’s connect on social media, I’d love to engage with you further!

LinkedIn Facebook X

6
Subscribe to my newsletter

Read articles from Ikoh Sylva directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ikoh Sylva
Ikoh Sylva

I'm a Mobile and African Tech Enthusiast with a large focus on Cloud Technology (AWS)