FSD1
FSD1
FULLSTACK DEVELOPMENT
Introduction to JavaScript
🔹 What is JavaScript?
JavaScript (JS) is a lightweight, interpreted, client-side scripting language used
for making web pages interactive. It is used to create dynamic web applications,
handle events, validate forms, and more.
🔹 Features of JavaScript
Client-Side Execution: Runs in the browser, reducing server load.
Interactivity: Enables user interaction (e.g., form validation, animations).
Event-Driven: Executes code based on user actions (e.g., clicks,
keypresses).
Cross-Platform: Works across all browsers and devices.
Supports Object-Oriented Programming (OOP).
🔹 History of JavaScript
1995: Developed by Brendan Eich at Netscape (originally named
Mocha).
1996: Renamed to JavaScript and became part of Netscape Navigator.
1997: Standardized as ECMAScript (ES1) by ECMA International.
2009: ES5 introduced modern features.
2015: ES6 (ECMAScript 2015) introduced let, const, arrow functions,
classes, and modules.
Present: Regular updates (ES6, ES7, ES8, ESNext) continue improving
JS.
🔹 Writing JavaScript
JavaScript can be written in three ways:
1. Inline JS (inside HTML elements)
<button onclick="alert('Hello, World!')">Click Me</button>
//html
<script src="script.js"></script>
JavaScript Statements
1 Declaration Statements
Declaration statements define variables, constants, or functions.
Example: Variable Declaration
var x; // Declares a variable
let y = 10; // Declares and assigns a value
const PI = 3.14; // Declares a constant
2️ Assignment Statements
Used to assign values to variables.
Example:
let a = 5; // Assigns 5 to a
let b = 10; // Assigns 10 to b
b += a; // Adds a to b (b = b + a → 15)
console.log(b);
3️ Expression Statements
Expressions that produce a value.
Example:
let result = 10 + 5; // Addition expression
console.log(result); // Output: 15
5️ Looping Statements
Used to execute a block of code multiple times.
Example: for Loop
for (let i = 1; i <= 5; i++) {
console.log("Iteration " + i);
}
Example: while Loop
let count = 3;
while (count > 0) {
console.log("Countdown: " + count);
count--;
}
6️ Function Statements
Define reusable blocks of code.
Example: Function Definition & Call
function add(a, b) {
return a + b;
}
console.log(add(5, 10)); // Output: 15
Summary
JavaScript statements execute instructions in a program.
Declaration statements define variables and functions.
Assignment statements assign values.
Expression statements compute values.
Control statements manage program flow (if, switch).
Looping statements repeat actions (for, while).
Function statements define reusable code blocks.
Error handling statements prevent crashes.
Variables
But you cannot redeclare the same variable more than one time:
let a = 1
let a = 2
Now that we saw how to work with const and let, I want to mention var.
Until 2015, var was the only way we could declare a variable in JavaScript.
Today, a modern codebase will most likely just use const and let.
Data Types
1. String
Used to store text, enclosed in single ('), double ("), or backticks ( `).
3️. Boolean
Represents true or false values.
4️. BigInt
Used for large numbers beyond Number.MAX_SAFE_INTEGER.
5️. Undefined
A variable is undefined when it is declared but not assigned a value.
let value;
console.log(value); // Output: undefined
6️. Null
Represents an intentional absence of value.
let data = null;
console.log(data);
7️. Symbol
Used to create unique identifiers.
let id1 = Symbol('id');
let id2 = Symbol('id');
console.log(id1 === id2); // Output: false (Symbols are always unique)
1. Object
Used to store key-value pairs.
let student = {
name: "Deepika",
age: 22,
course: "MERN Stack"
};
console.log(student.name, student.age);
2️. Array
Stores multiple values in a single variable.
3️. Function
A block of reusable code.
function greet() {
return "Hello, JavaScript!";
}
console.log(greet());
Array Methods
JavaScript Strings
Example:
let userInput = " Hello ";
console.log(userInput.trim()); // Output: "Hello"
Example:
let str = "JavaScript";
console.log(str.slice(0, 4)); // Output: "Java"
console.log(str.slice(-6)); // Output: "Script"
Often used for extracting parts of a string where negative indexing is not
needed.
Example:
let text = "I love JavaScript";
console.log(text.replace("JavaScript", "Python")); // Output: "I love Python"
Example:
let sentence = "Apples are tasty. Apples are juicy.";
console.log(sentence.replaceAll("Apples", "Oranges"));
// Output: "Oranges are tasty. Oranges are juicy."
Replaces multiple instances of a word in large text.
Example:
let words = "apple,banana,grape";
let arr = words.split(",");
console.log(arr); // Output: ["apple", "banana", "grape"]
Example:
let text = "Hello JavaScript";
console.log(text.indexOf("JavaScript")); // Output: 6
Example:
let text = "Hello JavaScript JavaScript";
console.log(text.lastIndexOf("JavaScript")); // Output: 17
JavaScript Objects
Output
{ name: 'Sourav', age: 23, job: 'Developer' }
Output
{ name: 'Sourav', age: 22 }
{ name: 'Sourav', age: 23 }
You can dynamically add new properties to an object using dot or bracket
notation.
Output
{ model: 'Tesla', color: 'Red' }
4️. Removing Properties from an Object
Output
{ model: 'Tesla' }
Output
name: Sourav
age: 23
Output
True
const students = {
name: "Deepika",
age: 25,
greet: function() {
return `Hello, my name is ${this.name}.`;
}
};
console.log(students.greet());
Output: Hello, my name is Deepika.
const car1 = {
brand: "Toyota",
model: "Camry",
getCarInfo: function() {
return `Car: ${this.brand} ${this.model}`;
}
};
console.log(car1.getCarInfo());
const calculator = {
value: 0,
add(num) {
this.value += num;
return this;
},
subtract(num) {
this.value -= num;
return this;
},
getResult() {
console.log(this.value);
return this;
}
};
calculator.add(10).subtract(5).getResult();
Output: 5️
5️. Preventing Object Modification with Object.freeze()
The Object.freeze() method prevents adding, removing, or modifying properties
of an object. The person object remains unchanged even after attempting
modifications.
Ternary Operator (? :)
What is a Ternary Operator
The ternary operator is a conditional operator that takes three operands: a
condition, a value to be returned if the condition is true, and a value to be
returned if the condition is false. It evaluates the condition and returns one of
the two specified values based on whether the condition is true or false.
switch Statement
The JavaScript switch statement evaluates an expression and executes a block
of code based on matching cases. It provides an alternative to long if-else
chains, improving readability and maintainability, especially when handling
multiple conditional branches.
Ex
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
console.log(dayName);
Output: Wednesday
JavaScript Loops
Output
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Let’s now discuss the different types of loops available in JavaScript
Output
Count: 1
Count: 2
Count: 3
In this example
Initializes the counter variable (let i = 1).
Tests the condition (i <= 3); runs while true.
Executes the loop body and increments the counter (i++).
Syntax
while (condition) {
// Code to execute
}
let i = 0;
while (i < 3) {
console.log("Number:", i);
i++;
}
Output
Number: 0
Number: 1
Number: 2
In this example
Initializes the variable (let i = 0).
Runs the loop body while the condition (i < 3) is true.
Increments the counter after each iteration (i++).
3️. JavaScript do-while Loop
The do-while loop is similar to while loop except it executes the code block at
least once before checking the condition.
Syntax
do {
// Code to execute
} while (condition);
let i = 0;
do {
console.log("Iteration:", i);
i++;
} while (i < 3);
Output
Iteration: 0
Iteration: 1
Iteration: 2
In this example:
Executes the code block first.
Checks the condition (i < 3) after each iteration.
Output
name : Ashish
age : 25
In this example:
Iterates over the keys of the person object.
Accesses both keys and values.
Output
1
2
3
4
5
Choosing the Right Loop
Use for loop when the number of iterations is known.
Use while loop when the condition depends on dynamic factors.
Use do-while loop to ensure the block executes at least once.
Use for…in loop to iterate over object properties.
Use for…of loop for iterating through iterable objects.
In JavaScript, break and continue are used to control loop execution. break
immediately terminates a loop when a condition is met, while continue Skips
the current iteration and proceeds to the next loop iteration. Additionally,
JavaScript supports labels, which can be used with break and continue to
control nested loops efficiently.
The break Statement
The break statement is used to exit a loop when a certain condition is satisfied.
It is commonly used when searching for a specific value in an array or when an
early exit from a loop is required.
Syntax
break;
Using break in a for loop
for (let i = 0; i < 10; i++) {
if (i === 5) {
console.log("Breaking the loop at", i);
break;
}
console.log(i);
}
Output
0
1
2
3
4
Breaking the loop at 5
In this example
The loop starts from i = 0 and iterates up to i < 10.
When i reaches 5, the break statement executes, terminating the loop
immediately.
Numbers 0 to 4 are printed before the loop stops.
Output
1
2
3
4
5
Loop stopped at 6
In this example
The loop starts from n = 1 and runs as long as n <= 10.
When n reaches 6, the break statement is executed, stopping the loop.
The numbers 1 to 5 are printed before the loop terminates.
Output
1
3
5
7
9
In this example
The loop iterates from i = 0 to i < 10.
If i is an even number (i % 2 === 0), the continue statement is executed,
skipping that iteration.
Only odd numbers are printed.
Using continue in a while Loop
let i = 0;
while (i < 10) {
i++;
if (i % 3 === 0) {
continue; // Skips multiples of 3
}
console.log(i);
}
Output
1
2
4
5
7
8
10
In this example
The loop starts from i = 0 and runs while i < 10.
If i is a multiple of 3, the continue statement skips that iteration.
Numbers 3, 6, and 9 are not printed.
Functions in JavaScript
function sum(x, y) {
return x + y;
}
console.log(sum(6, 9));
Output
15
Calling Functions
After defining a function, the next step is to call them to make use of the
function. We can call a function by using the function name separated by the
value of parameters enclosed between the parenthesis.
// Function Definition
function welcomeMsg(name) {
return ("Hello " + name + " welcome ");
}
Output
Hello User welcome
Why Functions?
Functions can be used multiple times, reducing redundancy.
Break down complex problems into manageable pieces.
Manage complexity by hiding implementation details.
Can call themselves to solve problems recursively.
Function Invocation
The function code you have written will be executed whenever it is called.
Triggered by an event (e.g., a button click by a user).
When explicitly called from JavaScript code.
Automatically executed, such as in self-invoking functions.
Function Expression
It is similar to a function declaration without the function name. Function
expressions can be stored in a variable assignment.
Syntax:
Ex,
const mul = function (x, y) {
return x * y;
};
console.log(mul(4, 5));
Output
20
Arrow Functions
Arrow functions are a concise syntax for writing functions, introduced in ES6,
and they do not bind their own this context.
Syntax:
let function_name = (argument1, argument2 ,..) => expression
Ex,
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];
const a2 = a.map(function (s) {
return s.length;
});
console.log("Normal way ", a2);
//Arrow function
const a3 = a.map((s) => s.length);
console.log("Using Arrow Function ", a3);
Output
Normal way [ 8, 6, 7, 9 ]
Using Arrow Function [ 8, 6, 7, 9 ]
Callback Functions
A callback function is passed as an argument to another function and is
executed after the completion of that function.
function num(n, callback) {
return callback(n);
}
const double = (n) => n * 2;
console.log(num(5, double));
Output
10
Anonymous Functions
Anonymous functions are functions without a name. They are often used as
arguments to other functions.
Nested Functions
Functions defined within other functions are called nested functions. They have
access to the variables of their parent function.
function outerFun(a) {
function innerFun(b) {
return a + b;
}
return innerFun;
}
const addTen = outerFun(10);
console.log(addTen(5));
Output
15
Key Characteristics of Functions
Parameters and Arguments: Functions can accept parameters
(placeholders) and be called with arguments (values).
Return Values: Functions can return a value using the return keyword.
Default Parameters: Default values can be assigned to function
parameters.
Advantages of Functions in JavaScript
Reusability: Write code once and use it multiple times.
Modularity: Break complex problems into smaller, manageable pieces.
Improved Readability: Functions make code easier to understand.
Maintainability: Changes can be made in one place without affecting the
entire codebase.