Welcome to the JavaScript tutorial! Here, you will learn everything about JavaScript, from basic concepts to advanced topics.
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.
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>
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.");
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
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();
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
*/
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'
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
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
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");
}
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
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
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
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
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
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
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
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" }
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
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!");
});
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!
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
JavaScript provides methods to search for a substring within a string, such as indexOf()
, includes()
, and search()
.
let text = "Hello, welcome to the world!";
console.log(text.indexOf("welcome")); // Outputs: 7
console.log(text.includes("world")); // Outputs: true
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.
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
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
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
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
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
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]
JavaScript provides several methods to search for elements in an array, such as indexOf()
, find()
, and includes()
.
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits.indexOf("Banana")); // Outputs: 1
console.log(fruits.includes("Grapes")); // Outputs: false
console.log(fruits.find(fruit => fruit === "Cherry")); // Outputs: Cherry
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]
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]
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.
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)"
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"
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)
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
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
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
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
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
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.");
}
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
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
}
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
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
}
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++;
}
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
}
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
}
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
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
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
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
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)
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
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
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)
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"]
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);
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
}
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
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");
}
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)
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
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
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
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!
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
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)
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!");
};
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;
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)
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!");
});
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
JavaScript has evolved over the years with new features and enhancements in every version. Below is a summary of each major version:
ECMAScript 5 (ES5) was a major update to JavaScript, released in 2009. It brought several important features and improvements to the language.
forEach()
, map()
, filter()
, and reduce()
were introduced for better array handling.JSON.stringify()
and JSON.parse()
methods for working with JSON data.ECMAScript 2015, commonly known as ES6, introduced significant improvements and new features to JavaScript. These changes greatly improved syntax and functionality.
() => {}
).`string ${expression}`
).ECMAScript 2016 (ES7) was a relatively small update to JavaScript but introduced a few useful features:
**
): A new operator for exponentiation (2 ** 3
is equivalent to Math.pow(2, 3)
).ECMAScript 2017 (ES8) brought a few new features to improve JavaScript's functionality:
padStart()
and padEnd()
for adding padding to strings.ECMAScript 2018 (ES9) continued to improve JavaScript with several small but important features:
for-await-of
loop to iterate over asynchronous data....obj
) in addition to arrays.s
flag (dotAll) to match line breaks.ECMAScript 2019 (ES10) focused on improving usability and standardizing methods for working with data:
flatMap()
: Methods for flattening arrays and mapping and flattening arrays in a single step.trimEnd()
: Methods for trimming spaces from the start and end of strings.catch
blocks.ECMAScript 2020 (ES11) introduced several significant new features:
??
): Allows checking for null
or undefined
more succinctly.?.
): Safely accesses deeply nested object properties without throwing an error if a reference is null
or undefined
.Number
.ECMAScript 2021 (ES12) brought improvements and new methods for working with data:
&&=
, ||=
, and ??=
).1_000_000
).ECMAScript 2022 (ES13) introduced:
await
directly inside modules without wrapping them in async functions.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.
ECMAScript 2024 (ES15) will likely introduce additional enhancements and features as the language continues to evolve. Look out for proposals from the JavaScript community.
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.
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).
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.
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);
}
};
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
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
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
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
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
Functions are a fundamental building block in JavaScript, allowing us to create reusable blocks of code. Here's a breakdown of function-related concepts:
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 + '!';
}
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 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!
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!
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!
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!
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
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.
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
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
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
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.
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 }
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.
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
});
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.
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.
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 allow you to interact with the document. Common methods include:
getElementById()
: Returns the element with the specified id.getElementsByClassName()
: Returns elements with the specified class name.querySelector()
: Returns the first matching element based on a CSS selector.createElement()
: Creates a new HTML element.const element = document.getElementById('myElement');
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 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
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
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');
});
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 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
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!');
});
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!');
});
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 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
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
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.
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()
: Displays an alert box with a message.window.innerWidth
: Returns the inner width of the window (including scrollbars).window.open()
: Opens a new browser window.window.alert('Hello, World!'); // Displays an alert box
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.
screen.width
: Returns the width of the screen in pixels.screen.height
: Returns the height of the screen in pixels.screen.colorDepth
: Returns the color depth of the screen (bits per pixel).console.log(screen.width); // Logs the width of the screen
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.
location.href
: Returns or sets the current page's URL.location.reload()
: Reloads the current page.location.assign()
: Loads a new document.console.log(location.href); // Logs the current URL of the page
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()
: Loads the previous URL in the history.history.forward()
: Loads the next URL in the history.history.go()
: Loads a specific page from the history.history.back(); // Navigates to the previous page
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()
: Displays a simple alert box with a message.confirm()
: Displays a dialog box that asks the user to confirm an action (OK/Cancel).prompt()
: Displays a dialog box asking the user for input.alert('This is an alert box!'); // Displays a simple alert
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()
: Executes a function after a specified number of milliseconds.setInterval()
: Repeatedly executes a function at specified intervals (in milliseconds).clearTimeout()
: Cancels a timeout set by setTimeout()
.clearInterval()
: Cancels an interval set by setInterval()
.setTimeout(() => { console.log('This runs after 2 seconds'); }, 2000);
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.
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.
HTMLFormElement
: Represents a form element in the DOM.form.submit()
: Submits a form programmatically.form.reset()
: Resets all form elements to their default values.document.querySelector('form').addEventListener('submit', function(event) {
event.preventDefault(); // Prevent form submission
console.log('Form submitted');
});
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()
: Adds a new entry to the browser's history stack without reloading the page.history.replaceState()
: Replaces the current history entry with a new one.history.back()
: Navigates to the previous page in the history stack.history.forward()
: Navigates to the next page in the history stack.history.pushState({ page: 1 }, "title 1", "?page=1");
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()
: Stores data persistently in local storage.localStorage.getItem()
: Retrieves data from local storage.sessionStorage.setItem()
: Stores data for the duration of the session.sessionStorage.getItem()
: Retrieves data from session storage.localStorage.setItem('username', 'JohnDoe');
console.log(localStorage.getItem('username')); // Logs 'JohnDoe'
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.
new Worker()
: Creates a new worker thread and runs JavaScript code in the background.worker.postMessage()
: Sends data to the worker thread.worker.onmessage
: Listens for messages from the worker thread.const worker = new Worker('worker.js');
worker.postMessage('Hello Worker');
worker.onmessage = function(event) {
console.log('Message from worker:', event.data);
};
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()
: Makes an HTTP request and returns a Promise that resolves with the Response object.response.json()
: Parses the response body as JSON.response.text()
: Parses the response body as text.fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log('Error:', error));
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 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.
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.
XMLHttpRequest
: A JavaScript object used to interact with servers to send and receive data.open(method, url)
: Initializes the request with the specified HTTP method (GET, POST) and URL.send()
: Sends the request to the server.let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.send();
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.
GET
: Retrieves data from the server.POST
: Sends data to the server.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');
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.
responseText
: Returns the response as plain text.responseXML
: Returns the response as an XML document.responseJSON
: The response data parsed as a JSON object (with appropriate parsing).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 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.
responseXML
: Retrieves the server's response as an XML document.XML DOM
: JavaScript can traverse the XML structure to extract relevant data.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 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 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 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 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.
Here are some examples of how AJAX can be used to enhance the functionality of web pages:
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 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 consists of key-value pairs, where the key is a string, and the value can be a string, number, object, array, or boolean.
{}
, and arrays are enclosed in square brackets []
.{
"name": "John",
"age": 30,
"city": "New York"
}
Both JSON and XML are used to store and transport data, but they have key differences:
JSON supports the following data types:
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
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}'
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"
};
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 is a simple API server used to simulate a RESTful API with CRUD operations. It is often used for prototyping and testing.
json-server
npm package.db.json
file as the data source.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 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 (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);
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 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:
$("#myID"); // Selects element with id="myID"
$(".myClass"); // Selects all elements with class="myClass"
div
, p
, button
).
$("p"); // Selects all
elements
$("[type='text']"); // Selects input elements with type="text"
$("#parent > div"); // Selects
elements that are direct children of #parent
jQuery provides several methods to manipulate the HTML content of an element:
$("#myDiv").html(); // Get HTML content
$("#myDiv").html("New content
"); // Set HTML content
$("#myDiv").text(); // Get text content
$("#myDiv").text("New text content"); // Set text content
$("#myImage").attr("src"); // Get src attribute of image
$("#myImage").attr("src", "newImage.jpg"); // Set new src for image
jQuery makes it easier to change CSS properties of elements dynamically:
$("#myDiv").css("color"); // Get color property
$("#myDiv").css("color", "red"); // Set color property to red
$("#myDiv").css({
"color": "red",
"background-color": "yellow"
});
$("#myDiv").addClass("newClass"); // Add class to element
$("#myDiv").removeClass("oldClass"); // Remove class from element
The DOM (Document Object Model) allows you to dynamically manipulate HTML elements. jQuery makes DOM manipulation easier:
$("#parent").append("New paragraph at the end
"); // Adds content at the end
$("#parent").prepend("New paragraph at the beginning
"); // Adds content at the beginning
$("#myDiv").remove(); // Removes the element from the DOM
$("#myDiv").empty(); // Empties the content inside the element
let clonedElement = $("#myDiv").clone();
$("#myDiv").wrap("");
JavaScript offers several libraries and APIs to create graphics, plots, charts, and visualizations for web pages. Here are some of the most popular options:
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.
<canvas id="myCanvas" width="500" height="500"></canvas>
To access the canvas and draw on it, you use JavaScript:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 100, 100); // Draw a blue square
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.
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>
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);
}
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.
This section provides various JavaScript examples to help you understand the core concepts and techniques for web development.
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".
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.
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.
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.
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.
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.
Practice is key to mastering JavaScript. Below are some exercises to help you improve your skills:
Test your JavaScript knowledge with quizzes. Here are some sample questions:
undefined
mean in JavaScript?let
, const
, and var
.this
keyword in JavaScript?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.
The JavaScript syllabus typically includes the following topics:
Prepare for JavaScript-related interviews with the following tips and common questions:
==
and ===
in JavaScript?Join a JavaScript bootcamp to enhance your skills quickly. Bootcamps provide structured learning, real-world projects, and support:
After completing your JavaScript learning journey, you can earn a certificate to validate your skills. Some popular platforms offering certificates are:
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 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.
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.