Introduction to JavaScript :-
JavaScript is a programming language that is primarily used for web development. It allows developers to add interactivity, functionality, and dynamic behavior to websites. Unlike HTML (Hypertext Markup Language) and CSS (Cascading Style Sheets), which are markup and styling languages respectively, JavaScript is a full-fledged programming language capable of creating complex applications.
What is JavaScript?
JavaScript is a high-level, interpreted scripting language that was initially created to make web pages more interactive. It was first introduced by Netscape Communications Corporation in December 1995 and initially named "LiveScript," but later renamed "JavaScript" when Netscape partnered with Sun Microsystems. Despite the similar name, JavaScript has no relation to Java. JavaScript is a versatile language that can be used both on the client-side (in web browsers) and the server-side (with the help of platforms like Node.js). It's known for its flexibility, allowing developers to create everything from simple website animations to complex web applications.

Why Learn JavaScript?
There are several reasons why learning JavaScript is valuable:
- Versatility: JavaScript can be used for both front-end and back-end development, making it a versatile language for full-stack developers
- Popularity: JavaScript is one of the most widely-used programming languages in the world. Learning it opens up a vast number of job opportunities.
- Community and Resources: There's a large and active community of JavaScript developers, as well as an abundance of resources, libraries, and frameworks to facilitate development.
- Career Growth: Proficiency in JavaScript is highly sought after by employers, especially for web development roles. It can significantly enhance your career prospects.
- Compatibility: JavaScript works across different platforms and browsers, ensuring a consistent user experience for web applications.
Brief History of JavaScript
- 1995: JavaScript was created by Brendan Eich at Netscape Communications Corporation. It was originally called "LiveScript" but was later renamed "JavaScript" to capitalize on the popularity of Java.
- 1996: Microsoft adopted a similar language called JScript for use in Internet Explorer, leading to browser wars between Netscape and Microsoft.
- 1997: JavaScript was standardized under the name ECMAScript by Ecma International to ensure compatibility among different implementations. ECMAScript is the official name of the language specification.
- 2000s: With the rise of AJAX (Asynchronous JavaScript and XML), JavaScript became even more popular for creating dynamic and interactive web applications.
- 2010s: The development of various JavaScript libraries and frameworks like jQuery, AngularJS, React, and Vue.js further propelled the adoption of JavaScript for web development.
- Present: JavaScript continues to evolve rapidly, with new features and updates being added regularly. It remains a fundamental tool for building modern web applications.
- Variables :- Variables are containers for storing data values. JavaScript has three types of variable declarations: `var`, `let`, and `const`.
- Data Types :- Data types in JavaScript include numbers, strings, booleans, null, undefined, and symbols.
- Operators :- Operators are symbols that perform operations on variables and values. JavaScript supports various types of operators like arithmetic, assignment, comparison, logical, etc.
- Comments :- Comments are used to annotate code for better understanding. Single-line comments start with `//`, while multi-line comments are enclosed between `/*` and `*/`.
- Conditional Statements :- Conditional statements (if, else if, else) are used to execute different blocks of code based on certain conditions. if statements check a condition and execute a block of code if it's true. else if and else statements provide additional conditions to check if the previous condition(s) are false.
- Loops (for, while) :- Loops are used to execute a block of code repeatedly until a specified condition is met. for loops are typically used when the number of iterations is known. while loops are used when the number of iterations is unknown but a condition needs to be checked before each iteration.
- Declaring Functions :- You can declare a function using the function keyword, followed by the function name and parentheses `()`. If the function takes parameters, they are listed within the parentheses. The function body, containing the code to be executed, is enclosed in curly braces `{}`.
- Parameters and Arguments :- Parameters are placeholders for values that a function expects to receive when it is called. They are listed inside the parentheses of the function declaration. Arguments are the actual values passed to the function when it is invoked.
- Return Statements :- The return statement is used to specify the value that a function should return when it is called. It allows a function to compute a value and then return it to the code that called the function.
- Declaring Arrays :- You can declare an array by enclosing its elements within square brackets `[]`.
- Accessing Elements :- You can access elements in an array using their index. Array indices start from 0, so the first element is at index 0, the second at index 1, and so on.
- Array Methods :- Arrays in JavaScript come with built-in methods to manipulate their contents. Some common array methods include:
- 1. push() :- The `push()` method adds one or more elements to the end of an array and returns the new length of the array.
- 2. pop() :- The `pop()` method removes the last element from an array and returns that element.
- 3. shift() :- The shift() method removes the first element from an array and returns that element. It also shifts all subsequent elements to a lower index.
- 4. unshift() :- The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
JavaScriptfruits.push( "grape") ;
console.log( fruits ) ; // Output : [ "apple", "banana", "orange", "grape" ]
JavaScriptvar lastFruit = fruits.pop ( )
console.log( lastFruit ) ; // Output : "grape"
console.log( fruits ) ; // Output : [ "apple", "banana", "orange" ]
JavaScriptvar firstFruit = fruits.shift ( )
console.log( firstFruit ) ; // Output : "apple"
console.log( fruits ) ; // Output : [ "banana", "orange" ]
JavaScriptfruits.unshift ( " Kiwi ") ;
console.log( fruits ) ; // Output : [ "kiwi", "banana", "orange" ]
- Creating Objects :- There are several ways to create objects in JavaScript:
- 1. Object Literal Syntax:
- 2. Constructor Function:
- 3. Object.create() Method:
JavaScriptvar person = {
name : " Zoya " ,
age : 18 ,
city : "New york"
} ;
JavaScriptfunction Person ( name, age, city ) {
this.name = name ;
this.age = age ;
this.city = city ;
} ;
var person = new Person("John" , 30 , "New York" ) ;
JavaScriptvar person = Object . create ( null ) ;
person.name = " Zoya " ;
person.age = 18 ;
person.city = " New york " ;
- Accessing Object Properties :- You can access object properties using dot notation (object.property) or bracket notation (object['property']). Dot notation is more commonly used when the property name is known at development time, while bracket notation is useful when the property name is dynamic or contains special characters.
- Object Methods :- Methods in objects are functions associated with the object's properties. They allow objects to perform actions or calculations and interact with other parts of your code. Here's how you can define a method within an object:
- Accessing HTML Elements :- JavaScript provides several methods for accessing HTML elements within a document:
- 1. getElementById() : This method returns the element with the specified ID attribute.
JavaScript
var element = document.getElementById( "elementId") ;
- 2. getElementsByClassName() : This method returns a collection of elements with the specified class name.
JavaScript
var elements = document.getElementsByClassName( "className") ;
- 3. getElementsByTagName() : This method returns a collection of elements with the specified tag name.
JavaScript
var elements = document.getElementsByTagName( "tagName") ;
- 4. querySelector() : This method returns the first element that matches the specified CSS selector.
JavaScript
var element = document.querySelector( "selector") ;
- 5. querySelectorAll() : This method returns a static NodeList containing all elements that match the specified CSS selector.
JavaScript
var elements = document.querySelectorAll( "selector") ;
- 1. getElementById() : This method returns the element with the specified ID attribute.
- Modifying HTML Content, Attributes, and Styles :- Once you have accessed HTML elements, you can modify their content, attributes, and styles using various properties and methods:
- 1. Modifying Content : This property sets or returns the HTML content (inner HTML) of an element.
JavaScript
element.innerHTML = "New content" ;
- 2. Modifying Attributes : This method sets the value of the specified attribute on the element.
JavaScript
element.setAttribute = ( "attributeName" , "value" ) ;
- 3. Modifying Styles : This property allows you to directly modify the inline style of an element.
JavaScript
element.style.property = "value" ;
- 1. Modifying Content : This property sets or returns the HTML content (inner HTML) of an element.
- Event handling :- Event handling is the process of writing code to respond to events. In JavaScript, you can define event handlers that are triggered when a particular event occurs. These event handlers specify the actions to be taken in response to the event.
- Event Listeners :- Event listeners are functions that wait for a specific event to occur and then execute a block of code in response. They are used to attach event handlers to DOM elements. Event listeners can be added to elements to listen for various types of events, such as click, mouseover, submit, etc.
- Common DOM Events :- Here are some of the most commonly used DOM events:
- 1. click : The click event occurs when an element is clicked by the user.
JavaScript
element.addEventListener ( "click" , function ( ) {
console.log( "Clicked!") ;
} );
- 2. mouseover : The mouseover event occurs when the mouse pointer enters the boundaries of an element.
JavaScript
element.addEventListener ( "mouseover" , function ( ) {
console.log( "Mouse over!") ;
} );
- 3. submit : The submit event occurs when a form is submitted.
JavaScript
form.addEventListener ( "submit" , function ( event ) {
event.preventDefault( ) // Prevents the default form submission
console.log( "Form submitted!") ;
} );
- 4. keydown : The keydown event occurs when a key is pressed down.
JavaScript
document.addEventListener ( "keydown" , function ( event ) {
console.log( "Key pressed : "+ event.key ; )
} );
- 5. load : The load event occurs when a resource and its dependent resources have finished loading.
JavaScript
window.addEventListener ( "load" , function ( ) {
console.log( "Page loaded!") ;
} );
- 1. click : The click event occurs when an element is clicked by the user.
- Syntax Errors vs. Runtime Errors :-
- 1. Syntax Errors:
Syntax errors occur when the syntax of the code is incorrect and prevents the program from running. These errors are detected by the interpreter or compiler during the parsing phase before the program is executed. Examples include missing semicolons, mismatched parentheses, or misspelled keywords.
JavaScript
// Syntax error: Missing closing parenthesis
console.log( "Hello, world" ;
- 2. Runtime Errors:
Runtime errors occur during the execution of the program and can cause the program to terminate abruptly or produce unexpected results. Runtime errors are often caused by issues such as division by zero, accessing undefined variables, or calling undefined functions.
parentheses, or misspelled keywords.
JavaScript
// Runtime error: Division by zero
var result = 10 / 10 ;
console.log( result ) ;
- 1. Syntax Errors:
Syntax errors occur when the syntax of the code is incorrect and prevents the program from running. These errors are detected by the interpreter or compiler during the parsing phase before the program is executed. Examples include missing semicolons, mismatched parentheses, or misspelled keywords.
- try...catch Statements :- The try...catch statement is used in JavaScript to handle runtime errors gracefully by allowing you to catch and handle exceptions that occur within a block of code. The try block contains the code that may potentially throw an error, and the catch block contains the code to handle the error if it occurs. Using try...catch statements is an effective way to prevent runtime errors from crashing your program and provides an opportunity to gracefully handle exceptions, log errors, or take corrective actions as needed.
JavaScript
try {
// Code that may throw an error
var result = 10 / 0 ;
console.log( result ) ;
} catch ( error ) {
// Code to handle the error
console.log( " An error occurred: "+ error.message ) ;
}
- setTimeout and setInterval :-
- 1. setTimeout:
The setTimeout function is a built-in JavaScript function used to execute a specified piece of code once after a specified amount of time (in milliseconds) has elapsed.
JavaScript
setTimeout ( function( ) {
console.log( "Delayed message") ;
} , 2000 ) ; // Execute after 2000 milliseconds (2 seconds)
- 2. setInterval:
The setInterval function is similar to setTimeout, but it repeatedly executes a specified piece of code at specified intervals (in milliseconds) until it is cleared.
JavaScript
setInterval ( function( ) {
console.log( "Repeated message") ;
} , 1000 ) ; // Execute every 1000 milliseconds (1 second)
- 1. setTimeout:
The setTimeout function is a built-in JavaScript function used to execute a specified piece of code once after a specified amount of time (in milliseconds) has elapsed.
- Callback Functions :-
A callback function is a function that is passed as an argument to another function and is executed after a particular task has been completed or when a certain event occurs. Callback functions are commonly used in asynchronous JavaScript to handle asynchronous operations, such as fetching data from a server or processing user input. Callback functions are fundamental in asynchronous JavaScript programming as they enable you to handle asynchronous operations in a non-blocking manner, ensuring that your code remains responsive and efficient.
JavaScript
function fetchData ( callback ) {
// Simulate fetching data from a server
setInterval ( function( ) {
var data = { name : "John" , age : 30 ; }
callback ( data ) ; // Execute the callback function with the fetched data
} , 2000 ) ;
}
function displayData ( data ) {
console.log ( " Name : " + data.name + " , Age : " + data.age ) ;
}
fetchData ( displayData ) ; // Pass the displayData function as a callback
- Making Asynchronous Requests with XMLHttpRequest :- The XMLHttpRequest (XHR) object is a built-in JavaScript API used to make HTTP requests to a server and receive data in response. It is the traditional way of making asynchronous requests in JavaScript and is the foundation of AJAX.
- We create a new XMLHttpRequest object using `new XMLHttpRequest()`.
- We open a GET request to the specified URL using `xhr.open()`.
- We define an event handler function (`xhr.onreadystatechange`) that will be called when the state of the request changes.
- Inside the event handler, we check if the request has completed (`xhr.readyState === 4`) and if the status code is 200 (indicating a successful response).
- If the conditions are met, we log the response data (`xhr.responseText`).
- We use the `fetch()` function to initiate a GET request to the specified URL.
- The `fetch()` function returns a Promise that resolves to the Response object representing the response to the request.
- We use `.then()` to handle the response asynchronously. Inside the first `.then()` block, we check if the response is OK (status code 200). If not, we throw an error.
- If the response is OK, we parse the response body as JSON using `response.json()`, which returns another Promise.
- We use another `.then()` block to process the parsed JSON data.
- We use `.catch()` to handle any errors that may occur during the fetch operation. The Fetch API offers a more modern and powerful way of making asynchronous requests in JavaScript, with built-in support for Promises, simpler syntax, and improved error handling compared to XMLHttpRequest.
Basic Syntax
This is a
multi-line
comment
*/
Control Flow
console.log ( "Positive") ;
console.log ( "Negative") ;
console.log ( "Zero") ;}
for ( var i = 0 ; i < 5 ; i++ ) {
console.log ( i) ;
}
var i = 10 ;
while ( i < 5 ) {
console.log( i) ;
i ++ ;
}
Functions
In JavaScript, functions are reusable blocks of code that perform a specific task. They are fundamental building blocks of JavaScript programming and help in organizing code, promoting reusability, and making code easier to understand and maintain.
/* Declaring Functions */
function greet( ) {
console.log ( "Hello, world!") ;
}
/* Parameters and Arguments */
function greet(name) {
console.log ( " Hello, " ) + name + "!" ) ;
}
// "Alice" is an argument passed to the greet function
greet( name)
/* Return Statements */
function add( a, b ) {
return a + b ;
}
var result = add( 3 , 5 ) ; // result is assigned the value 8
Array
Arrays are data structures in JavaScript used to store multiple values in a single variable. They are ordered collections of elements, each identified by an index starting from 0. Arrays in JavaScript can hold values of different data types, including numbers, strings, objects, and even other arrays.
var fruits = [ "apple" , "banana" , "orange" ] ;
console.log( fruits [ 0 ] ); // Output : "apple"
console.log( fruits [ 1 ] ); // Output : "banana"
console.log( fruits [ 2 ] ); // Output : "orange"
Objects
In JavaScript, objects are complex data types that allow you to store collections of key-value pairs. They are versatile and can represent various entities, such as a person, a car, or any other real-world object. Objects in JavaScript are instances of their respective classes and are mutable, meaning their properties can be changed after creation.
console.log ( person.name ) ; // Output: "John"
console.log ( person[ age] ) ; // Output: 18
var person = {
name : " Zoya " ,
age : 18 ,
city : "New york" ,
greet : function( ) {
console.log ( " Hello, my name is " + this.name ) ;
}
} ;
person.greet( ) ; // Output: "Hello, my name is John"
Introduction to the Document Object Model (DOM)
The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of HTML and XML documents as a hierarchical tree where each node represents an element, attribute, or text in the document. The DOM provides a structured representation of the document, allowing scripts to dynamically access and manipulate its content, structure, and style.
Events
Events are actions or occurrences that happen in the system or in the DOM. Examples of events include a user clicking a button, moving the mouse pointer over an element, pressing a key on the keyboard, or a web page finishing loading.
Error Handling
Error handling is the process of anticipating, detecting, and resolving errors that may occur during the execution of a program. Errors can occur for various reasons, such as invalid user input, unexpected system behavior, or programming mistakes.
Introduction to Asynchronous JavaScript
Asynchronous JavaScript refers to the execution of code that does not necessarily run in sequence, meaning that certain operations can start, run, and complete independently of other code. This allows JavaScript to handle tasks such as fetching data from servers, processing user input, or performing animations without blocking the main execution thread.
Introduction to AJAX
AJAX, which stands for Asynchronous JavaScript and XML, is a technique used in web development to create asynchronous web applications. It allows you to send and receive data from a server asynchronously without interfering with the behavior and display of the existing page. With AJAX, you can update parts of a web page without requiring a full page refresh.
Example of Making a GET Request with XMLHttpRequest:
var xhr = new XMLHttpRequest ( ) ;
xhr.open ( "GET", "https://api.example.com/data", true ) ; // true for asynchronous
xhr.onreadystatechange = function ( ) {
if ( xhr.readyState === 4 && xhr.status === 200 )
console.log( xhr.responseText ) ; // Response data
}
};
xhr.send( ) ;
In this example:
Introduction to Fetch API
The Fetch API is a modern alternative to XMLHttpRequest for making HTTP requests in JavaScript. It provides a simpler and more flexible interface for fetching resources from the web. The Fetch API is based on Promises, allowing you to write cleaner and more concise code for handling asynchronous requests. The Fetch API offers a more modern and powerful way of making asynchronous requests in JavaScript, with built-in support for Promises, simpler syntax, and improved error handling compared to XMLHttpRequest.
Example of Making a GET Request with Fetch API:
fetch ( "https://api.example.com/data")
.then ( response => {
if ( ! response.ok ) {
throw new Error ( "HTTP error, status = " + response.status ) ;
}
return response. json( ) ;
} )
.then ( data => {
console.log ( data ) ; // Process the response data
} )
.catch ( error => {
console.error ( "Fetch error:", error ) ;
} )
In this example: