Complete JavaScript Course

JS HOME

Welcome to the JavaScript tutorial! Here, you will learn everything about JavaScript, from basic concepts to advanced topics.

JS Introduction

JavaScript is a dynamic, high-level programming language primarily used for creating interactive effects within web browsers. It is an essential part of web development, alongside HTML and CSS, and is commonly used for client-side scripting.

JS Where To

JavaScript code can be placed in three main areas: inside the <script> tag in an HTML file, externally in a .js file, or inline within the HTML attributes. Here's an example of each:


<!-- In HTML file -->
<script>
    alert("Hello, World!");
</script>

<!-- External JS file -->
<script src="app.js"></script>

<!-- Inline event handler -->
<button onclick="alert('Hello!')">Click Me</button>
    

JS Output

JavaScript provides several ways to display output, such as alert(), console.log(), and document.write(). Here's an example of using each:


alert("Hello, World!");
console.log("This is a console message.");
document.write("This will write on the webpage.");
    

JS Statements

In JavaScript, a statement is a single line of code that performs an action. Statements can be assignments, function calls, or control structures like loops and conditionals.


let x = 10;  // This is an assignment statement
console.log(x);  // This is a function call statement
    

JS Syntax

JavaScript syntax is the set of rules that defines a correctly structured JavaScript program. It includes concepts like semicolons, curly braces, and parentheses. Here’s a basic structure:


function myFunction() {
    let x = 5;
    console.log(x);
}
myFunction();
    

JS Comments

Comments in JavaScript are used to explain the code and make it more readable. They are ignored by the JavaScript engine. You can add comments using // for single-line comments and /* */ for multi-line comments.


// This is a single-line comment

/*
  This is a
  multi-line comment
*/
    

JS Variables

In JavaScript, variables are used to store data values. You can declare variables using var, let, and const. Here’s an example:


let name = "John";  // Declaring a variable with 'let'
const age = 30;  // Declaring a constant
var city = "New York";  // Declaring a variable with 'var'
    

JS Let

The let keyword is used to declare variables in JavaScript. Variables declared with let have block scope, meaning they are only accessible within the block in which they are declared.


let x = 10;
{
    let x = 20; // This 'x' is different from the one above
    console.log(x); // Outputs: 20
}
console.log(x); // Outputs: 10
    

JS Const

The const keyword is used to declare constants. A constant's value cannot be changed after it is initialized. Constants also have block scope.


const PI = 3.14;
PI = 3.14159; // This will cause an error because PI is constant
    

JS Operators

JavaScript uses operators to perform operations on variables and values. Common operators include arithmetic operators, assignment operators, and comparison operators. Here’s an example:


let x = 10 + 5; // Arithmetic operator
let y = x; // Assignment operator
if (x > y) { // Comparison operator
    console.log("x is greater than y");
} else {
    console.log("x is equal to y");
}
    

JS Arithmetic

Arithmetic operators in JavaScript perform mathematical operations on numeric values. These include addition, subtraction, multiplication, division, and modulus.


let a = 10;
let b = 5;
console.log(a + b); // Addition: 15
console.log(a - b); // Subtraction: 5
console.log(a * b); // Multiplication: 50
console.log(a / b); // Division: 2
console.log(a % b); // Modulus: 0
    

JS Assignment

Assignment operators in JavaScript assign values to variables. These include simple assignment (=) and compound assignment operators (+=, -=, *=, /=, etc.).


let x = 5;
x += 2; // x = x + 2 => x = 7
x *= 3; // x = x * 3 => x = 21
console.log(x); // Outputs: 21
    

JS Data Types

JavaScript has various data types used to define variables. These include:


let name = "Alice"; // String
let age = 25; // Number
let isAdult = true; // Boolean
let undefinedVar; // Undefined
let person = null; // Null
let sym = Symbol("unique"); // Symbol
    

JS Functions

Functions in JavaScript are blocks of code that perform a specific task. They can be defined using function declarations or expressions.


// Function declaration
function greet(name) {
    return "Hello, " + name;
}

// Function expression
const sum = function(a, b) {
    return a + b;
};

console.log(greet("Alice")); // Outputs: Hello, Alice
console.log(sum(5, 3)); // Outputs: 8
    

JS Objects

An object is a collection of key-value pairs. It can store multiple values in a single variable.


let person = {
    name: "John",
    age: 30,
    greet: function() { return "Hello, " + this.name; }
};

console.log(person.name); // Outputs: John
console.log(person.greet()); // Outputs: Hello, John
    

JS Object Properties

Properties are values associated with an object. They can be accessed using dot notation or bracket notation.


let car = {
    brand: "Toyota",
    model: "Corolla"
};

console.log(car.brand); // Outputs: Toyota
console.log(car["model"]); // Outputs: Corolla
    

JS Object Methods

Methods are functions stored as object properties. They are invoked using the object reference.


let person = {
    firstName: "John",
    lastName: "Doe",
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
};

console.log(person.fullName()); // Outputs: John Doe
    

JS Object Display

Objects can be displayed using console.log(), and their properties can be accessed for display.


let user = {
    name: "Alice",
    age: 25,
    country: "USA"
};

console.log(user); // Outputs: { name: "Alice", age: 25, country: "USA" }
    

JS Object Constructors

Object constructors are functions used to create new objects with the same structure.


function Person(name, age) {
    this.name = name;
    this.age = age;
    this.greet = function() {
        return "Hello, " + this.name;
    };
}

let person1 = new Person("Bob", 30);
console.log(person1.greet()); // Outputs: Hello, Bob
    

JS Events

Events in JavaScript are actions that occur when the user interacts with HTML elements (e.g., click, load, mouseover). They can be handled using event listeners.


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

JS Strings

Strings in JavaScript are sequences of characters. They can be enclosed in single, double, or backtick (template literal) quotes.


let greeting = "Hello, World!";
let message = 'JavaScript is fun!';
let template = `This is a template string.`;

console.log(greeting); // Outputs: Hello, World!
    

JS String Methods

Strings come with built-in methods for manipulation, like toUpperCase(), toLowerCase(), slice(), etc.


let str = "Hello World!";
console.log(str.toUpperCase()); // Outputs: HELLO WORLD!
console.log(str.slice(0, 5)); // Outputs: Hello
    

JS String Templates

Template literals (backticks ``) allow for multi-line strings and embedded expressions using ${}.


let name = "Alice";
let age = 25;
let message = `Hello, my name is ${name} and I am ${age} years old.`;

console.log(message); // Outputs: Hello, my name is Alice and I am 25 years old.
    

JS Numbers

JavaScript uses the Number type for representing both integers and floating-point numbers.


let x = 5; // Integer
let y = 3.14; // Floating-point
console.log(x + y); // Outputs: 8.14
    

JS BigInt

BigInt is a built-in object that allows for the representation of large integers beyond the limit of Number.


let bigNumber = 1234567890123456789012345678901234567890n;
console.log(bigNumber); // Outputs: 1234567890123456789012345678901234567890n
    

JS Number Methods

JavaScript has several methods for manipulating numbers, such as toFixed(), parseInt(), and parseFloat().


let num = 3.14159;
console.log(num.toFixed(2)); // Outputs: 3.14
console.log(parseInt("42.5")); // Outputs: 42
    

JS Number Properties

JavaScript provides properties of the Number object like Number.MAX_VALUE, Number.MIN_VALUE, and Number.NaN.


console.log(Number.MAX_VALUE); // Outputs: 1.7976931348623157e+308
console.log(Number.MIN_VALUE); // Outputs: 5e-324
console.log(Number.NaN); // Outputs: NaN
    

JS Arrays

An array is an ordered collection of values, which can be of different types. Arrays are used to store multiple values in a single variable.


let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // Outputs: Apple
console.log(fruits.length); // Outputs: 3
    

JS Array Methods

JavaScript arrays have built-in methods that allow us to manipulate and interact with them, such as push(), pop(), shift(), and unshift().


let numbers = [1, 2, 3];

// Add an element to the end of the array
numbers.push(4);
console.log(numbers); // Outputs: [1, 2, 3, 4]

// Remove the last element from the array
numbers.pop();
console.log(numbers); // Outputs: [1, 2, 3]
    

JS Array Sort

Arrays in JavaScript can be sorted using the sort() method. It sorts the array elements by converting them into strings.


let numbers = [4, 2, 9, 1, 5, 6];
numbers.sort();
console.log(numbers); // Outputs: [1, 2, 4, 5, 6, 9]
    

To sort numbers correctly (in numeric order), you can provide a sorting function:


numbers.sort((a, b) => a - b);
console.log(numbers); // Outputs: [1, 2, 4, 5, 6, 9]
    

JS Array Iteration

JavaScript provides several methods to iterate over arrays, such as forEach(), map(), filter(), and reduce().


// forEach example
let fruits = ["Apple", "Banana", "Cherry"];
fruits.forEach((fruit) => {
    console.log(fruit);
});
// Outputs: Apple, Banana, Cherry

// map example
let numbers = [1, 2, 3];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // Outputs: [2, 4, 6]
    

JS Array Const

Using const for arrays makes the reference to the array constant, meaning the variable cannot be reassigned, but the contents of the array can still be modified.


const fruits = ["Apple", "Banana", "Cherry"];
fruits.push("Orange"); // This is allowed
console.log(fruits); // Outputs: ["Apple", "Banana", "Cherry", "Orange"]

// Reassigning the array will cause an error
// fruits = ["Grape", "Pineapple"]; // Error: Assignment to constant variable.
    

JS Dates

JavaScript provides the Date object to handle dates and times. It allows you to work with dates, calculate differences, and format them.


let currentDate = new Date();
console.log(currentDate); // Outputs the current date and time, e.g., "Tue Nov 20 2024 12:30:00 GMT+0000 (UTC)"
    

JS Date Formats

JavaScript's Date object can display dates in various formats using the toLocaleDateString() method and others.


let date = new Date();

console.log(date.toLocaleDateString()); // Outputs date in the format "MM/DD/YYYY"
console.log(date.toLocaleDateString("en-GB")); // Outputs date in the format "DD/MM/YYYY"
console.log(date.toISOString()); // Outputs date in ISO 8601 format: "2024-11-20T12:30:00.000Z"
    

JS Date Get Methods

The Date object provides several getter methods to retrieve parts of the date, such as getDate(), getMonth(), getFullYear(), and getHours().


let date = new Date();

console.log(date.getDate()); // Day of the month (1-31)
console.log(date.getMonth()); // Month (0-11)
console.log(date.getFullYear()); // Year
console.log(date.getHours()); // Hours (0-23)
    

JS Date Set Methods

Similar to getter methods, the Date object also provides setter methods to set specific parts of the date, such as setDate(), setMonth(), setFullYear(), and setHours().


let date = new Date();

date.setDate(25); // Set day of the month
date.setMonth(11); // Set month (0-11)
date.setFullYear(2025); // Set year
date.setHours(15); // Set hours (0-23)

console.log(date); // Outputs updated date
    

JS Math

The Math object provides mathematical functions and constants like Math.PI, Math.pow(), Math.sqrt(), and Math.random().


console.log(Math.PI); // Outputs: 3.141592653589793
console.log(Math.pow(2, 3)); // Outputs: 8 (2 raised to the power of 3)
console.log(Math.sqrt(16)); // Outputs: 4 (square root of 16)
console.log(Math.random()); // Outputs: A random number between 0 and 1
    

JS Random

The Math.random() function generates a random floating-point number between 0 (inclusive) and 1 (exclusive).


let randomNumber = Math.random();
console.log(randomNumber); // Outputs a random number between 0 and 1

// Generate a random number between 1 and 10
let randomInRange = Math.floor(Math.random() * 10) + 1;
console.log(randomInRange); // Outputs a random number between 1 and 10
    

JS Booleans

A Boolean represents a logical entity that can be either true or false. Booleans are often used in conditional testing.


let isTrue = true;
let isFalse = false;
console.log(isTrue); // Outputs: true
console.log(isFalse); // Outputs: false
    

JS Comparisons

Comparison operators in JavaScript allow you to compare values. Common comparison operators include ==, ===, !=, >, and <.


let a = 5, b = 10;

console.log(a == b);  // false
console.log(a != b);  // true
console.log(a < b);   // true
console.log(a === 5); // true
    

JS If Else

The if statement in JavaScript executes a block of code if the specified condition evaluates to true. You can also use else to execute code if the condition is false.


let age = 18;

if (age >= 18) {
    console.log("You are an adult.");
} else {
    console.log("You are a minor.");
}
    

JS Switch

The switch statement evaluates an expression and executes the code block corresponding to the matching case.


let day = 2;
let dayName;

switch (day) {
    case 1:
        dayName = "Monday";
        break;
    case 2:
        dayName = "Tuesday";
        break;
    case 3:
        dayName = "Wednesday";
        break;
    default:
        dayName = "Invalid day";
}
console.log(dayName); // Outputs: Tuesday
    

JS Loop For

The for loop repeats a block of code a certain number of times, with the loop counter controlling the number of iterations.


for (let i = 0; i < 5; i++) {
    console.log(i); // Outputs: 0, 1, 2, 3, 4
}
    

JS Loop For In

The for...in loop iterates over the properties of an object.


let person = { name: "John", age: 30, country: "USA" };

for (let key in person) {
    console.log(key + ": " + person[key]);
}
// Outputs: name: John, age: 30, country: USA
    

JS Loop For Of

The for...of loop iterates over iterable objects such as arrays, strings, and maps, accessing each value directly.


let fruits = ["Apple", "Banana", "Cherry"];

for (let fruit of fruits) {
    console.log(fruit); // Outputs: Apple, Banana, Cherry
}
    

JS Loop While

The while loop executes as long as the specified condition evaluates to true.


let count = 0;

while (count < 5) {
    console.log(count); // Outputs: 0, 1, 2, 3, 4
    count++;
}
    

JS Break

The break statement terminates the loop or switch statement, and the program continues after the loop or switch.


for (let i = 0; i < 5; i++) {
    if (i === 3) {
        break;
    }
    console.log(i); // Outputs: 0, 1, 2
}
    

JS Iterables

Iterables are objects that can be iterated over with a for...of loop. Arrays, strings, sets, and maps are examples of iterables.


let iterable = ["Apple", "Banana", "Cherry"];

for (let item of iterable) {
    console.log(item); // Outputs: Apple, Banana, Cherry
}
    

JS Sets

A Set is a collection of unique values. It automatically removes duplicates.


let uniqueNumbers = new Set([1, 2, 3, 4, 4, 5, 5]);

console.log(uniqueNumbers); // Outputs: Set { 1, 2, 3, 4, 5 }

// Adding new elements
uniqueNumbers.add(6);
console.log(uniqueNumbers); // Outputs: Set { 1, 2, 3, 4, 5, 6 }

// Checking if a value exists
console.log(uniqueNumbers.has(3)); // Outputs: true
console.log(uniqueNumbers.has(7)); // Outputs: false
    

JS Set Methods

Set methods allow you to manipulate and interact with sets, such as adding/removing elements, checking size, and more.


let fruits = new Set();

// Adding elements to the set
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
fruits.add("Apple"); // Duplicate elements are ignored

// Checking the size of the set
console.log(fruits.size); // Outputs: 3

// Removing an element
fruits.delete("Banana");

// Checking if an element exists
console.log(fruits.has("Cherry")); // Outputs: true

// Clearing all elements
fruits.clear();
console.log(fruits.size); // Outputs: 0
    

JS Maps

A Map is a collection of key-value pairs, where both keys and values can be any type, and the keys are ordered.


let person = new Map();

// Adding key-value pairs
person.set("name", "John");
person.set("age", 30);

// Getting the value by key
console.log(person.get("name")); // Outputs: John

// Checking if a key exists
console.log(person.has("age")); // Outputs: true

// Removing a key-value pair
person.delete("age");

// Getting the size of the map
console.log(person.size); // Outputs: 1

// Iterating through a map
person.forEach((value, key) => {
    console.log(key + ": " + value);
});
// Outputs: name: John
    

JS Map Methods

Map objects have various methods like set(), get(), has(), delete(), and more to handle key-value pairs.


let map = new Map([["a", 1], ["b", 2]]);
map.set("c", 3); // Adds a new key-value pair
console.log(map.get("b")); // Outputs: 2
console.log(map.has("a")); // Outputs: true
map.delete("a");
console.log(map.size); // Outputs: 2
    

JS Typeof

The typeof operator returns the type of a variable or expression.


console.log(typeof "Hello"); // Outputs: string
console.log(typeof 123); // Outputs: number
console.log(typeof true); // Outputs: boolean
console.log(typeof undefined); // Outputs: undefined
console.log(typeof null); // Outputs: object (this is a bug in JavaScript)
    

JS Type Conversion

Type conversion in JavaScript can be explicit or implicit. Implicit conversion is done automatically by JavaScript, while explicit conversion requires using built-in functions.


// Implicit Conversion
let result = "5" + 2; // Outputs: "52" (string concatenation)

// Explicit Conversion
let number = Number("5"); // Converts string to number
let boolean = Boolean(1); // Converts number to boolean
console.log(number); // Outputs: 5
console.log(boolean); // Outputs: true
    

JS Destructuring

Destructuring allows you to extract values from arrays or objects and assign them to variables in a concise way.


// Array Destructuring
let [a, b] = [1, 2];
console.log(a, b); // Outputs: 1 2

// Object Destructuring
let person = { name: "John", age: 30 };
let { name, age } = person;
console.log(name, age); // Outputs: John 30
    

JS Bitwise

Bitwise operators perform operations on the individual bits of numbers. Some common operators are &, |, ^, and ~.


let x = 5; // 0101 in binary
let y = 3; // 0011 in binary

console.log(x & y); // Outputs: 1 (0101 & 0011 = 0001)
console.log(x | y); // Outputs: 7 (0101 | 0011 = 0111)
console.log(x ^ y); // Outputs: 6 (0101 ^ 0011 = 0110)
console.log(~x); // Outputs: -6 (Bitwise NOT flips all bits)
    

JS RegExp

Regular expressions (RegEx) are patterns used to match character combinations in strings. JavaScript supports RegEx for string manipulation.


let regex = /hello/;
let str = "hello world";

console.log(regex.test(str)); // Outputs: true (matches "hello")
console.log(str.match(regex)); // Outputs: ["hello"]
    

JS Precedence

Operator precedence determines the order in which operations are evaluated in an expression. For example, multiplication and division have higher precedence than addition and subtraction.


let result = 5 + 2 * 3; // Outputs: 11 (multiplication happens before addition)
console.log(result);
    

JS Errors

Errors in JavaScript can be handled using try...catch. JavaScript provides different error types like SyntaxError, ReferenceError, etc.


try {
    let x = y; // This will throw a ReferenceError
} catch (error) {
    console.log(error.name + ": " + error.message); // Outputs: ReferenceError: y is not defined
}
    

JS Scope

Scope in JavaScript refers to the accessibility of variables. A variable's scope determines where it can be accessed or modified.


let globalVar = "I am global";

function myFunction() {
    let localVar = "I am local";
    console.log(globalVar); // Accessible
    console.log(localVar);  // Accessible
}

console.log(globalVar);  // Accessible
console.log(localVar);   // Error: localVar is not defined
    

JS Hoisting

Hoisting is JavaScript's behavior of moving declarations to the top of their containing scope. Only the declarations are hoisted, not the initializations.


console.log(x); // Outputs: undefined (x is hoisted but not initialized)
var x = 5;

myFunction(); // Outputs: "Hello"

function myFunction() {
    console.log("Hello");
}
    

JS Strict Mode

Strict mode in JavaScript is a way to opt-in to a restricted variant of JavaScript, which helps catch common coding errors and improves performance.


// Without strict mode
x = 10; // No error, but it's an undeclared variable

// With strict mode
"use strict";
x = 10; // Error: x is not defined (must be declared first)
    

JS This Keyword

The this keyword refers to the object that is currently executing the code. It behaves differently in global context, methods, and functions.


function show() {
    console.log(this); // Refers to the global object in non-strict mode
}

const person = {
    name: "John",
    greet: function() {
        console.log(this.name); // Refers to the person object
    }
};

show(); // In non-strict mode, this refers to the global object
person.greet(); // Outputs: John
    

JS Arrow Function

Arrow functions provide a shorter syntax for writing functions. They also do not bind their own this, instead they inherit it from the surrounding context.


// Traditional function
const sum = function(a, b) {
    return a + b;
};

// Arrow function
const sumArrow = (a, b) => a + b;

console.log(sum(5, 3)); // Outputs: 8
console.log(sumArrow(5, 3)); // Outputs: 8
    

JS Classes

JavaScript classes provide a blueprint for creating objects with predefined properties and methods. They are syntactical sugar over JavaScript’s existing prototype-based inheritance.


class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

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

const john = new Person("John", 30);
john.greet(); // Outputs: Hello, John
    

JS Modules

JavaScript modules allow you to break your code into smaller, reusable pieces. You can export functions, objects, or variables from one file and import them into another.


// In module.js file
export const greet = () => {
    console.log("Hello from module!");
};

// In app.js file
import { greet } from './module.js';
greet(); // Outputs: Hello from module!
    

JS JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and easy for machines to parse and generate.


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

// Converting object to JSON string
let jsonString = JSON.stringify(person);
console.log(jsonString); // Outputs: {"name":"John","age":30}

// Parsing JSON string to object
let parsedObject = JSON.parse(jsonString);
console.log(parsedObject.name); // Outputs: John
    

JS Debugging

Debugging in JavaScript involves finding and fixing bugs in your code. You can use browser developer tools, console.log(), breakpoints, and other debugging tools.


// Example: Finding issues with console logging
function add(a, b) {
    console.log(a, b);
    return a + b;
}

add(5); // Outputs: 5 undefined (debug by checking missing argument)
    

JS Style Guide

A JavaScript style guide helps developers maintain consistency in code formatting. It includes rules for naming conventions, indentation, and other coding practices. Some popular guides are from Airbnb and Google.


// Example from Airbnb style guide

// Always use semicolons
const name = "John";

// Prefer const over let
const age = 30;

// Use arrow functions for anonymous functions
const greet = () => {
    console.log("Hello!");
};
    

JS Best Practices

Best practices help you write efficient, maintainable, and error-free JavaScript code. Examples include using strict mode, avoiding global variables, and modularizing code.


// Use strict mode to avoid errors
"use strict";

// Avoid global variables
let globalVar = 10;

// Use let and const instead of var for better scoping
const constant = 5;
    

JS Mistakes

Common JavaScript mistakes include incorrect use of this, not using const and let properly, and neglecting to check for null/undefined values before accessing properties.


// Mistake: Using var instead of let or const
var x = 10; // Causes issues with scope

// Mistake: Forgetting to declare variables
y = 5; // ReferenceError in strict mode

// Mistake: Confusing == and ===
console.log(0 == '0'); // true (loose equality)
console.log(0 === '0'); // false (strict equality)
    

JS Performance

Performance optimization involves improving the speed and efficiency of JavaScript code. Some techniques include minimizing DOM manipulations, reducing memory usage, and using efficient algorithms.


// Example: Avoiding unnecessary DOM queries
const button = document.getElementById("myButton");
button.addEventListener("click", () => {
    console.log("Button clicked!");
});
    

JS Reserved Words

JavaScript has a set of reserved words that cannot be used as variable or function names. These include let, const, function, and others.


// Example of reserved words
let let = 5; // Error: let is a reserved word
const const = 10; // Error: const is a reserved word
    

JS Versions

JavaScript has evolved over the years with new features and enhancements in every version. Below is a summary of each major version:

JS 2009 (ES5)

ECMAScript 5 (ES5) was a major update to JavaScript, released in 2009. It brought several important features and improvements to the language.

JS 2015 (ES6)

ECMAScript 2015, commonly known as ES6, introduced significant improvements and new features to JavaScript. These changes greatly improved syntax and functionality.

JS 2016

ECMAScript 2016 (ES7) was a relatively small update to JavaScript but introduced a few useful features:

JS 2017 (ES8)

ECMAScript 2017 (ES8) brought a few new features to improve JavaScript's functionality:

JS 2018 (ES9)

ECMAScript 2018 (ES9) continued to improve JavaScript with several small but important features:

JS 2019 (ES10)

ECMAScript 2019 (ES10) focused on improving usability and standardizing methods for working with data:

JS 2020 (ES11)

ECMAScript 2020 (ES11) introduced several significant new features:

JS 2021 (ES12)

ECMAScript 2021 (ES12) brought improvements and new methods for working with data:

JS 2022 (ES13)

ECMAScript 2022 (ES13) introduced:

JS 2023 (ES14)

ECMAScript 2023 (ES14) is expected to continue the evolution of JavaScript, but as of the time of writing, it’s still under development with new features being proposed and reviewed.

JS 2024 (ES15)

ECMAScript 2024 (ES15) will likely introduce additional enhancements and features as the language continues to evolve. Look out for proposals from the JavaScript community.

JS IE / Edge

Internet Explorer (IE) and Microsoft Edge have historically had different levels of support for JavaScript. IE often lagged behind modern features, while Edge has better compatibility with recent ECMAScript versions. IE is now deprecated, and Edge is the modern browser for Windows.

JS History

JavaScript was created by Brendan Eich in 1995 and has gone through numerous versions and improvements. Initially used for small client-side scripts, it has evolved into a powerful language used for both frontend and backend development (e.g., Node.js).

JS Objects

In JavaScript, objects are key-value pairs that allow you to store multiple values in a single variable. They are fundamental in organizing data and defining behavior.

Object Definitions

Objects are collections of properties and methods. A property is a key-value pair, and a method is a function stored as a property. Objects can represent real-world entities and store various types of data.


        const person = {
            name: 'John Doe',
            age: 30,
            greet: function() {
                console.log('Hello, ' + this.name);
            }
        };
    

Object Prototypes

Every JavaScript object has a prototype, which is also an object. Prototypes allow objects to share properties and methods. They are used to implement inheritance.


        function Person(name, age) {
            this.name = name;
            this.age = age;
        }
        Person.prototype.greet = function() {
            console.log('Hello, ' + this.name);
        };
        const person1 = new Person('Alice', 25);
        person1.greet(); // Output: Hello, Alice
    

Object Methods

Methods are functions stored as properties of an object. They define the behavior of an object. You can define methods directly inside an object or add them later using prototypes.


        const car = {
            brand: 'Toyota',
            model: 'Corolla',
            drive: function() {
                console.log('Driving the ' + this.brand + ' ' + this.model);
            }
        };
        car.drive(); // Output: Driving the Toyota Corolla
    

Object Properties

Properties are values associated with an object. These values can be strings, numbers, arrays, or other objects. Properties are accessed using dot notation or bracket notation.


        const user = {
            name: 'Jane',
            age: 28
        };
        console.log(user.name); // Output: Jane
        console.log(user['age']); // Output: 28
    

Object Get / Set

Getters and setters allow you to define special methods for reading and writing property values. Getters retrieve values, while setters modify them.


        const person = {
            firstName: 'John',
            lastName: 'Doe',
            get fullName() {
                return this.firstName + ' ' + this.lastName;
            },
            set fullName(name) {
                const nameParts = name.split(' ');
                this.firstName = nameParts[0];
                this.lastName = nameParts[1];
            }
        };
        console.log(person.fullName); // Output: John Doe
        person.fullName = 'Jane Smith';
        console.log(person.firstName); // Output: Jane
    

Object Protection

JavaScript objects can be protected using various methods, such as Object.freeze(), Object.seal(), and defining properties with specific descriptors like writable, enumerable, and configurable.


        const obj = {
            name: 'Alice'
        };
        Object.freeze(obj);
        obj.name = 'Bob'; // This change will not be applied
        console.log(obj.name); // Output: Alice
    

JS Functions

Functions are a fundamental building block in JavaScript, allowing us to create reusable blocks of code. Here's a breakdown of function-related concepts:

Function Definitions

Functions in JavaScript can be defined using the function keyword. A function definition includes the function name, parameters (optional), and the block of code to execute.

function greet(name) {
    return 'Hello, ' + name + '!';
}

Function Parameters

Parameters are values passed into a function when it is called. They act as placeholders for data that the function needs to operate on. Functions can have default parameters as well.

function greet(name = 'Guest') {
    return 'Hello, ' + name + '!';
}

Function Invocation

Function invocation refers to the actual call of a function to execute the code within it. You can invoke a function using its name and passing the required arguments.

greet('Alice'); // Outputs: Hello, Alice!

Function Call

A function call involves invoking a function to execute its logic. Functions can be called with or without arguments, depending on the function's definition.

greet('Bob'); // Outputs: Hello, Bob!

Function Apply

The apply() method calls a function with a given this value, and an array or array-like object of arguments.

greet.apply(null, ['Charlie']); // Outputs: Hello, Charlie!

Function Bind

The bind() method creates a new function that, when invoked, has its this value set to the provided value and has a given sequence of arguments preceding any provided when the new function is called.

const greetAlice = greet.bind(null, 'Alice');
greetAlice(); // Outputs: Hello, Alice!

Function Closures

A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope. This allows a function to "remember" the environment in which it was created.

function outer() {
    let count = 0;
    return function inner() {
        count++;
        return count;
    };
}
const counter = outer();
console.log(counter()); // Outputs: 1
console.log(counter()); // Outputs: 2

JS Classes

JavaScript classes are templates for creating objects. Classes provide a way to define object properties and methods. They were introduced in ECMAScript 6 (ES6) and allow for a more object-oriented approach to JavaScript programming.

Class Introduction

Classes in JavaScript are defined using the class keyword. A class can have a constructor to initialize the object's properties and methods that define the behavior of the object.

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    
    greet() {
        return 'Hello, ' + this.name;
    }
}

const person1 = new Person('Alice', 30);
console.log(person1.greet()); // Outputs: Hello, Alice

Class Inheritance

JavaScript supports inheritance, allowing one class to inherit properties and methods from another class. This is done using the extends keyword.

class Employee extends Person {
    constructor(name, age, position) {
        super(name, age); // Calls the parent class constructor
        this.position = position;
    }

    describe() {
        return this.name + ' is a ' + this.position;
    }
}

const employee1 = new Employee('Bob', 35, 'Developer');
console.log(employee1.greet()); // Outputs: Hello, Bob
console.log(employee1.describe()); // Outputs: Bob is a Developer

Class Static

Static methods in a class are defined using the static keyword. They are called on the class itself, rather than on instances of the class. Static methods are useful for utility functions or shared behavior that doesn’t rely on instance data.

class MathUtil {
    static add(a, b) {
        return a + b;
    }
}

console.log(MathUtil.add(5, 10)); // Outputs: 15

JS Asynchronous Programming

Asynchronous programming allows JavaScript to execute tasks like reading files, making HTTP requests, or performing computations without blocking the main thread of execution. It helps in making applications more responsive and efficient.

JS Callbacks

A callback is a function that is passed into another function as an argument and is executed after the completion of the task. It’s often used to handle asynchronous operations.

function fetchData(callback) {
    setTimeout(() => {
        const data = { user: 'Alice', age: 30 };
        callback(data); // callback function is called after 2 seconds
    }, 2000);
}

function processData(data) {
    console.log('Data received:', data);
}

fetchData(processData); // Outputs: Data received: { user: 'Alice', age: 30 }

JS Asynchronous

Asynchronous code in JavaScript enables functions to be executed without blocking the execution of other operations. A common pattern is using callbacks, but there are more modern approaches, such as Promises and async/await.

One of the key features of asynchronous code is the ability to handle tasks in the background (like API calls) while allowing the program to continue with other operations.

JS Promises

A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation. Promises have three states: pending, fulfilled, and rejected.

const fetchData = new Promise((resolve, reject) => {
    setTimeout(() => {
        const data = { user: 'Bob', age: 25 };
        resolve(data); // Promise is fulfilled
        // reject('Error: Data could not be fetched'); // If rejected
    }, 2000);
});

fetchData.then(data => {
    console.log('Data received:', data); // Outputs: Data received: { user: 'Bob', age: 25 }
}).catch(error => {
    console.log(error); // If the promise is rejected, this will run
});

JS Async/Await

Async/Await is a modern way to handle asynchronous code in JavaScript. It allows you to write asynchronous code in a synchronous-looking style, making it easier to read and maintain.

The async keyword is used to define a function that returns a Promise, while the await keyword is used inside an async function to wait for a Promise to resolve.

async function getUserData() {
    const data = await fetchData(); // Waits for the Promise to resolve
    console.log('Data received:', data); // Outputs: Data received: { user: 'Alice', age: 30 }
}

getUserData(); // Calling the async function

Async/Await simplifies the handling of Promises and allows for cleaner, more readable code compared to using chained then() methods.

JS HTML DOM

The Document Object Model (DOM) represents the structure of an HTML document as a tree-like structure. JavaScript can interact with the DOM to manipulate content, structure, and style of web pages dynamically.

DOM Intro

The DOM is a programming interface for web documents. It represents the page so that programs can manipulate the structure, style, and content of the document.

With the DOM, JavaScript can dynamically change the document's structure, style, and content in response to user interactions or other events.

DOM Methods

DOM methods allow you to interact with the document. Common methods include:

const element = document.getElementById('myElement');

DOM Document

The document object in JavaScript represents the HTML document that is currently loaded in the browser. It serves as an entry point to access all elements and interact with the page's content.

console.log(document.title); // Accesses the title of the document

DOM Elements

DOM elements are individual parts of the HTML document. Every HTML tag (like <div>, <p>, etc.) becomes an element in the DOM, and JavaScript can manipulate these elements using DOM methods.

const heading = document.createElement('h1'); // Creates a new h1 element
heading.textContent = 'Hello, World!';
document.body.appendChild(heading); // Appends the new element to the body

DOM HTML

The innerHTML property allows JavaScript to get or set the HTML content inside an element. It can be used to dynamically change content, add elements, or modify attributes.

const container = document.getElementById('container');
container.innerHTML = '

This is a new paragraph

'; // Updates the content inside the container

DOM Forms

JavaScript can interact with forms and their elements. This includes retrieving values from form inputs, setting values, and submitting forms programmatically.

const form = document.querySelector('form');
form.addEventListener('submit', function(event) {
    event.preventDefault();
    console.log('Form submitted');
});

DOM CSS

The DOM allows you to manipulate the style of elements dynamically through the style property. You can modify individual CSS properties using JavaScript.

const element = document.getElementById('myElement');
element.style.backgroundColor = 'blue'; // Changes the background color of the element

DOM Animations

DOM can be used to create simple animations by modifying the CSS properties of elements over time using methods like setInterval(), requestAnimationFrame(), or through CSS transitions and animations.

const box = document.getElementById('box');
let position = 0;
setInterval(function() {
    position += 1;
    box.style.left = position + 'px';
}, 10); // Moves the element to the right

DOM Events

Events are actions that occur in the browser, such as clicks, key presses, or mouse movements. JavaScript can listen to these events and respond accordingly.

const button = document.getElementById('myButton');
button.addEventListener('click', function() {
    alert('Button clicked!');
});

DOM Event Listener

The addEventListener() method is used to attach an event handler to an element. It listens for a specific event and executes a callback function when the event occurs.

document.querySelector('button').addEventListener('click', function() {
    alert('Button was clicked!');
});

DOM Navigation

DOM navigation refers to the ability to move between elements within the DOM tree. JavaScript allows you to navigate parent, child, and sibling elements.

const parentElement = document.querySelector('.parent');
const firstChild = parentElement.firstElementChild;
console.log(firstChild); // Outputs the first child of the parent element

DOM Nodes

In the DOM, everything is a node: elements, attributes, and text. Nodes are the building blocks of the DOM structure.

const textNode = document.createTextNode('Hello World!');
document.body.appendChild(textNode); // Adds a new text node to the document

DOM Collections

DOM collections are arrays of DOM elements returned by methods like getElementsByClassName() or getElementsByTagName(). These collections are live, meaning they update automatically when the document changes.

const divs = document.getElementsByTagName('div');
console.log(divs.length); // Outputs the number of div elements in the document

DOM Node Lists

Node lists are similar to collections but are static. They do not automatically update when changes are made to the DOM. They are returned by methods like querySelectorAll().

const nodes = document.querySelectorAll('div');
console.log(nodes.length); // Outputs the number of div elements selected by the CSS selector

JS Browser BOM

The Browser Object Model (BOM) provides objects that allow JavaScript to interact with the browser outside of the HTML document. It gives access to various browser-specific functionalities, such as controlling the browser window, navigating, and handling events.

JS Window

The window object represents the browser window. It provides methods and properties to interact with the browser window, such as resizing the window, opening new windows, and accessing various browser-related features.

window.alert('Hello, World!'); // Displays an alert box

JS Screen

The screen object contains information about the user's screen, such as the screen's width, height, and color depth. It helps to gather information about the screen's display properties.

console.log(screen.width); // Logs the width of the screen

JS Location

The location object allows you to get or set the current URL of the browser window. It is useful for navigating the browser or manipulating the URL in the address bar.

console.log(location.href); // Logs the current URL of the page

JS History

The history object allows you to interact with the browser's history. You can navigate backward and forward in the browser's history or manipulate the history stack.

history.back(); // Navigates to the previous page

JS Navigator

The navigator object contains information about the browser and the user's operating system. It provides details like the browser version, the platform, and whether the browser is online or offline.

console.log(navigator.userAgent); // Logs browser details

JS Popup Alert

JavaScript provides methods to create pop-up alerts, confirm boxes, and prompt boxes. These are used to display messages to the user or gather input from them.

alert('This is an alert box!'); // Displays a simple alert

JS Timing

JavaScript provides functions to execute code after a certain amount of time or repeatedly at specified intervals. These timing functions are useful for animations, delayed actions, or periodic tasks.

setTimeout(() => { console.log('This runs after 2 seconds'); }, 2000);

JS Cookies

Cookies are small pieces of data stored in the user's browser. JavaScript can be used to read, set, and delete cookies, which are often used for session management, user preferences, and tracking.

document.cookie = "username=JohnDoe"; // Sets a cookie named 'username'

JS Web APIs

Web APIs provide JavaScript with the ability to interact with various aspects of the web browser and the web environment. These APIs offer a wide range of functionality for modern web development, including managing web storage, fetching data from servers, geolocation services, and more.

Web Forms API

The Web Forms API provides JavaScript with methods and events to interact with web forms. It can be used to access and manipulate form elements, handle user input, and validate forms before submission.

document.querySelector('form').addEventListener('submit', function(event) {
    event.preventDefault(); // Prevent form submission
    console.log('Form submitted');
});

Web History API

The Web History API allows JavaScript to interact with the browser's history. It can be used to modify the history state and navigate between pages programmatically without reloading the page. This API is useful for single-page applications (SPAs).

history.pushState({ page: 1 }, "title 1", "?page=1");

Web Storage API

The Web Storage API provides access to local storage and session storage, allowing you to store data persistently on the user's browser. Local storage data persists across sessions, while session storage is cleared when the browser session ends.

localStorage.setItem('username', 'JohnDoe');
console.log(localStorage.getItem('username')); // Logs 'JohnDoe'

Web Worker API

The Web Worker API allows JavaScript to run background threads for executing tasks in parallel without blocking the main thread. This is particularly useful for performance-intensive operations that might otherwise freeze the UI.

const worker = new Worker('worker.js');
worker.postMessage('Hello Worker');
worker.onmessage = function(event) {
    console.log('Message from worker:', event.data);
};

Web Fetch API

The Web Fetch API provides a modern way to make network requests, such as HTTP requests to retrieve or send data to a server. It returns a Promise that resolves with the Response object, which allows access to the response data.

fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.log('Error:', error));

JS AJAX

AJAX (Asynchronous JavaScript and XML) is a technique used to update parts of a web page without reloading the whole page. It allows for asynchronous data exchange between the client and the server, enhancing the user experience.

AJAX Intro

AJAX is a web development technique that enables asynchronous communication between the client and server. It allows you to send and receive data in the background without refreshing the page, making web applications faster and more interactive.

AJAX XMLHttpRequest

The XMLHttpRequest (XHR) object is the core component for making AJAX requests in JavaScript. It allows you to send and receive data from a server asynchronously.

let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.send();

AJAX Request

An AJAX request is created using the XMLHttpRequest object. You define the type of request (GET, POST), the URL, and the event handler to process the server's response.

let xhr = new XMLHttpRequest();
xhr.open('POST', 'submit_form.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('name=JohnDoe&email=john@example.com');

AJAX Response

The server's response to an AJAX request can be handled using the onreadystatechange event or modern onload and onerror events. The response can be accessed in various formats, such as text, JSON, or XML.

let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText); // Handle the response
    }
};
xhr.send();

AJAX XML File

AJAX can be used to request XML data from a server, which can then be processed in JavaScript using the XMLHttpRequest object and parsed with DOM methods.

let xhr = new XMLHttpRequest();
xhr.open('GET', 'data.xml', true);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        let xmlDoc = xhr.responseXML;
        let element = xmlDoc.getElementsByTagName('name')[0].childNodes[0].nodeValue;
        console.log(element);
    }
};
xhr.send();

AJAX PHP

AJAX can be used with PHP to send data to the server and process it without reloading the page. The server can return a response (like JSON or HTML), which is then handled on the client side.

let xhr = new XMLHttpRequest();
xhr.open('POST', 'submit_form.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText); // Handle PHP response
    }
};
xhr.send('name=JohnDoe&email=john@example.com');

AJAX ASP

AJAX can also interact with ASP.NET applications. The ASP.NET server can handle AJAX requests, perform operations, and return data without page refresh.

let xhr = new XMLHttpRequest();
xhr.open('POST', 'submit_form.aspx', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText); // Handle ASP response
    }
};
xhr.send('name=JohnDoe&email=john@example.com');

AJAX Database

AJAX can be used to interact with a database via server-side scripts like PHP, ASP, or Node.js. You can send queries to a database and return results asynchronously, which is often used in search features or dynamic content updates.

let xhr = new XMLHttpRequest();
xhr.open('GET', 'fetch_data.php?query=searchTerm', true);
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        let data = JSON.parse(xhr.responseText); // Process database response
        console.log(data);
    }
};
xhr.send();

AJAX Applications

AJAX is used in various web applications, including real-time chat applications, social media feeds, email clients, and more. Its ability to load data in the background without reloading the entire page enhances the user experience.

AJAX Examples

Here are some examples of how AJAX can be used to enhance the functionality of web pages:

JS JSON

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 commonly used to transmit data between a server and a web application.

JSON Intro

JSON is a format used to represent structured data as key-value pairs, similar to how objects and arrays are represented in JavaScript. It is widely used for exchanging data between a client and server in web applications.

JSON Syntax

JSON syntax consists of key-value pairs, where the key is a string, and the value can be a string, number, object, array, or boolean.

{
    "name": "John",
    "age": 30,
    "city": "New York"
}

JSON vs XML

Both JSON and XML are used to store and transport data, but they have key differences:

JSON Data Types

JSON supports the following data types:

JSON Parse

The JSON.parse() method is used to parse a JSON string and convert it into a JavaScript object.

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

JSON Stringify

The JSON.stringify() method is used to convert a JavaScript object into a JSON string.

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

JSON Objects

A JSON object is a collection of key-value pairs, similar to a JavaScript object. Keys are strings, and values can be various data types (strings, numbers, arrays, etc.).

let person = {
    "name": "John",
    "age": 30,
    "city": "New York"
};

JSON Arrays

A JSON array is an ordered list of values, which can be of any data type. The values in an array are separated by commas and enclosed in square brackets.

let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]);  // Output: Apple

JSON Server

JSON Server is a simple API server used to simulate a RESTful API with CRUD operations. It is often used for prototyping and testing.

JSON PHP

In PHP, you can use the json_encode() and json_decode() functions to work with JSON data.

$jsonStr = '{"name":"John", "age":30}';
$decodedObj = json_decode($jsonStr);
echo $decodedObj->name;  // Output: John

JSON HTML

JSON data can be used in HTML documents, typically by parsing it in JavaScript and then dynamically generating HTML content based on that data.

let jsonData = '{"name": "John", "age": 30}';
let obj = JSON.parse(jsonData);
document.getElementById("name").innerHTML = obj.name; // Display in HTML element

JSONP

JSONP (JSON with Padding) is a technique used to overcome the limitations of the Same-Origin Policy in browsers. It allows for requesting data from a server on a different domain by using a script tag instead of XMLHttpRequest.

function handleResponse(data) {
    console.log(data);
}
let script = document.createElement('script');
script.src = 'https://example.com/data?callback=handleResponse';
document.body.appendChild(script);

JS vs jQuery

JavaScript and jQuery are both used to create dynamic content for websites, but they differ in several key aspects:

While JavaScript is a full-fledged programming language, jQuery simplifies the process of writing JavaScript code, especially when working with DOM manipulation, animations, and event handling.

jQuery Selectors

jQuery selectors are used to select HTML elements that you want to manipulate. These selectors are much easier to use than their JavaScript equivalents. Here are some examples:

jQuery HTML

jQuery provides several methods to manipulate the HTML content of an element:

jQuery CSS

jQuery makes it easier to change CSS properties of elements dynamically:

jQuery DOM

The DOM (Document Object Model) allows you to dynamically manipulate HTML elements. jQuery makes DOM manipulation easier:

JS Graphics

JavaScript offers several libraries and APIs to create graphics, plots, charts, and visualizations for web pages. Here are some of the most popular options:

JS Canvas

The <canvas> element in HTML5 allows you to draw graphics via JavaScript. It is commonly used for rendering graphics such as graphs, games, and interactive visualizations.

JS Plotly

Plotly is a powerful JavaScript library used to create interactive plots, charts, and visualizations. It supports a variety of chart types including line charts, scatter plots, bar charts, pie charts, and more.

To use Plotly, include the Plotly.js script in your HTML:

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>

Example of a basic Plotly chart:

var data = [{
  x: [1, 2, 3, 4],
  y: [10, 11, 12, 13],
  type: 'scatter'
}];
Plotly.newPlot('myDiv', data);

Plotly provides a wide range of customizable options for interactive visualizations and graphs.

JS Chart.js

Chart.js is a simple yet flexible JavaScript charting library for creating beautiful charts. It supports line, bar, radar, pie, doughnut, and polar area charts.

To use Chart.js, include its script in your HTML:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

Example of a basic bar chart with Chart.js:

<canvas id="myChart"></canvas>

JS Google Chart

Google Charts is a library that allows you to create a wide variety of charts with ease. It offers charts such as line charts, bar charts, pie charts, and geo charts, and can be integrated with Google Sheets or other data sources.

To use Google Charts, include the Google Charts library:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

Example of a Google Bar Chart:

google.charts.load('current', {
    packages: ['corechart', 'bar']
});
google.charts.setOnLoadCallback(drawStuff);

function drawStuff() {
    var data = new google.visualization.arrayToDataTable([
        ['City', '2010 Population', '2000 Population'],
        ['New York City, NY', 8175133, 8008278],
        ['Los Angeles, CA', 3792621, 3694820],
        ['Chicago, IL', 2695598, 2896016],
        ['Houston, TX', 2129784, 1953631]
    ]);
    var options = {
        title: 'Population of Largest U.S. Cities',
        chartArea: {width: '50%'},
        hAxis: {
            title: 'Total Population',
            minValue: 0
        },
        vAxis: {
            title: 'City'
        }
    };
    var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
    chart.draw(data, options);
}

JS D3.js

D3.js (Data-Driven Documents) is a powerful JavaScript library for producing dynamic, interactive data visualizations in the browser. It allows you to bind data to a DOM element and then apply data-driven transformations to the document.

To use D3.js, include the library:

<script src="https://d3js.org/d3.v6.min.js"></script>

Example of a simple bar chart with D3.js:

var data = [30, 86, 168, 281, 303, 365];
var width = 420,
    barHeight = 20;

var x = d3.scaleLinear()
    .domain([0, d3.max(data)])
    .range([0, width]);

var chart = d3.select(".chart")
    .attr("width", width)
    .attr("height", barHeight * data.length);

var bar = chart.selectAll("g")
    .data(data)
    .enter().append("g")
    .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

bar.append("rect")
    .attr("width", x)
    .attr("height", barHeight - 1);

bar.append("text")
    .attr("x", function(d) { return x(d) - 3; })
    .attr("y", barHeight / 2)
    .attr("dy", ".35em")
    .text(function(d) { return d; });

D3.js is particularly useful for complex visualizations like interactive charts, hierarchical diagrams, and network graphs.

JS Examples

This section provides various JavaScript examples to help you understand the core concepts and techniques for web development.

JS HTML DOM

The Document Object Model (DOM) represents the structure of an HTML document as a tree of objects. JavaScript can interact with the DOM to modify HTML elements dynamically.

document.getElementById("demo").innerHTML = "Hello, JavaScript!";

This example changes the content of an element with the ID "demo".

JS HTML Input

JavaScript can interact with HTML form elements like text inputs, buttons, checkboxes, etc., to create dynamic user interactions.

document.getElementById("myBtn").addEventListener("click", function() {
            alert("Button clicked!");
        });

This example shows how to add a click event listener to a button.

JS HTML Objects

In JavaScript, HTML elements can be represented as objects. You can access and modify these objects to change the page's content and structure.

var img = document.createElement("img");
img.src = "https://example.com/image.jpg";
document.body.appendChild(img);

This code creates an image element dynamically and appends it to the document body.

JS HTML Events

Events in JavaScript allow you to add interactivity to HTML elements. These events include actions like clicks, mouse movements, key presses, etc.

document.getElementById("myButton").addEventListener("click", function() {
            alert("You clicked the button!");
        });

This code attaches a click event to a button and shows an alert when the button is clicked.

JS Browser

JavaScript provides access to browser-related objects such as window, navigator, screen, etc., to interact with the browser environment.

console.log(window.innerWidth);

This code logs the inner width of the browser window.

JS Editor

To run JavaScript code, you can use various code editors like Visual Studio Code, Sublime Text, or online editors like JSFiddle or CodePen.

These tools provide environments where you can write, test, and debug your JavaScript code in real-time.

JS Exercises

Practice is key to mastering JavaScript. Below are some exercises to help you improve your skills:

JS Quiz

Test your JavaScript knowledge with quizzes. Here are some sample questions:

JS Website

Building websites with JavaScript is common for creating dynamic, interactive web pages. Below is a simple example of using JavaScript to interact with HTML elements on a webpage:

<button id="changeColor">Change Background Color</button>

This code adds a button that changes the background color of the page when clicked.

JS Syllabus

The JavaScript syllabus typically includes the following topics:

JS Interview Prep

Prepare for JavaScript-related interviews with the following tips and common questions:

JS Bootcamp

Join a JavaScript bootcamp to enhance your skills quickly. Bootcamps provide structured learning, real-world projects, and support:

JS Certificate

After completing your JavaScript learning journey, you can earn a certificate to validate your skills. Some popular platforms offering certificates are:

JS References

JavaScript references provide detailed information about JavaScript objects and HTML DOM objects. These references can help you understand the properties, methods, and events associated with JavaScript and the DOM:

JavaScript Objects

JavaScript objects are collections of properties, and each property is a key-value pair. Objects are a fundamental data type in JavaScript and are used to store data and functionality.

  • Object properties
  • Object methods
  • Creating and modifying objects
  • Object prototypes

HTML DOM Objects

The Document Object Model (DOM) represents the structure of HTML documents as objects. Each element in an HTML document is an object, and JavaScript can interact with these objects to change the content, structure, and style of a webpage.

  • DOM document object
  • DOM element objects
  • DOM events
  • DOM node manipulation