Skip to main content

Fundamental JavaScript

Introduction to JavaScript and the web:

JavaScript is a programming language that is primarily used to create interactive and dynamic websites. It is a client-side programming language, which means that it runs on the user's web browser and not on the web server. JavaScript is used to add interactivity and dynamic behavior to web pages, such as form validation, image sliders, and modal windows.

JavaScript was first introduced in 1995 by Netscape and is now supported by all modern web browsers. It is an essential component of web development and is used in conjunction with HTML and CSS to create dynamic and engaging websites.

JavaScript is a high-level, interpreted programming language that is easy to learn and use. It is an object-oriented language, which means that it is based on the concept of objects and their properties and methods. It is also a versatile language and can be used for tasks such as creating web applications, browser automation, server-side programming, and more.

JavaScript is also closely integrated with web technologies such as HTML and CSS. HTML defines the structure and layout of a web page, while CSS is used for styling and presentation. JavaScript allows for interaction and dynamic behavior on the web page by manipulating the HTML and CSS.

In summary, JavaScript is an essential component of web development. It allows for the creation of interactive and dynamic websites, and is closely integrated with HTML and CSS. It's a versatile programming language that can be used for various tasks beyond the web, making it an important skill for any developer to have.

JavaScript syntax and data types:

JavaScript syntax and data types are the foundation of the language and understanding them is essential to working with JavaScript. This tutorial will cover the basics of JavaScript syntax and the different data types that are used in the language.

JavaScript Syntax

JavaScript uses a C-style syntax, which means that it uses curly braces {} to define blocks of code, and semicolons ; to separate statements. JavaScript also uses the var, let, and const keywords to declare variables.

Here is an example of a basic JavaScript program that declares a variable and assigns a value to it:

function (name){
let message = "Hello World! Hello " + name + ".";
console.log(message);
}

JavaScript Data Types

JavaScript has several data types that are used to represent different types of values. The most common data types in JavaScript are:

  • Number: Represents numbers, both integers and floating-point values.
let age = 25;
let price = 12.99;
  • String: Represents a sequence of characters. Strings must be enclosed in single or double quotes.
let name = "John Doe";
let message = 'Hello World!';
  • Boolean: Represents a true or false value.
let isAdmin = true;
let isLoggedIn = false;
  • Array: Represents a collection of values. Arrays are defined using square brackets [] and the values are separated by commas.
let colors = ['red', 'green', 'blue'];
let numbers = [1, 2, 3, 4, 5];
  • Object: Represents a collection of key-value pairs. Objects are defined using curly braces {} and the keys and values are separated by colons.
let person = {
name: 'John',
age: 25,
isAdmin: true
};
  • Null: Represents an empty or non-existent value.
let empty = null;
  • Undefined: Represents a variable that has been declared but has not been assigned a value.
let x;
console.log(x); // undefined

It's important to note that JavaScript is a loosely typed language, which means that a variable can hold any type of value and the type can be changed at any time.

Understanding JavaScript syntax and data types is essential to working with the language. By understanding the basics of JavaScript syntax, you can write and read JavaScript code effectively. Understanding the different data types will help you to choose the right data type for your variables and use them effectively in your code.

Variables and control flow

JavaScript variables are used to store data in the program and are essential to working with JavaScript. This tutorial will cover the basics of JavaScript variables and control flow.

JavaScript Variables

JavaScript variables are used to store data in the program. Variables are declared using the var, let, or const keyword, and are assigned a value using the assignment operator (=).

The var keyword is used to declare variables that are function scoped, while the let and const are block scoped. Variables declared with var can be re-declared and reassigned, while let and const can't be re-declared but can be reassigned.

Here is an example of declaring and assigning a value to a variable:

var name = "Lex";
let message = "Hello World";
const title = "JS Intro";

JavaScript also supports variable hoisting, which means that variables can be declared and used before they are defined in the code. It is recommended to use let and const instead of var to avoid hoisting and to have better control over the scope of the variables.

JavaScript Control Flow

JavaScript control flow refers to the order in which statements are executed in a program. JavaScript uses control flow statements such as if-else and switch-case to control the flow of execution.

JavaScript If-Else Statement

The if-else statement is used to execute a block of code based on a certain condition. The syntax for an if-else statement is:

if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}

For example:

let age = 25;
if (age >= 18) {
console.log("You are an adult");
} else {
console.log("You are not an adult");
}

JavaScript Switch-Case Statement

The switch-case statement is used to execute a block of code based on a certain value. The syntax for a switch-case statement is:

switch (expression) {
case value1:
// code to be executed if expression === value1
break;
case value2:
// code to be executed if expression === value2
break;
default:
// code to be executed if expression is not matched
}

For example:

let day = "Monday";
switch (day) {
case "Monday":
console.log("Today is Monday");
break;
case "Tuesday":
console.log("Today is Tuesday");
break;
default:
console.log("Today is not Monday or Tuesday");
}

JavaScript Loops

JavaScript supports loop statements such as for, while, and do-while loops.

The for loop is used to repeat a block of code a certain number of times, the while loop is used to repeat a block of code as long as a certain condition is true, and the do-while loop is used to repeat a block of code at least once and then check the condition to repeat again.

For example, the for loop:

for (let i = 0; i < 5; i++) {
console.log(i);
}

The while loop:

let i = 0;
while (i < 5) {
console.log(i);
i++;
}

The do-while loop:

let i = 0;
do {
console.log(i);
i++;
} while (i < 5);

It's important to note that JavaScript uses dynamic and loose typing, which means that the type of a variable can change during the execution of the program and the type of a variable is determined at runtime.

In conclusion, understanding JavaScript variables and control flow is essential to working with the language. By understanding how to declare and use variables and how to control the flow of execution in a program, you can write and read JavaScript code effectively. It's important to be aware of the scope of the variables, the type of the variables and the control flow statements to write clean and maintainable code.

Functions and scope

JavaScript functions and scope are essential concepts in the language. Functions are used to group and organize code, while scope refers to the accessibility of variables and functions in different parts of the program.

This guide will cover the basics of JavaScript functions and scope.

JavaScript Functions

JavaScript functions are used to group and organize code. Functions are defined using the function keyword and can accept input in the form of parameters and return output in the form of a return value.

Here is an example of a basic function in JavaScript:

function greet(name) {
console.log("Hello, " + name);
}

greet("John"); // Output: Hello, John

Functions can also be defined using arrow function syntax in ES6, which is more concise and easier to read.

let greet = (name) => { console.log("Hello, " + name); }
greet("John"); // Output: Hello, John

JavaScript functions can also accept multiple parameters. For example:

function add(a, b) {
return a + b;
}

let result = add(1, 2);
console.log(result); // Output: 3

Functions can also return multiple values by returning an array or an object. For example:

function getPerson() {
return {
name: "John",
age: 25
}
}

let person = getPerson();
console.log(person.name); // Output: John
console.log(person.age); // Output: 25

JavaScript also supports default parameters, which allows you to set default values for function parameters. For example:

function greet(name = "John") {
console.log("Hello, " + name);
}

greet(); // Output: Hello, John

JavaScript also supports rest parameters, which allows you to pass an arbitrary number of arguments to a function. The rest parameter must be the last parameter in the function. For example:

function add(a, b, ...numbers) {
let sum = a + b;
for (let number of numbers) {
sum += number;
}
return sum;
}

let result = add(1, 2, 3, 4, 5);
console.log(result); // Output: 15

It's also possible to use closures in javascript. A closure is a function object that has access to variables in its lexical scope, even when the function is invoked outside that lexical scope.

In conclusion, understanding JavaScript functions is essential to working with the language. By understanding how to define and use functions, how to pass and return values, how to use default and rest parameters, and how to use closures, you can write and read JavaScript code effectively. It's important to be aware of the scope of the variables and the functions to avoid naming conflicts and to write clean and maintainable code.

JavaScript Scope

JavaScript scope refers to the accessibility of variables and functions in different parts of the program. JavaScript has two types of scope: global scope and local scope.

  • Global scope refers to variables and functions that are accessible from anywhere in the program. Variables declared outside of a function are in the global scope.
let message = "Hello World";

function greet() {
console.log(message);
}

Local scope refers to variables and functions that are only accessible within a specific function or block of code. Variables declared inside a function are in the local scope.

function greet() {
let message = "Hello World";
console.log(message);
}

It's important to note that variables declared with the let and const keywords are block-scoped, which means that they are only accessible within the block of code in which they are defined. Variables declared with the var keyword are function-scoped, which means that they are only accessible within the function in which they are defined.

In conclusion, understanding JavaScript functions and scope is essential to working with the language. By understanding how to define and use functions and how to manage the scope of variables, you can write and read JavaScript code effectively. It's important to be aware of the scope of the variables to avoid naming conflicts and to write clean and maintainable code.

Arrays and Objects

JavaScript arrays and objects are important data structures that allow you to store and manipulate collections of data.

This tutorial will cover the basics of JavaScript arrays and objects.

JavaScript Arrays

JavaScript arrays are used to store collections of data. Arrays are created using the square bracket notation, with values separated by commas. Here is an example of an array:

let numbers = [1, 2, 3, 4, 5];

JavaScript Array Methods and Iterators

JavaScript arrays are dynamic, which means that you can add or remove elements from an array.

push()

For example, you can use the push() method to add an element to the end of an array:

numbers.push(6);
console.log(numbers); // Output: [1, 2, 3, 4, 5, 6]

pop()

You can also use the pop() method to remove the last element of an array:

numbers.pop();
console.log(numbers); // Output: [1, 2, 3, 4, 5]

JavaScript also provides various other array methods such as shift(), unshift(), slice(), splice(), concat(), join() etc.

shift()

The shift() method is used to remove the first element of an array and returns the removed element.

let first = numbers.shift();
console.log(first); // Output: 1
console.log(numbers); // Output: [2, 3, 4, 5]

unshift()

The unshift() method is used to add one or more elements to the beginning of an array and returns the new length of the array.

numbers.unshift(1);
console.log(numbers); // Output: [1, 2, 3, 4, 5]

slice()

The slice() method is used to extract a section of an array and returns a new array.

let subArray = numbers.slice(1, 3);
console.log(subArray); // Output: [2, 3]

splice()

The splice() method is used to add or remove elements from an array.

numbers.splice(1, 2, 10, 11);
console.log(numbers); // Output: [1, 10, 11, 4, 5]

concat()

The concat() method is used to merge two or more arrays and returns a new array.

let numbers2 = [6, 7, 8];
let combined = numbers.concat(numbers2);
console.log(combined); // Output: [1, 2, 3, 4, 5, 6, 7, 8]

join()

The join() method is used to join all elements of an array into a string and returns the resulting string.

let str = numbers.join(", ");
console.log(str); // Output: "1, 2, 3, 4, 5"

JavaScript provides several array iterators that allow you to perform specific actions on every element of an array. These iterators include forEach(), map(), filter(), reduce() and some(), every().

forEach()

The forEach() method is used to iterate through an array and perform a specific action on each element. For example, you can use the forEach method to print out the elements of an array:

let numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(element) {
console.log(element);
});
// Output: 1, 2, 3, 4, 5

map()

The map() method is used to create a new array with the results of calling a provided function on every element in the calling array. For example, you can use the map method to double the elements of an array:

let doubleNumbers = numbers.map(function(element) {
return element * 2;
});
console.log(doubleNumbers); // Output: [2, 4, 6, 8, 10]

filter()

The filter() method is used to create a new array with all elements that pass the test implemented by the provided function. For example, you can use the filter method to get the even numbers from an array:

let evenNumbers = numbers.filter(function(element) {
return element % 2 === 0;
});
console.log(evenNumbers); // Output: [2, 4]

reduce()

The reduce() method is used to apply a function to each element in an array and reduce the array to a single value. For example, you can use the reduce method to sum up the elements of an array:

let sum = numbers.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
});
console.log(sum); // Output: 15

some()

The some() method is used to check if at least one element in the array pass the test implemented by the provided function.

let hasEven = numbers.some(function(element) {
return element % 2 === 0;
});
console.log(hasEven); // Output: true

every()

The every() method is used to check if all elements in the array pass the test implemented by the provided function.

let allEven = numbers.every(function(element) {
return element % 2 === 0;
});
console.log(allEven); // Output: false

In conclusion, understanding and using JavaScript array iterators can help you write more efficient and effective code. These iterators are useful for tasks such as iterating through an array, transforming elements, filtering elements, reducing an array to a single value, and checking if elements pass a certain test. It's important to be aware of the different array iterators available in JavaScript to write clean and maintainable code.

JavaScript Objects

JavaScript objects are used to store collections of data in the form of key-value pairs. Objects are created using curly braces, with keys and values separated by colons. Here is an example of an object:

let person = {
name: "John",
age: 25
};

JavaScript objects are dynamic, which means that you can add or remove properties from an object. For example, you can add a new property to an object using dot notation:

person.gender = "male";
console.log(person); // Output: { name: "John", age: 25, gender: "male" }

You can also remove a property from an object using the delete keyword:

delete person.gender;
console.log(person); // Output: { name: "John", age: 25 }

You can access the properties of an object using the dot notation or the square bracket notation. The dot notation is used to access properties that have a valid identifier name. The square bracket notation is used to access properties that have a variable name or a special character in the name.

console.log(person.name); // Output: "John"
console.log(person["age"]); // Output: 25

Objects in JavaScript are also passed by reference, which means that when you assign an object to a variable, the variable holds a reference to the object and not a copy of the object.

Built-in Object Methods

JavaScript provides several built-in object methods that allow you to perform specific actions on an object. These methods include Object.keys(), Object.values(), Object.entries(), Object.assign(), Object.create(), Object.freeze(), Object.defineProperty(), Object.getOwnPropertyDescriptor() and Object.getPrototypeOf().

Object.keys()

The Object.keys() method returns an array of the object's own property names. For example:

let person = {
name: "John",
age: 25
};
console.log(Object.keys(person)); // Output: ["name", "age"]

Object.values()

The Object.values() method returns an array of the object's own property values. For example:

console.log(Object.values(person)); // Output: ["John", 25]

Object.entries()

The Object.entries() method returns an array of the object's own enumerable property [key, value] pairs. For example:

console.log(Object.entries(person)); // Output: [["name", "John"], ["age", 25]]

Object.assign()

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. For example:

let newPerson = Object.assign({}, person, {gender: "male"});
console.log(newPerson); // Output: { name: "John", age: 25, gender: "male" }

Object.create()

The Object.create() method is used to create a new object with the specified prototype object and properties. For example:

let newPerson = Object.create(person);
console.log(newPerson); // Output: {}

Object.freeze()

The Object.freeze() method is used to freeze an object. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. For example:

Object.freeze(person);
person.age = 30;
console.log(person.age); // Output: 25

Object.defineProperty()

The Object.defineProperty() method is used to add a new property or modify the attributes of an existing property on an object. For example:

let person = {};
Object.defineProperty(person, "name", {
value: "John",
writable: true,
enumerable: true,
configurable: true
});
console.log(person.name); // Output: "John"

Object.getOwnPropertyDescriptor()

The Object.getOwnPropertyDescriptor() method is used to retrieve the attributes of a property on an object. For example:

let descriptor = Object.getOwnPropertyDescriptor(person, "name");
console.log(descriptor);
/* Output:
{
value: "John",
writable: true,
enumerable: true,
configurable: true
}
*/

Object.getPrototypeOf()

The Object.getPrototypeOf() method is used to retrieve the prototype of an object. The prototype is the object that is used as the basis for the inheritance of properties and methods for an object. For example:

let person = { name: "John" };
console.log(Object.getPrototypeOf(person) === Object.prototype); // Output: true

In conclusion, understanding JavaScript arrays and objects is essential to working with the language. By understanding how to create, manipulate, and iterate over arrays and objects, you can store and manipulate collections of data effectively. It's important to be aware of the properties and methods of arrays and objects to write clean and maintainable code.

JavaScript Event handling and DOM manipulation

JavaScript Event handling and DOM manipulation are two important concepts in web development. They allow you to create interactive and dynamic websites by responding to user actions and manipulating the Document Object Model (DOM).

Event handling in JavaScript is the process of listening for and responding to user actions such as clicks, key presses, and form submissions. The basic syntax for event handling is to add an event listener to an element and define a callback function to handle the event. Here is an example of how to add a click event listener to a button element:

let button = document.querySelector("button");
button.addEventListener("click", function() {
console.log("Button was clicked!");
});

The DOM is a tree-like structure that represents the structure of a web page. It allows you to access and manipulate the elements of a page using JavaScript. For example, you can use the document.querySelector() method to select an element by its CSS selector and then use the .innerHTML property to change its content. Here is an example of how to change the text of a heading element:

let heading = document.querySelector("h1");
heading.innerHTML = "New heading text";

You can also use the document.createElement() method to create new elements and the .appendChild() method to add them to the DOM. Here is an example of how to create a new list item and add it to a list element:

let list = document.querySelector("ul");
let newItem = document.createElement("li");
newItem.innerHTML = "New list item";
list.appendChild(newItem);

You can also use the .classList property to add, remove, and toggle CSS classes on elements. Here is an example of how to toggle a class on a button element:

let button = document.querySelector("button");
button.classList.toggle("selected");

Asynchronous Programming and AJAX

JavaScript Asynchronous Programming and AJAX (Asynchronous JavaScript and XML) are two important concepts in web development that allow you to perform tasks and make requests without blocking the execution of the rest of your code.

JavaScript is a single-threaded language, which means that only one task can be executed at a time. However, with asynchronous programming, you can execute multiple tasks simultaneously. This can be achieved using callback functions, promises, and async/await.

Callback functions

Callbacks are functions that are passed as arguments to other functions and are executed after the main function has completed. They allow you to perform tasks asynchronously by providing a function that will be called when the task is completed. Here is an example of a callback function:

function printHello() {
console.log("Hello");
}
setTimeout(printHello, 1000);
console.log("World");

In this example, the function printHello will be called after 1 second, while the console.log("World") is executed immediately.

Promises

Promises are objects that represent the eventual completion (or failure) of an asynchronous operation, and its resulting value. A promise can be in one of three states: fulfilled, rejected, or pending. Here is an example of a promise:

let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Hello");
}, 1000);
});
promise.then((value) => {
console.log(value);
});
console.log("World");

In this example, the promise is fulfilled after 1 second, and the value "Hello" is passed to the then method, which logs the value to the console.

Async/await

Async/await is a more recent addition to JavaScript and allows you to write asynchronous code in a synchronous style. Here is an example of async/await:

async function getData() {
let response = await fetch('https://jsonplaceholder.typicode.com/users');
let data = await response.json();
console.log(data);
}
getData();

AJAX

AJAX (Asynchronous JavaScript and XML) is a technique for making requests to a server and updating parts of a web page without refreshing the whole page. It uses the XMLHttpRequest object to make requests and receive responses. Here is an example of an AJAX request:

let xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/users");
xhr.onload = function() {
if (xhr.status === 200) {
console.log(JSON.parse(xhr.responseText));
}
};
xhr.send();

Asynchronous programming and AJAX are important concepts in web development that allow you to perform tasks and make requests without blocking the execution of the rest of your code. They allow you to create more responsive and efficient web applications by using callback functions, promises, async/await and XMLHttpRequest object to handle async request. Understanding and mastering these concepts are key to building professional and high-performance web applications.

Working with JSON and APIs

Working with JSON and APIs (Application Programming Interfaces) in JavaScript is a common task for web developers. JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999.

JSON

To work with JSON in JavaScript, you can use the JSON.stringify() method to convert a JavaScript object to a JSON string, and the JSON.parse() method to convert a JSON string to a JavaScript object. Here is an example of converting a JavaScript object to a JSON string:

let person = { name: "John", age: 30 };
let jsonString = JSON.stringify(person);
console.log(jsonString); // Output: {"name":"John","age":30}

And here is an example of converting a JSON string to a JavaScript object:

let jsonString = '{"name":"John","age":30}';
let person = JSON.parse(jsonString);
console.log(person); // Output: { name: "John", age: 30 }

API

An API (Application Programming Interface) is a set of rules and protocols for building and interacting with software applications. Web APIs allow you to access data and functionality from external sources, such as databases and web services, using HTTP requests. To make API calls in JavaScript, you can use the fetch() function or a library like axios.

In JavaScript, you can use the fetch() method to make different types of API requests, such as GET, POST, PUT, PATCH, and DELETE. The fetch() method is a modern way to make HTTP requests and handle responses, and it is supported by most modern browsers.

GET

Here is an example of making a GET request to an API using the fetch() function:

fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(data => console.log(data))

This requests the data from the API endpoint and parse the response as json and logs it.

POST

Here is an example of making a POST request to an API using the fetch() method:

let data = { name: "John", age: 30 };
fetch("https://jsonplaceholder.typicode.com/users", {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(data => console.log(data))

This sends the data to the API endpoint and parse the response as json and logs it.

PUT

Here is an example of making a PUT request to an API using the fetch() method:

let data = { name: "John", age: 30 };
fetch("https://jsonplaceholder.typicode.com/users/1", {
method: "PUT",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(data => console.log(data))

This sends the data to the API endpoint and updates the resource with the given id and parse the response as json and logs it.

PATCH

Here is an example of making a PATCH request to an API using the fetch() method:

let data = { name: "John" };
fetch("https://jsonplaceholder.typicode.com/users/1", {
method: "PATCH",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(data => console.log(data))

This sends the data to the API endpoint and updates the resource with the given id and parse the response as json and logs it.

DELETE

Here is an example of making a DELETE request to an API using the fetch() method:

fetch("https://jsonplaceholder.typicode.com/users/1", {
method: "DELETE"
})
.then(response => response.json())
.then(data => console.log(data))

This sends the DELETE request to the API endpoint and delete the resource with the given id and parse the response as json and logs it.

It's important to note that when making requests to an API, it's important to handle errors and check the status of the response before processing the data.

Best practices and debugging

JavaScript best practices and debugging are essential skills for any developer. Properly implemented best practices can help improve the performance, maintainability, and security of your code, while debugging allows you to identify and fix errors in your code.

Best Practices

Here are some best practices to keep in mind when working with JavaScript:

  1. Use strict mode: Strict mode is a way to opt-in to a restricted variant of JavaScript. It enables a restricted syntax set and throws more exceptions.

    "use strict";
  2. Declare variables with let or const: The var keyword is considered outdated and should be avoided. Instead, use let for variables that will be reassigned, and const for variables that will not be reassigned.

  3. Use arrow functions: Arrow functions are a shorthand for anonymous functions and have a shorter syntax. They also have a more intuitive way of handling this and arguments

    let add = (a, b) => a + b;
  4. Use template literals: Template literals are a more readable way to create strings and include expressions. They use backticks instead of quotes and use the ${} syntax to include expressions.

    let name = "John";
    console.log(`Hello, ${name}!`);
  5. Always validate user input: Never trust user input, always validate it to prevent security vulnerabilities such as SQL injection or cross-site scripting (XSS) attacks.

  6. Use modules: JavaScript modules are a way to split your code into separate files and reuse them across different parts of your application. Use of modules helps to maintain the codebase.

Debugging

Debugging is an essential part of the development process, and there are several tools available to help you debug your JavaScript code.

  1. Use the browser developer tools: Most modern web browsers come with built-in developer tools that allow you to inspect and debug your code. You can use the console to log messages and inspect variables, and the debugger to set breakpoints and step through your code.

  2. Use console.log(): The console.log() function is a quick and easy way to log messages and inspect variables.

  3. Use a linter: A linter is a tool that checks your code for common errors and potential problems.

  4. Use a debugging tool: There are several debugging tools available such as debug in node.js, console.table(), console.dir() etc

  5. Use try-catch blocks: Try-catch blocks allow you to catch and handle errors in your code. It's useful for catching unexpected errors and can be used to provide a better user experience.

    try {
    // your code here
    } catch (error) {
    console.log(error);
    }

By following these best practices and using these debugging tools, you can improve the quality and maintainability of your JavaScript code.

Congratulations

Congrats on finishing the JavaScript basics. This is far from a comprehensive JavaScript course. But it will give you grasp of the basics and you can always refer to this refresher course to remember the basics of JS. Alright let us test your skills with an assessment.