The JavaScript language is commonly used for coding interactive web pages and web applications.
With ES6, let and const become block-scoped variables, while var becomes function-scoped. The let type allows for assignment, the const type is for variables that don't change, and the var type is for variables with function scope.
let x = 10;
x = 20; // Valid: x can be reassigned a new value
let y = 5;
let y = 15; // Invalid: Trying to redeclare y within the same block
const PI = 3.14;
PI = 3.14159; // Invalid: Trying to reassign a new value to PI
const myArray = [1, 2, 3];
myArray.push(4); // Valid: Modifying the array by adding a new element
var a = 5;
var a = 10; // Valid: Redeclaring a within the same scope
function example() {
var b = 15;
if (true) {
var b = 20; // Same variable b, as var does not have block scope
console.log(b); // Output: 20
}
console.log(b); // Output: 20
}
example();
The hoisting process in JavaScript involves moving variable and function declarations to the top of their containing scope during compilation.
var x1;
x1 = 5;
console.log(x1); // 5
x2 = 10;
console.log(x2); // 10
var x2;
var x3;
console.log(x3); // undefined
x3 = 15;
x4 = 20;
var x4;
console.log(x4); // 20
var x5;
console.log(x5); // undefined
console.log(x6); // undefined
var x6 = 25;
y1 = "25";
let y1;
console.log(y1); // ReferenceError: Cannot access 'y1' before initialization
z1 = "30";
const z1;
console.log(z1); // SyntaxError: Missing initializer in const declaration
When a function is defined within another function in JavaScript, the inner function has access to the outer function's variables even after it has finished executing.
function outerFunction() {
var outerVariable = "I'm from the outer function";
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
var closure = outerFunction();
closure(); // Output: "I'm from the outer function"
An event delegation technique involves adding an event listener to a parent element to handle events occurring on its children. As a result, the number of event handlers is minimized and performance is improved.
<!DOCTYPE html>
<html>
<head>
<title>Event Delegation Example</title>
</head>
<body>
<ul id="myList">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
</ul>
<script>
// Attach the event handler to the parent element
const list = document.getElementById('myList');
list.addEventListener('click', function(event) {
// Check if the clicked element is an <li> element
if (event.target.nodeName === 'LI') {
// Get the text content of the clicked <li> element
const text = event.target.textContent;
console.log('Clicked:', text);
}
});
</script>
</body>
</html>
When == is used, the equality is compared after type conversion while === is used to check for strict equality when no type conversion is involved.
//Strict Equality (===)
console.log(5 === 5); // true
console.log("5" === 5); // false (different types)
console.log(5 === "5"); // false (different types)
console.log(true === true); // true
console.log(null === undefined); // false (different types)
//Loose Equality (==)
console.log(5 == 5); // true
console.log("5" == 5); // true (converted string to number)
console.log(5 == "5"); // true (converted string to number)
console.log(true == 1); // true (converted boolean to number)
console.log(null == undefined); // true (special case)
In JavaScript, you can prevent the default behavior of an event by using the event.preventDefault() method.
<!DOCTYPE html>
<html>
<head>
<title>Event.preventDefault() Example</title>
</head>
<body>
<a href="https://www.techstackguru.com/" id="myLink">Click me</a>
<script>
document.getElementById("myLink").addEventListener("click", function(event) {
event.preventDefault(); // Prevent the link from navigating to a new page
console.log("Link clicked, but default behavior prevented");
});
</script>
</body>
</html>
In JavaScript, there are several types of errors, such as syntax errors, runtime errors, and logical errors.
//Syntax Errors
if (x == 5 { // Missing closing parenthesis
console.log("x is equal to 5");
}
//Reference Errors
console.log(x); // ReferenceError: x is not defined
//Type Errors
var x = "Hello";
console.log(x.toUpperCase()); // TypeError: x.toUpperCase is not a function
//Range Errors
var arr = [1, 2, 3];
console.log(arr[5]); // RangeError: Invalid array length
//Logic Errors
function calculateAverage(numbers) {
var sum = 0;
for (var i = 0; i <= numbers.length; i++) {
sum += numbers[i];
}
return sum / numbers.length;
}
var result = calculateAverage([1, 2, 3]);
console.log(result); // NaN (Not a Number)
//EvalErrors
eval("x ++ y"); // EvalError: invalid increment operand
//URIErrors
decodeURI('%'); // URIError: URI malformed
Programmers use the this keyword to refer to a methods object or the context within which it is called.
const employee = {
firstName: "Vishal",
lastName : "Torgal",
getFullName : function() {
return this.firstName + ' ' + this.lastName;
}
};
console.log(employee.getFullName()); //Vishal Torgal
An object can inherit properties and methods from another object via a prototype chain in JavaScript. When an objects properties or methods are not available, it uses the prototype object as a fallback.
//Creating objects with their own properties:
const adam = Object.create(personPrototype);
adam.name = "Vishal";
adam.age = 19;
console.log(adam.name); // Output: Vishal
console.log(adam.age); // Output: 19
Asynchronous programming allows tasks to be executed concurrently without blocking execution flow, in contrast to synchronous programming which executes tasks one after the other in a blocking manner.
//Synchronous Programming:
console.log("Start");
function synchronousTask() {
console.log("Synchronous Task");
}
synchronousTask();
console.log("End");
//Output
Start
Synchronous Task
End
//Asynchronous Programming:
console.log("Start");
function asynchronousTask() {
setTimeout(function() {
console.log("Asynchronous Task");
}, 2000);
}
asynchronousTask();
console.log("End");
//Output
Start
End
Asynchronous Task
JavaScript allows you to create new objects by using
//Object Literal
const person = {
name: "Katha",
age: 8,
greet: function() {
console.log(this.name);
}
};
person.greet() //Katha
//Constructor Function
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log(this.name);
};
}
const obj = new Person("Astha", 13);
obj.greet(); //Astha
//Object.create()
const personPrototype = {
greet: function() {
console.log(this.name);
}
};
const obj = Object.create(personPrototype);
obj.name = "Kanishka";
obj.age = 2;
obj.greet(); //Kanishka
Whenever the bind() method is invoked, it will set the this keyword to a specific value, regardless of how it is called.
const person = {
firstName: 'Aarush',
lastName: 'P',
};
// Creating a function
function hello(greeting) {
console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}
// Using bind() to bind the function to the person object
const boundHello = hello.bind(person);
// Calling the bound function
boundHello('Hi'); //Hi Aarush P
In JavaScript, the map() method performs transformations on each element of an array and returns a new array with the results.
// Original array
const num = [1, 2, 3, 4, 5];
// Using map() to double each number
const doubledNum = num.map((num) => num * 2);
console.log(doubledNum);
The Array.isArray() method can be used to determine whether a variable is an array.
// Check if a value is an array
console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray('Hello')); // false
console.log(Array.isArray({ a: 1 })); // false
// Check if a variable is an array
const fruits = ['apple', 'banana', 'orange'];
console.log(Array.isArray(fruits)); // true
const person = { name: 'John', age: 25 };
console.log(Array.isArray(person)); // false
JavaScript provides several methods for cloning objects, including Object.assign(), spread syntax, or JSON.parse(JSON.stringify()).
//Spread Operator(...)
const originalObj = { name: 'John', age: 25 };
const clonedObj = { ...originalObj };
console.log(clonedObj); //{ name: 'John', age: 25 }
//Object.assign()
const originalObj = { name: 'John', age: 25 };
const clonedObj = Object.assign({}, originalObj);
console.log(clonedObj); //{ name: 'John', age: 25 }
//JSON.parse() and JSON.stringify()
const originalObj = { name: 'John', age: 25 };
const clonedObj = JSON.parse(JSON.stringify(originalObj));
console.log(clonedObj); //{ name: 'John', age: 25 }
In the DOM hierarchy, an event triggered on a particular element, such as a button, will also trigger on all its parents. The propagation of an event from the innermost element to its ancestors is called event bubbling.
<div id="outer">
<div id="inner">
<button id="btn">Click me!</button>
</div>
</div>
document.getElementById("outer").addEventListener("click", function() {
console.log("Outer div clicked!");
});
document.getElementById("inner").addEventListener("click", function() {
console.log("Inner div clicked!");
});
document.getElementById("btn").addEventListener("click", function() {
console.log("Button clicked!");
});
When a CSS selector is specified, querySelector() will select the first element matching that CSS selector.
//HTML
<div id="container">
<h1>Title</h1>
<p class="content">Lorem ipsum dolor sit amet.</p>
<p class="content">Consectetur adipiscing elit.</p>
</div>
//JavaScript
// Select the first <p> element with the class "content"
const firstParagraph = document.querySelector('p.content');
// Log the text content of the selected element
console.log(firstParagraph.textContent);
//Output
Lorem ipsum dolor sit amet.
JavaScripts arrow functions enable function expressions to be written in a concise manner. Their syntax is shorter, and they inherit this value from their surrounding scopes.
// Regular function expression
const addRegular = function (a, b) {
return a + b;
};
console.log(addRegular(2, 3)); // Output: 5
// Arrow function
const addArrow = (a, b) => a + b;
console.log(addArrow(2, 3)); // Output: 5
JavaScript provides functions that can be used to convert strings into numbers, such as parseInt() or parseFloat().
let str = "42";
let num = parseInt(str);
console.log(num); // Output: 42
console.log(typeof num); // Output: number
let str = "3.14";
let num = parseFloat(str);
console.log(num); // Output: 3.14
console.log(typeof num); // Output: number
When setTimeout() is invoked, a function or code snippet will run after a specified period of time.
function greet() {
console.log("Hello, world!");
}
setTimeout(greet, 2000); // Schedule the greet function to run after 2000 milliseconds (2 seconds)
QuerySelectorAll() returns a static NodeList containing all elements matching a specified CSS selector.
<!DOCTYPE html>
<html>
<head>
<title>querySelectorAll Example</title>
</head>
<body>
<h1>querySelectorAll Example</h1>
<ul>
<li class="fruit">Apple</li>
<li class="animal">Tiger</li>
<li class="fruit">Orange</li>
</ul>
<script>
// Select all elements with class "fruit" and change their text color
const fruits = document.querySelectorAll('.fruit');
fruits.forEach(fruit => {
console.log(fruit)
});
</script>
</body>
</html
//Console
Apple
Orange
Async and await keywords enable asynchronous code to appear synchronous, allowing promise handling and handling asynchronous operations more easily.
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('Resolved after 2 seconds');
}, 2000);
});
}
async function asyncFunction() {
console.log('Async function started');
try {
const result = await resolveAfter2Seconds();
console.log(result);
console.log('Async function completed');
} catch (error) {
console.error('Error:', error);
}
}
asyncFunction();
//Output
Async function started
Resolved after 2 seconds
Async function completed
The array-like object can be converted to an array using the Array.from() method or by spreading it into an array [...object].
//Array.from()
const arrayLikeObject = { 0: 'foo', 1: 'bar', length: 2 };
const array = Array.from(arrayLikeObject);
console.log(array); // Output: ['foo', 'bar']
//Spread syntax (...)
const arrayLikeObject = { 0: 'foo', 1: 'bar', length: 2 };
const array = [...arrayLikeObject];
console.log(array); // Output: ['foo', 'bar']
//Array.prototype.slice()
const arrayLikeObject = { 0: 'foo', 1: 'bar', length: 2 };
const array = Array.prototype.slice.call(arrayLikeObject);
console.log(array); // Output: ['foo', 'bar']
//Array.prototype.concat()
const arrayLikeObject = { 0: 'foo', 1: 'bar', length: 2 };
const array = Array.prototype.concat.apply([], arrayLikeObject);
console.log(array); // Output: ['foo', 'bar']
A JavaScript reduce() method reduces an array to a single value by executing a reducer function on each element.
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue;
}, 0); //0 is initial value
console.log(sum); // Output: 15
To handle exceptions in JavaScript, try-catch statements can be used.
try {
// Code that may potentially throw an error
const result = someFunction();
console.log(result);
} catch (error) {
// Code to handle the error
console.error('An error occurred:', error);
}
In sessionStorage, data persists only during the session of the user.
As another type of web storage, localStorage is capable of retaining data even after the user closes the browser.
Cookie files are small pieces of data stored in the browser of a user. In addition to their expiration date, they can be accessed from both the client and the server.
// Example using session storage
sessionStorage.setItem('username', 'John');
console.log(sessionStorage.getItem('username')); // Output: John
// Example using local storage
localStorage.setItem('username', 'John');
console.log(localStorage.getItem('username')); // Output: John
// Example using cookies
document.cookie = 'username=John; expires=Thu, 31 Dec 2023 23:59:59 UTC; path=/';
console.log(document.cookie); // Output: username=John
If you want to convert an object to a JSON string, you can use the JSON.stringify() method.
const person = {
name: 'John',
age: 30,
city: 'New York'
};
const jsonString = JSON.stringify(person);
console.log(jsonString); //{"name":"John","age":30,"city":"New York"}
When push() is used, one or more elements are added to the end of an array and the size of the array is recalculated.
const fruits = ['apple', 'banana', 'orange'];
fruits.push('mango');
console.log(fruits); // Output: ['apple', 'banana', 'orange', 'mango']
fruits.push('strawberry', 'grape');
console.log(fruits); // Output: ['apple', 'banana', 'orange', 'mango', 'strawberry', 'grape']
JavaScript provides methods like splice(), pop(), shift() and filter() for removing elements from arrays.
//splice()
const fruits = ['apple', 'banana', 'orange', 'mango'];
fruits.splice(1, 1); // Remove 1 element at index 1
console.log(fruits); // Output: ['apple', 'orange', 'mango']
//pop()
const fruits = ['apple', 'banana', 'orange'];
const removedElement = fruits.pop();
console.log(removedElement); // Output: 'orange'
console.log(fruits); // Output: ['apple', 'banana']
//shift()
const fruits = ['apple', 'banana', 'orange'];
const removedElement = fruits.shift();
console.log(removedElement); // Output: 'apple'
console.log(fruits); // Output: ['banana', 'orange']
//filter()
const fruits = ['apple', 'banana', 'orange'];
const filteredFruits = fruits.filter(fruit => fruit !== 'banana');
console.log(filteredFruits); // Output: ['apple', 'orange']
Call() and apply() invoke a function with specific arguments andthis value. There is a difference in how arguments are passed: call() accepts individual arguments, while apply() accepts an array-like object.
//call
function greet(name) {
console.log({name}); //{ name: 'John' }
}
greet.call(null, 'John');
//apply
function greet(name) {
console.log({name}); //{ name: 'Dark' }
}
greet.apply(null, ['Dark']);
To convert a number to a string, use the toString() method or concatenate it with an empty string.
//toString()
let number = 42;
let stringNumber = number.toString();
console.log(typeof stringNumber); // "string"
console.log(stringNumber); // "42"
//Using string concatenation
let number = 42;
let stringNumber = '' + number;
console.log(typeof stringNumber); // "string"
console.log(stringNumber); // "42"
JavaScript offers built-in mathematical functions and constants through the Math object.
// Example 1: Calculating the square root
let number = 16;
let squareRoot = Math.sqrt(number);
console.log(squareRoot); // 4
// Example 2: Generating a random number
let randomNum = Math.random();
console.log(randomNum); // Random number between 0 (inclusive) and 1 (exclusive)
// Example 3: Rounding a number
let floatNum = 3.14;
let roundedNum = Math.round(floatNum);
console.log(roundedNum); // 3
// Example 4: Using mathematical constants
let circleArea = Math.PI * Math.pow(radius, 2);
console.log(circleArea); // Area of a circle with radius 'radius'
Arrays can be filtered using the filter() method with the indexOf() function, or converting them to Sets and then back to arrays.
//Set
let array = [1, 2, 3, 4, 4, 5, 6, 6];
let uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4, 5, 6]
//filter() and indexOf()
let array = [1, 2, 3, 4, 4, 5, 6, 6];
let uniqueArray = array.filter((value, index) => array.indexOf(value) === index);
console.log(uniqueArray); // [1, 2, 3, 4, 5, 6]
//reduce() and includes()
let array = [1, 2, 3, 4, 4, 5, 6, 6];
let uniqueArray = array.reduce((acc, value) => {
if (!acc.includes(value)) {
acc.push(value);
}
return acc;
}, []);
console.log(uniqueArray); // [1, 2, 3, 4, 5, 6]
Generator functions allow you to generate a series of values over time by pausing and resuming their execution.
function* numberGenerator() {
yield 1;
yield 2;
yield 3;
}
const generator = numberGenerator();
console.log(generator.next()); // { value: 1, done: false }
console.log(generator.next()); // { value: 2, done: false }
console.log(generator.next()); // { value: 3, done: false }
console.log(generator.next()); // { value: undefined, done: true }
In order to check whether an object has a specific property, you can use hasOwnProperty() or the in operator.
//hasOwnProperty()
const obj = {
prop1: 'value1',
prop2: 'value2'
};
if (obj.hasOwnProperty('prop1')) {
console.log('obj has prop1');
} else {
console.log('obj does not have prop1');
}
//in operator
const obj = {
prop1: 'value1',
prop2: 'value2'
};
if ('prop1' in obj) {
console.log('obj has prop1');
} else {
console.log('obj does not have prop1');
}
Comparisons of objects are usually based on their references, not their properties. It is possible to check the equality of two objects by manually comparing their properties.
//Strict property comparison
function areObjectsEqual(obj1, obj2) {
if (Object.keys(obj1).length !== Object.keys(obj2).length) {
return false;
}
for (let key in obj1) {
if (obj1[key] !== obj2[key]) {
return false;
}
}
return true;
}
const obj1 = { prop1: 'value1', prop2: 'value2' };
const obj2 = { prop1: 'value1', prop2: 'value2' };
console.log(areObjectsEqual(obj1, obj2)); // true
//JSON serialization:
function areObjectsEqual(obj1, obj2) {
const str1 = JSON.stringify(obj1);
const str2 = JSON.stringify(obj2);
return str1 === str2;
}
const obj1 = { prop1: 'value1', prop2: 'value2' };
const obj2 = { prop1: 'value1', prop2: 'value2' };
console.log(areObjectsEqual(obj1, obj2)); // true
//Library functions
const obj1 = { prop1: 'value1', prop2: 'value2' };
const obj2 = { prop1: 'value1', prop2: 'value2' };
console.log(_.isEqual(obj1, obj2)); // true (using Lodash)
console.log(R.equals(obj1, obj2)); // true (using Ramda)
Promises represent the completion or failure of asynchronous operations and are used to chain callbacks and catch errors.
const fetchData = new Promise((resolve, reject) => {
// Simulating an asynchronous operation (e.g., fetching data from a server)
setTimeout(() => {
const data = 'Some fetched data';
if (data) {
resolve(data); // Operation succeeded
} else {
reject('Data not found'); // Operation failed
}
}, 2000);
});
// Consuming the promise
fetchData
.then((result) => {
console.log('Data:', result);
})
.catch((error) => {
console.log('Error:', error);
});
In shallow copies, properties of the original object are referenced, while in deep copies, the original object is completely duplicated.
//Shallow Copy
let dev1 = {name:'Vishal'}
let dev2 = dev1; //Shallow Copy
console.log(dev1); //{ name: 'Vishal' }
dev2.name = 'Torgal'
console.log(dev1); //{ name: 'Torgal' }
console.log(dev2); //{ name: 'Torgal' }
//Deep Copy
let dev1 = {name:'Vishal'}
let dev2 = JSON.parse(JSON.stringify(dev1)); //Deep Copy
console.log(dev1); //{ name: 'Vishal' }
dev2.name = 'Torgal'
console.log(dev1); //{ name: 'Vishal' }
console.log(dev2); //{ name: 'Torgal' }
Promise constructors can be used to wrap a callback-based function in a promise. The promise can then be resolved or rejected based on the result of the callback.
// Callback-based function
function fetchData(callback) {
// Simulating an asynchronous operation
setTimeout(() => {
const data = 'Some data';
if (data) {
callback(null, data); // Call the callback with the result
} else {
callback('Error: Data not found', null); // Call the callback with an error
}
}, 2000);
}
// Promise-based function
function fetchDataPromise() {
return new Promise((resolve, reject) => {
// Invoke the original function inside the Promise executor
fetchData((error, data) => {
if (error) {
reject(error); // Call reject with the error
} else {
resolve(data); // Call resolve with the result
}
});
});
}
// Usage of the promise-based function
fetchDataPromise()
.then((data) => {
console.log('Data:', data);
})
.catch((error) => {
console.error('Error:', error);
});
An event-driven program is one that follows the flow of events occurring in the program, such as user actions or system events.
// HTML:
// <button id="myButton">Click me!</button>
// JavaScript:
const button = document.getElementById('myButton');
// Event Listener registration
button.addEventListener('click', function(event) {
console.log('Button clicked!');
});
console.log('Waiting for button click...');
// The program continues to execute while waiting for events
Navigator.userAgent gives you access to the user agent string for the browser.
const userAgent = navigator.userAgent;
console.log(userAgent);
You can use the fetch() function to make HTTP requests and asynchronously retrieve resources.
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not OK');
}
return response.json(); // Parse the response body as JSON
})
.then(data => {
console.log('Data:', data);
})
.catch(error => {
console.error('Error:', error);
});
To sort an array of objects based on a specific property value, you can use the sort() method with a custom comparison function.
const people = [
{ name: 'John', age: 25 },
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 20 }
];
// Sorting the array based on the 'age' property in ascending order
people.sort((a, b) => a.age - b.age);
console.log(people);
//Output
[
{ name: 'Bob', age: 20 },
{ name: 'John', age: 25 },
{ name: 'Alice', age: 30 }
]
In the Object.keys() method, enumerable property names are returned in an array.
const person = {
name: 'John',
age: 25,
occupation: 'Engineer'
};
const keys = Object.keys(person);
console.log(keys); //[ 'name', 'age', 'occupation' ]
A string can be converted to uppercase or lowercase using the toUpperCase() and toLowerCase() methods.
const myString = 'Hello, World!';
const uppercaseString = myString.toUpperCase();
console.log(uppercaseString); // Output: "HELLO, WORLD!"
const lowercaseString = myString.toLowerCase();
console.log(lowercaseString); // Output: "hello, world!"
A module contains related functions, variables, and classes within a self-contained unit of code. By using it, code can be better organized, reusable, and pollution of global namespaces can be avoided.
// File: mathUtils.js (module)
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
// File: main.js (usage)
import { add, subtract } from './mathUtils.js';
console.log(add(5, 3)); // Output: 8
console.log(subtract(10, 4)); // Output: 6
When dealing with asynchronous code, you can use callbacks, promises, or the newer async/await syntax, which lets you handle nonblocking operations without blocking the main thread.
//Using Callbacks
function fetchData(callback) {
// Simulating an asynchronous operation
setTimeout(() => {
const data = 'Some data';
callback(null, data);
}, 2000);
}
fetchData((error, data) => {
if (error) {
console.error('Error:', error);
} else {
console.log('Data:', data);
}
});
//Using Promises
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = 'Some data';
resolve(data);
}, 2000);
});
}
fetchData()
.then(data => {
console.log('Data:', data);
})
.catch(error => {
console.error('Error:', error);
});
//Using Async/await
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = 'Some data';
resolve(data);
}, 2000);
});
}
async function fetchDataAsync() {
try {
const data = await fetchData();
console.log('Data:', data);
} catch (error) {
console.error('Error:', error);
}
}
fetchDataAsync();
Event loops are used by JavaScript to handle asynchronous operations. This guarantees that long-running operations are handled in a non-blocking manner, allowing the program to remain responsive while it waits for them to complete. Event loops continuously check the event queue for new tasks and execute them one by one.
console.log('Start');
// Asynchronous setTimeout function
setTimeout(function() {
console.log('Async task 1');
}, 2000);
// Synchronous task
console.log('Sync task');
// Asynchronous setTimeout function
setTimeout(function() {
console.log('Async task 2');
}, 0);
console.log('End');
//Output
Start
Sync task
End
Async task 2
Async task 1
In JavaScript, web APIs refer to a set of APIs (Application Programming Interfaces) provided by web browsers. Through these APIs, JavaScript code interacts with the browser environment and performs various tasks.
//***DOM API***
// Get an element by its ID
const element = document.getElementById('myElement');
// Manipulate element content
element.textContent = 'Hello, world!';
// Add an event listener
element.addEventListener('click', () => {
console.log('Element clicked!');
});
//***Fetch API***
fetch('https://api.com/data')
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
//***localStorage API***
// Store a value
localStorage.setItem('username', 'John');
// Retrieve a value
const username = localStorage.getItem('username');
console.log(username); // Output: John
// Remove a value
localStorage.removeItem('username');
//***Geolocation API***
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
console.log(latitude);
console.log(longitude);
}, error => {
console.error(error);
});
} else {
console.error('Geolocation is not supported by this browser.');
}
//***WebSockets API***
const socket = new WebSocket('wss://example.com/socket');
// Connection opened
socket.addEventListener('open', event => {
console.log('WebSocket connected.');
socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', event => {
console.log('Received message:', event.data);
});
// Connection closed
socket.addEventListener('close', event => {
console.log('WebSocket disconnected.');
});