Day_1
1. JS Introduction
JavaScript (JS) is versatile (it can be used for front-end, back-end, mobile app, and even desktop
application development) and widely-used programming language primarily known for it role in web
development. And it is one of the core technologies of World Wide Web and plays a fundamental role in
creating dynamic and interactive web pages and web applications.
Purpose: JavaScript was initially created to add interactivity and functionality to web pages. It allows
when developers to create features like form validation, Animations, Real-time updates, And interactive
user interfaces in web applications.
Client side scripting: Is primarily used on the client side meaning directly in the users web browser. This
enables web developers to create responsive and dynamic web pages that can react to user actions
without the need to communicate with web server for every interaction.
Server-Side Javascript: JavaScript is primarily used on the claim side it can also be used on the server
side with platforms like [Link]. This has let to the development of full stack JavaScript applications
were both the front-end and back-end of the web application are written in JavaScript.
Syntax: JavaScript has a C style syntax, making it relatively easy to learn especially for those with
experience in other programming languages. It uses variables, functions, loops and conditional
statements to perform various tasks.
DOM manipulation: Javascript can interact with a Document Object Model (DOM), which represents the
structure and content of the web page. This allows developers to access and modify elements on the
webpage dynamically.
Even-Driven: Javascript operates on an event driven model. It can respond to events such as user clicks,
mouse moments, keyboard inputs, and more making it well suited for building interactive user interfaces.
Cross browser compatibility: Javascript is supported by all browsers including Chrome, Firefox, Safari
and Edge, ensuring that code written in javascript will work consistently across different browsers.
Frameworks and Libraries: JavaScript has a vast ecosystem of frameworks and libraries such as React,
Angular, [Link] and jQuery, which provide pre-built components and tools to simplify web development
tasks and enhance productivity.
Asynchronous programming: JavaScript supports a synchronous programming allowing tasks like
making network requests and handling data to be perform efficiently without blocking the main program
flow. Promises and async or await are features commonly used for managing asynchronous operation.
1
Day_1
WHAT IS JAVASCRIPT?
JavaScript is a high level, Interpreted scripting language. JavaScript is primarily used for client side
scripting which means it directly runs in users web browser. This enables developers to create interactive
web pages and web applications.
HISTORY OF JAVASCRIPT?
JavaScript was created by Brendan Eich while working at Netscape Communications Corporation in the
mid 1990s. It was originally named LiveScript but was nature remained JavaScript to write the
popularity of Java. *Despite the name similarity JavaScript and Java and entirely different languages.
Key features of JavaScript
● Interactivity: JavaScript allows you to add interactivity to web pages. You can respond to user
actions like clicks, form submissions and keyboard input.
● Cross platform: JavaScript works across different browsers and platforms making it a universal
language for web development.
● Event driven: It is event driven meaning it response to events like mouse click and keyboard inputs.
This event driven nature makes it ideal for creating interactive user interfaces.
● Asynchronous: JavaScript supports asynchronous programming enabling task like fetching data
from server without blocking the user interface.
How JavaScript is used
● Client-side web development: The most common use of JavaScript is for enhancing functionality
of websites. It can modify the DOM, handle form validations, and create animations.
● Web applications: JavaScript is the backbone of many web applications including popular
frameworks like React, Angular, and [Link].
● Server side development: While JavaScript is mainly used on the plane side it can also be used on
the server side with platforms like [Link].
● Mobile app development: JavaScript can be used to develop the mobile applications using
frameworks like react native.
Summary
JavaScript is a powerful and essential programming language for web development enabling developers to
create dynamic, Interactive and responsive web applications that enhance the user experience on the internet.
Its versatility and wide-spread adaption make it valuable skill for web developers and key technology for
building modern websites and web based applications.
2
Day_1
2. JS Syntax
Understanding JS syntax is fundamental to work with JS effectively.
In HTML, the <script> tag is used to include JavaScript code within an HTML document. The <script> tag
can be placed in the <head> or <body> section of your HTML document and it can be used to either
embed JavaScript code directly or reference and external JavaScript file.
When you include JavaScript code directly within the <script> tags. This code will be executed when
browser encounters it.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<h1> Using Javascript Alert </h1>
<script>
alert("Hello, World!");
</script>
</body>
</html>
The JavaScript code enclosed within the <script> tags will display and alert when the page loads.
* It is important to place the <script> tags appropriately within the HTML document as the order in which
scripts are loaded and executed than impact the behaviour of your web page. Additionally when using
external JavaScript file, ensure that the file path specified in the src attribute is correct and accessible
from the location of your HTML file.
Statements and expressions
JavaScript is composed of statements and expressions.
*A statement is a complete line of code that performs and action.
Example: Declaring a variable or invoking a function.
[Link](sum); //This calls the log function to print the value (statement)
* An expression is a piece of code that evaluates to a value.
Example: 2+2 is an expression that evaluates to 4.
let sum = 2 + 2; //'let sum = 2 + 2;' is a statement, '2 + 2' is an expression
Comments
3
Day_1
Comments in JavaScript are used to explain code and are ignored by the interpreter.
1. Single-line comments: Start with //
// This is a single-line comment
let x = 10; // Declare a variable
2. Multiline comments: Enclosed within /* */
/*
This is a multi-line comment.
It can span multiple lines.
*/
Variables
Variables are used to store and manage data.
1. Use let, const, or var to declare variables.
let a = 5;
const b = 10;
var c = 15;
2. Variable names must start with a letter, _, or $.
let name = "Sheldon";
let _privateVar = "secret";
let $dollarVar = 100;
3. Variable names cannot start with a number.
// let 1number = 10; // Invalid – will cause SyntaxError
4. Variable names are case-sensitive.
let age = 25;
let Age = 30;
[Link](age); // 25
[Link](Age); // 30
5. Do not use JavaScript reserved keywords as variable names.
4
Day_1
// let class = "Physics"; //Invalid – 'class' is a reserved keyword
6. Use let for changeable values, const for constants.
let score = 0;
score = 10; // allowed
const pi = 3.14;
// pi = 3.1415; // Error – cannot reassign const
7. Avoid using var in modern code (it's function-scoped).
function testVar() {
if (true) {
var test = "visible outside block"; // function-scoped
}
[Link](test); // visible
}
testVar();
8. Use meaningful and descriptive variable names.
let userAge = 22;
let userName = "Alice";
9. let and const cannot be re-declared in the same scope.
let city = "Delhi";
// let city = "Mumbai"; // Error – re-declaration not allowed with let
10.Uninitialized const declarations are not allowed.
// const country; // Error – must assign a value immediately
const country = "India"; // correct
Data Types
JavaScript has several built-in data types including:
Primitive Types: numbers, strings, booleans, null, undefined, symbols (ES6).
// Primitive Types
5
Day_1
let num = 42; // number
let str = "Hello, World!"; // string
let isActive = true; // boolean
let nothing = null; // null
let notDefined; // undefined (not initialized)
let sym = Symbol("id"); // symbol (ES6)
Objects: arrays, functions, objects, dates, etc.
// Object Types
let arr = [1, 2, 3]; // array (object type)
function greet() { // function (also an object type)
[Link]("Hi!");
}
let person = { // object
name: "Sheldon",
age: 25
};
let today = new Date(); // date object
// Logging all values
[Link](num, str, isActive, nothing, notDefined, sym);
[Link](arr, greet, person, today);
Operators
1. Arithmetic Operators
These are used to perform mathematical operations.
let a = 10;
let b = 5;
[Link](a + b); // Addition: 10 + 5 = 15
[Link](a - b); // Subtraction: 10 - 5 = 5
[Link](a * b); // Multiplication: 10 * 5 = 50
[Link](a / b); // Division: 10 / 5 = 2
[Link](a % b); // Modulus (remainder): 10 % 5 = 0
[Link](a ** b); // Exponentiation: 10 ** 5 = 100000
6
Day_1
2. Assignment Operators
Used to assign values to variables.
let x = 10;
x += 5; // Equivalent to x = x + 5; x becomes 15
x -= 3; // Equivalent to x = x - 3; x becomes 12
x *= 2; // Equivalent to x = x * 2; x becomes 24
x /= 4; // Equivalent to x = x / 4; x becomes 6
x %= 3; // Equivalent to x = x % 3; x becomes 0
3. Comparison Operators
Used to compare two values and return true or false.
let num1 = 10;
let num2 = 5;
[Link](num1 == num2); // Equal to (Value): false
[Link](num1 === num2); // Strict equal to (Value and Type): false
[Link](num1 != num2); // Not equal to (Value): true
[Link](num1 !== num2); //Strict not equal to (Value and Type): true
[Link](num1 > num2); // Greater than: true
[Link](num1 < num2); // Less than: false
[Link](num1 >= num2); // Greater than or equal to: true
[Link](num1 <= num2); // Less than or equal to: false
4. Logical Operators
Used to perform logical operations.
let x = true;
let y = false;
[Link](x && y); // AND: false (both need to be true)
[Link](x || y); // OR: true (one or both need to be true)
[Link](!x); // NOT: false (reverses the boolean value)
5. Unary Operators
Perform operations on a single operand.
7
Day_1
let a = 10;
[Link](++a); // Increment: 11
[Link](--a); // Decrement: 10
[Link](+a); // Unary plus (coerces to a number, if possible)
//Unary plus is used to coerce (force or convert) the value of a to a
number (if possible).
[Link](-a); // Unary minus (negates the value)
6. Ternary (Conditional) Operator
A shorthand for if-else statements.
let age = 18;
let canVote = (age >= 18) ? "Yes" : "No";
[Link](canVote); // Output: Yes
7. Type Operators
Used to check types.
let value = 10;
[Link](typeof value); // "number" (checks type of value)
let obj = {};
[Link](typeof obj); // "object" (checks type of object)
[Link]([Link]([1, 2, 3])); // true (checks if it's an array)
8. Bitwise Operators
Operate on the binary representation of numbers.
let x = 5; // 0101 in binary
let y = 3; // 0011 in binary
[Link](x & y); // Bitwise AND: 1 (0101 & 0011 = 0001)
[Link](x | y); // Bitwise OR: 7 (0101 | 0011 = 0111)
[Link](x ^ y); // Bitwise XOR: 6 (0101 ^ 0011 = 0110)
[Link](~x); // Bitwise NOT: -6 (invert all bits)
8
Day_1
[Link](x << 1); // Left shift: 10 (0101 << 1 = 1010)
[Link](x >> 1); // Right shift: 2 (0101 >> 1 = 0010)
9. Spread Operator (...)
Used to expand elements of an array or object.
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5];
[Link](arr2); // [1, 2, 3, 4, 5]
let obj1 = { a: 1, b: 2 };
let obj2 = { ...obj1, c: 3 };
[Link](obj2); // { a: 1, b: 2, c: 3 }
10. Destructuring Assignment
Used to unpack values from arrays or objects.
// Array destructuring
let [a, b] = [1, 2, 3];
[Link](a, b); // Output: 1 2
// Object destructuring
let obj = { name: "Sheldon", age: 25 };
let { name, age } = obj;
[Link](name, age); // Output: Sheldon 25
11. Optional Chaining (?.)
Allows safe access to deeply nested properties.
let user = { profile: { name: "Sheldon" } };
[Link](user?.profile?.name); // Output: Sheldon
[Link](user?.address?.city); // Output: undefined (no error)
Conditional Statements
Conditional Statements allow you to make decisions in your code.
9
Day_1
1. if Statement
The if statement executes a block of code if a specified condition is true.
let age = 18;
if (age >= 18) {
[Link]("You are an adult.");
}
2. else Statement
The else statement executes a block of code if the condition in the if statement is false.
let age = 16;
if (age >= 18) {
[Link]("You are an adult.");
} else {
[Link]("You are a minor.");
}
3. else if Statement
The else if statement is used to specify a new condition to test if the previous conditions are
false.
let age = 20;
if (age < 18) {
[Link]("You are a minor.");
} else if (age >= 18 && age <= 65) {
[Link]("You are an adult.");
} else {
[Link]("You are a senior.");
}
10
Day_1
4. Ternary Operator (Conditional Operator)
The ternary operator is a shorthand for if-else statements. It has the format: condition ?
value_if_true : value_if_false.
let age = 22;
let message = (age >= 18) ? "You are an adult." : "You are a minor.";
[Link](message);
5. switch Statement
The switch statement is used to perform different actions based on different conditions. It's an
alternative to using multiple else if statements.
let fruit = "apple";
switch (fruit) {
case "apple":
[Link]("It's an apple.");
break;
case "banana":
[Link]("It's a banana.");
break;
default:
[Link]("Unknown fruit.");
}
The switch checks the value of fruit. If it matches "apple", it logs "It's an apple.". If none of
the cases match, the default block will execute.
Summary:
● if: Checks a condition and executes a block of code if it's true.
● else: Executes a block of code if the condition in if is false.
● else if: Used to check another condition if the if condition is false.
● Ternary Operator: A shorthand for if-else.
● switch: A cleaner alternative to multiple if-else for comparing one variable to different
values.
Loops
11
Day_1
Loops in JavaScript are used to execute a block of code repeatedly as long as a specified condition is met.
Here are the most common types of loops in JavaScript:
1. for Loop
The for loop repeats a block of code a certain number of times, based on a counter.
Syntax:
for (initialization; condition; increment/decrement) {
// Code to be executed
}
Example:
for (let i = 0; i < 5; i++) {
[Link](i);
}
Explanation: This loop will print the numbers from 0 to 4. The loop runs while i is less than 5, and i
is incremented after each iteration.
2. while Loop
The while loop executes a block of code as long as a condition is true.
Syntax:
while (condition) {
// Code to be executed
}
Example:
let i = 0;
while (i < 5) {
[Link](i);
i++;
}
12
Day_1
Explanation: This loop will print the numbers from 0 to 4. It keeps running while i is less than 5, and
i is incremented inside the loop.
3. do...while Loop
The do...while loop executes a block of code once, and then repeats the loop as long as the
condition is true.
Syntax:
do {
// Code to be executed
} while (condition);
Example:
let i = 0;
do {
[Link](i);
i++;
} while (i < 5);
Explanation: This loop will also print the numbers from 0 to 4. The difference is that the code block is
executed at least once, even if the condition is false initially.
4. for...in Loop
The for...in loop is used to iterate over the properties of an object.
Syntax:
for (let key in object) {
// Code to be executed
}
Example:
let person = { name: "John", age: 30, city: "New York" };
for (let key in person) {
[Link](key + ": " + person[key]);
}
13
Day_1
Explanation: This loop iterates over the keys of the person object and logs each key-value pair.
5. for...of Loop
The for...of loop is used to iterate over the values of an iterable object (like arrays, strings, etc.).
Syntax:
for (let value of iterable) {
// Code to be executed
}
Example:
let numbers = [10, 20, 30, 40];
for (let number of numbers) {
[Link](number);
}
Explanation: This loop iterates over the values of the numbers array and logs each value.
6. break and continue Statements
● break: Used to exit a loop early.
● continue: Skips the current iteration and moves to the next one.
Example with break:
for (let i = 0; i < 5; i++) {
if (i === 3) {
break; // Exit the loop when i is 3
}
[Link](i);
}
14
Day_1
Explanation: The loop will stop and exit when i is 3.
Example with continue:
for (let i = 0; i < 5; i++) {
if (i === 3) {
continue; // Skip the iteration when i is 3
}
[Link](i);
}
Explanation: The loop will skip the iteration when i is 3 and continue with the next value.
Summary:
● for: Ideal for loops with a known number of iterations.
● while: Repeats code as long as a condition is true.
● do...while: Executes code at least once, then repeats based on a condition.
● for...in: Iterates over object properties.
● for...of: Iterates over iterable objects like arrays.
● break: Exits the loop early.
● continue: Skips the current iteration and proceeds to the next.
Functions
In JavaScript, functions are blocks of reusable code that perform a specific task. They can accept inputs
(called parameters) and return an output (using the return keyword). Functions help in organizing code,
improving readability, and promoting reuse.
1. Function Declaration (Traditional Function)
A function is declared using the function keyword, followed by the function name, parameters
(optional), and a block of code.
Syntax:
function functionName(parameter1, parameter2) {
// Code to execute
return result; // (optional)
15
Day_1
Example:
function greet(name) {
[Link]("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
Explanation: This function greet takes a name parameter and logs a greeting message.
2. Function Expression (Anonymous Function)
A function expression is a function without a name (an anonymous function) that can be assigned to a
variable. These are often used as callbacks or arguments for other functions.
Syntax:
let functionName = function(parameter1, parameter2) {
// Code to execute
return result; // (optional)
};
Example:
let add = function(a, b) {
return a + b;
};
[Link](add(5, 3)); // Output: 8
Explanation: This function is assigned to the variable add. It can be invoked using add(5, 3).
3. Arrow Function (ES6)
Arrow functions provide a shorter syntax for writing functions. They are also anonymous functions
and do not have their own this context (useful in certain situations).
Syntax:
const functionName = (parameter1, parameter2) => {
// Code to execute
return result; // (optional)
};
16
Day_1
Example:
const multiply = (a, b) => {
return a * b;
};
[Link](multiply(4,5)); // Output: 20
Explanation: The arrow function syntax is more concise and avoids the need for the function
keyword.
4. Function with Default Parameters
JavaScript functions can have default parameters. If a parameter is not provided when the function is
called, it will take the default value.
Syntax:
function greet(name = "Guest") {
[Link]("Hello, " + name + "!");
}
Example:
greet(); // Output: Hello, Guest!
greet("Alice"); // Output: Hello, Alice!
Explanation: If name is not provided, it defaults to "Guest".
5. Function Returning a Value
Functions can return values using the return statement. If no return is provided, the function
returns undefined.
Syntax:
function add(a, b) {
return a + b;
}
Example:
let result = add(2, 3);
[Link](result); // Output: 5
Explanation: The function add calculates the sum and returns it.
17
Day_1
6. Function with Multiple Return Statements
A function can have multiple return statements inside different conditional blocks. As soon as a
return is encountered, the function exits and returns the value.
Example:
function checkEvenOdd(num) {
if (num % 2 === 0) {
return "Even";
} else {
return "Odd";
}
}
[Link](checkEvenOdd(4)); // Output: Even
[Link](checkEvenOdd(7)); // Output: Odd
Explanation: The function checks whether a number is even or odd and returns the result.
7. Immediately Invoked Function Expression (IIFE)
An IIFE is a function that is defined and executed immediately after its creation. This is often used for
creating private scopes and avoiding global variable conflicts.
Syntax:
(function() {
// Code to execute immediately
})();
Example:
(function() {
[Link]("This function runs immediately!");
})();
Explanation: This function runs immediately when defined, without the need to call it.
8. Function Scope
Functions have their own scope, meaning variables declared inside a function are not accessible
outside of it.
18
Day_1
Example:
function testScope() {
let a = 5;
[Link](a); // Output: 5
}
testScope();
[Link](a); // Error: a is not defined
Explanation: The variable a is local to the testScope function and cannot be accessed outside of it.
9. Function Parameters (Rest Parameters)
Rest parameters allow you to pass a variable number of arguments to a function, and they are stored
in an array.
Syntax:
function sum(...numbers) {
return [Link]((acc, num) => acc + num, 0);
}
Example:
[Link](sum(1, 2, 3, 4)); // Output: 10
[Link](sum(5, 10)); // Output: 15
Explanation: The function sum uses rest parameters to accept any number of arguments and
calculates their sum.
10. Function Expressions as Arguments
You can pass functions as arguments to other functions. This is known as callback functions.
Example:
function greetUser(callback) {
[Link]("Hello!");
callback();
}
greetUser(function() {
[Link]("Welcome to the site!");
});
19
Day_1
Explanation: A function is passed as an argument to the greetUser function, and it gets invoked
inside greetUser.
A callback is a function you give to another function so it can call it back when it’s done
doing something.
A callback is a function passed as an argument to another function, which is then invoked
(called back) later inside that function to complete some kind of routine or action.
Summary of Function Types:
1. Function Declaration: Traditional function.
2. Function Expression: Anonymous function assigned to a variable.
3. Arrow Function: Shorter syntax, no this context.
4. Default Parameters: Parameters with default values.
5. Returning a Value: Functions return values using return.
6. Multiple Returns: Functions can have multiple return statements.
7. IIFE (Immediately Invoked Function Expression): Functions executed immediately after
definition.
8. Function Scope: Variables inside a function are local to it.
9. Rest Parameters: Functions that accept a variable number of arguments.
10.Function Expressions as Arguments: Functions passed as arguments to other functions
(callbacks).
Objects
In JavaScript, an object is a data structure that allows you to store collections of key-value pairs.
An object is a collection of properties, where each property has a key (also called name) and a
value.
Example:
let person = {
name: "Sheldon",
age: 25,
isStudent: true,
20
Day_1
greet: function() {
[Link]("Hello, my name is " + [Link]);
}
};
[Link]([Link]); // Output: Sheldon
[Link](person["age"]); // Output: 25
[Link](); // Output: Hello, my name is Sheldon
Key Features:
● Keys are always strings (even if you don’t quote them).
● Values can be anything: strings, numbers, booleans, arrays, functions, or other objects.
● Functions inside objects are called methods.
Accessing and Updating:
[Link] = 26; // Update
[Link] = "Delhi"; // Add new property
delete [Link]; // Remove property
Arrays
In JavaScript, an array is a special type of object used to store multiple values in a single variable,
ordered by index.
An array is a list-like object that stores elements at numbered indexes starting from 0.
Example:
let fruits = ["apple", "banana", "mango"];
[Link](fruits[0]); // Output: apple
[Link](fruits[2]); // Output: mango
Common Array Methods:
[Link]("orange"); // Add to end
[Link](); // Remove from end
[Link]([Link]); // Get number of items
21
Day_1
Looping through an Array:
for (let i = 0; i < [Link]; i++) {
[Link](fruits[i]);
}
Or with forEach:
[Link](function(fruit) {
[Link](fruit);
});
22