Skip to main content

Command Palette

Search for a command to run...

What is Web

Updated
26 min readView as Markdown
B

Student | Tech enthusiast | Aspiring software developer

.1 Overview of the Internet

The Internet is a vast network of interconnected computers and devices that communicate with each other. It is the infrastructure that supports the Web and other services like email, online gaming, and file sharing.

  • Network of Networks: The Internet connects millions of private, public, academic, business, and government networks.

  • Protocols: It uses a set of rules called protocols to ensure devices can communicate. The most common protocol is TCP/IP (Transmission Control Protocol/Internet Protocol).

Example: When you access a website, your computer connects to the Internet, finds the server hosting the website, and retrieves the necessary data.

1.2 How the Web Works

The Web operates over the Internet and consists of a vast collection of interconnected documents and resources. Here's a step-by-step look at how it works:

  • Client (Browser) Request: You open a web browser and type a URL (like www.sikshyashala.com). This action sends a request to the web server hosting the website.

  • Server Response: The web server receives the request, processes it, and sends back the required files (HTML, CSS, JavaScript) to your browser.

  • Rendering: Your browser interprets these files and displays the webpage on your screen.

  • Interaction: When you interact with the webpage (clicking buttons, filling forms), your browser may send more requests to the server to update the page dynamically.

1.3 Web Browsers and Servers

  • Web Browsers: A web browser is an application that allows you to access and interact with the Web. Popular browsers include Google Chrome, Mozilla Firefox, Safari, and Microsoft Edge. Browsers fetch the content from web servers and display it to you.

  • Example: When you type www.example.com into Chrome, the browser requests the webpage from the server and displays it.

  • Web Servers: A web server is a powerful computer that stores websites and their files. When a browser requests a webpage, the server finds the requested files and sends them to the browser.

  • Example: If you visit www.example.com, your browser sends a request to the server hosting example.com, which then responds with the necessary files.

1.4 HTTP/HTTPS Protocols

  • HTTP (HyperText Transfer Protocol): HTTP is the protocol used by browsers and servers to communicate. It defines how messages are formatted and transmitted over the Web.

    Example: When you type http://www.example.com, your browser sends an HTTP request to the server, which responds with the webpage.

  • HTTPS (HyperText Transfer Protocol Secure): HTTPS is the secure version of HTTP. It encrypts data exchanged between your browser and the server, protecting it from being intercepted.

    Example: When you type https://www.example.com, your browser establishes a secure connection with the server, ensuring that any data you send or receive is encrypted and secure.

1.5 Domain Names and IP Addresses

  • Domain Names: A domain name is a human-readable address used to identify a website on the Internet. Examples include www.google.com, www.facebook.com, and www.example.com. Domain names are easier to remember and use compared to numerical IP addresses.

    Example: www.example.com is a domain name that points to a specific website.

  • IP Addresses (Internet Protocol Addresses): An IP address is a unique numerical label assigned to each device connected to the Internet. It acts like a phone number, identifying the device's location on the network.

    Example: 192.168.1.1 is an example of an IP address.

How They Work Together: When you type a domain name in your browser, a Domain Name System (DNS) server translates the domain name into an IP address so your browser can find and connect to the correct web server.

By understanding these foundational concepts, you'll have a solid base for learning how to build web applications with Django, leveraging the power of the Web to create dynamic, interactive user experiences

2.1 Client-Server Architecture

Client-server architecture is a foundational concept in web development. It describes how data and resources are shared between devices (clients) and servers.

  • Client: The client is the device and application you use to access websites, like your web browser (Chrome, Firefox, Safari) on your computer or smartphone. The client's job is to request and display web pages.

  • Server: The server is a powerful computer that stores websites and their content. When a client requests a webpage, the server processes this request and sends the required information back to the client.

To help understand this, think of visiting a library. You (the client) ask the librarian (the server) for a specific book (webpage). The librarian finds the book in the library's collection (server storage) and hands it to you (sends the webpage).

Example:

  • When you type www.example.com into your browser, your browser (client) sends a request to the server hosting the website.

  • The server receives the request, finds the necessary files, and sends them back to your browser.

  • Your browser then displays the webpage.

2.2 Frontend vs Backend Development

Web development is divided into two main parts: frontend and backend. Both parts are crucial for the functionality and usability of a website.

  • Frontend Development:

    • The frontend is everything you see and interact with on a website. It includes the design, layout, buttons, images, and text.

    • Frontend developers use languages like HTML (HyperText Markup Language), CSS (Cascading Style Sheets), and JavaScript to build the visible part of the website.

HTML structures the content, CSS styles it, and JavaScript adds interactivity. Think of the frontend as the storefront of a shop. It’s designed to be visually appealing and easy to navigate for customers.

Example: When you visit a website, the colors, fonts, and layout are all part of the frontend. When you click a button, it's JavaScript making things happen instantly without refreshing the page.

  • Backend Development:

    • The backend is everything that happens behind the scenes. It includes the server, database, and application logic.

    • Backend developers use programming languages like Python, Ruby, PHP, and frameworks like Django to manage data and ensure everything works smoothly.

The backend is like the kitchen of a restaurant. It’s where all the food is prepared, but customers don’t see it.

Example: When you log in to a website, the backend checks your username and password against its database. If they match, you gain access; if not, you see an error message.

2.3 Static vs Dynamic Websites

Websites can be categorized into two types based on how they deliver content: static and dynamic.

  • Static Websites:

    • Static websites display the same content to every visitor. They are simple, consisting of fixed HTML files that don’t change unless manually updated by the developer.

    • They are faster to load and easier to build but lack interactivity and real-time data updates.

Think of a static website as a printed brochure. Once printed, the content doesn’t change until a new brochure is made.

Example: A personal blog where the content is updated only when the owner makes changes.

  • Dynamic Websites:

    • Dynamic websites generate content on the fly based on user interactions or other factors. They use server-side scripting (like PHP or Python) to build pages dynamically.

    • They are more complex, allowing for interactive features like user accounts, comments, and real-time updates.

A dynamic website is like a restaurant menu board that changes depending on the time of day or customer preferences.

Example: Social media platforms like Facebook or Twitter, where content constantly changes based on user activity.

Summary

By understanding these basic concepts of web development—client-server architecture, frontend vs. backend development, and static vs. dynamic websites—you can grasp how websites work, how they are built, and how they deliver content to users. Whether you're a complete beginner or just looking to solidify your understanding, these fundamentals are the building blocks for diving deeper into web development and technologies like Django.

Overview of Javascript


JavaScript is a high-level, interpreted programming language that is primarily used for creating and controlling dynamic website content. It's a versatile language that can be used for a wide range of tasks, from simple form validations to complex web applications.

In this lesson, we will cover the following topics:

  • History of JavaScript

    • The origin and evolution of JavaScript.

    • Key milestones and updates in JavaScript's development.

  • Uses of JavaScript

    • JavaScript in web development (front-end and back-end).

    • JavaScript in mobile and desktop app development.

    • Other applications of JavaScript.

  • Importance of JavaScript

    • Popularity and widespread use.

    • Versatility across different platforms and applications.

    • Large community and extensive resources.

This overview will provide a strong foundation in JavaScript, preparing you for more advanced topics and for transitioning to React development.

Uses of JavaScript


Use of JavaScript

1. Web Development:

JavaScript is foundational in web development, serving both client-side (front-end) and server-side (back-end) purposes.

  • Client-Side JavaScript:

    • Enhancing User Interface (UI): JavaScript allows developers to manipulate HTML and CSS dynamically, enabling interactive features such as dropdown menus, sliders, and animations without reloading the entire page.
    • Form Validation: Ensures data entered by users in web forms is correct before submission, providing immediate feedback.
    • AJAX (Asynchronous JavaScript and XML): Facilitates asynchronous communication with the server, enabling fetching and updating data without reloading the entire page, resulting in smoother user experiences.
  • Server-Side JavaScript:

    • Node.js: JavaScript runtime environment that allows server-side scripting. It enables developers to build scalable and high-performance applications, leveraging JavaScript's event-driven, non-blocking I/O model.

      • API Development: Node.js is often used to build RESTful APIs (Application Programming Interfaces) that serve data to client-side applications.

2. Mobile and Desktop Applications:

JavaScript extends beyond web browsers, enabling the development of mobile and desktop applications.

  • React Native: A framework for building native mobile applications using JavaScript and React. It allows developers to write code once and deploy it across iOS and Android platforms, leveraging native components.

  • Electron: Enables building cross-platform desktop applications using web technologies (HTML, CSS, JavaScript). Applications like Slack, Discord, and Visual Studio Code are built using Electron.

3. Other Applications:

JavaScript's versatility extends into various specialized domains and use cases.

  • Game Development: JavaScript is used with game development libraries and engines like Phaser.js and Three.js, making it feasible to create browser-based games.

  • Internet of Things (IoT): JavaScript is increasingly used in IoT development, enabling devices to communicate with each other and with cloud services.

  • Serverless Computing: Platforms like AWS Lambda and Azure Functions support JavaScript, allowing developers to write serverless functions that execute in response to events without managing infrastructure.

4. Importance and Ecosystem:

JavaScript's importance in the development community is underscored by its extensive ecosystem, including frameworks (React, Angular, Vue.js), libraries (jQuery, lodash), and tools (Webpack, Babel) that streamline development processes.

  • Popularity: JavaScript consistently ranks as one of the most popular programming languages, ensuring a large pool of developers and resources.

  • Community Support: A vibrant community contributes to open-source projects, provides tutorials, and offers forums for troubleshooting and collaboration.

  • Continuous Evolution: The ECMAScript standard regularly introduces new features and improvements, ensuring JavaScript remains relevant and capable of meeting evolving development needs.

In summary, JavaScript's ubiquity and flexibility make it indispensable across a wide spectrum of applications, from enhancing web interfaces to building complex mobile and desktop applications and powering IoT devices. Its role continues to expand as technology evolves, solidifying its position as a fundamental language in modern software development.

Running Your First JavaScript Code


  • Create a Folder:

    • Create a new folder on your computer and name it practicejs.
  • Create an HTML File:

    • Inside the practicejs folder, create a new file and name it index.html.
  • Add Boilerplate Code:

    • Open index.html with a text editor (like VS Code, Sublime Text, or Notepad).

      • Add the following boilerplate HTML code to the file:

          <!DOCTYPE html>
          <html lang="en">
          <head>
              <meta charset="UTF-8">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <title>My First JavaScript Code</title>
          </head>
          <body>
              <h1>Hello, JavaScript!</h1>
              <script>
                  // Your JavaScript code will go here
                  console.log('Hello, world!');
              </script>
          </body>
          </html>
        
        • Open in Browser:

          • Save the file and open index.html in your web browser. You can do this by double-clicking the file or right-clicking it and selecting "Open with" and then choosing your browser.
        • Inspect and Open Console:

          • Right-click anywhere on the page and select "Inspect" (or press Ctrl+Shift+I on Windows/Linux or Cmd+Option+I on Mac).

            • Click on the "Console" tab in the Developer Tools that open up.

        • View Your First JavaScript Output:

          • You should see the message Hello, world! printed in the console.

Variable In Javascript


What is a Variable in JavaScript?

A variable in JavaScript is a container for storing data values. It allows you to save a value and use it later in your program. Variables can hold different types of data, such as numbers, strings, objects, and more.

Variable Assignment and Logging

a = 10;
console.log('a');
console.log(a);
  • a = 10;: This line assigns the value 10 to the variable a. Since a is not declared with var, let, or const, it becomes a global variable.

  • console.log('a');: This line prints the string 'a' to the console. It does not print the value of the variable a, but the literal string 'a'.

  • console.log(a);: This line prints the value of the variable a to the console. Since a has been assigned the value 10, it will print 10.

Assigning and Using Another Variable

a = 10;
b = a;
console.log(a);
  • a = 10;: This line reassigns the value 10 to the variable a. This doesn't change anything since a was already 10.

  • b = a;: This line assigns the value of a (which is 10) to the variable b. Now, b also holds the value 10.

  • console.log(a);: This line prints the value of the variable a to the console. It will print 10.

Reassigning the Variable a

a = 10;
a = 5;
console.log(a);
  • a = 10;: This line assigns the value 10 to the variable a again.

  • a = 5;: This line reassigns the value 5 to the variable a, overwriting the previous value 10.

  • console.log(a);: This line prints the current value of the variable a to the console. Since a has been reassigned to 5, it will print 5.

Variable Declarations in JavaScript: var


For var:

Variable a Declarations and Logging

var a = 10;
var a = 20;
var a = 30;

console.log(a);
  • var a = 10;: This line declares a variable a and assigns it the value 10.

  • var a = 20;: This line re-declares the variable a and assigns it a new value 20. In JavaScript, var allows redeclaration of the same variable within the same scope.

  • var a = 30;: This line re-declares the variable a again and assigns it a new value 30. Each time, the previous value is overwritten.

  • console.log(a);: This line prints the current value of a, which is 30. This is because the last assignment to a was 30.

Variable b Declaration and Block Scope

{
    var b = 10;
    console.log(b);
}
b = 20;

console.log(b);

Block Scope:

{
    var b = 10;
    console.log(b);
}
  • var b = 10;: This line declares a variable b and assigns it the value 10. Even though b is declared inside a block, because var is used, b is function-scoped or globally-scoped, not block-scoped.

  • console.log(b);: This line prints the value of b, which is 10.

Reassigning b:

b = 20;

b = 20;: This line reassigns the value of b to 20. Since b was declared with var, it is accessible outside the block, and this reassignment is valid.

Logging b:

console.log(b);
    • console.log(b);: This line prints the current value of b, which is now 20.

let


The let keyword in JavaScript is used to declare variables that are block-scoped. This means that a variable declared with let is only accessible within the block it was declared in, and it cannot be redeclared in the same scope.

Let's break down and explain the provided JavaScript code step by step.

Variable a Declaration and Reassignment

let a = 10;
a = 20;
console.log(a);
Copy
  • let a = 10;: This line declares a variable a with the value 10. The scope of a is the block in which it is declared.

  • a = 20;: This line reassigns the value of a to 20. Reassignment of let variables is allowed.

  • console.log(a);: This line prints the value of a to the console, which is 20.

Block Scope with let for Variable b

let b = 20;
{ 
    let b = 30;
    console.log(b);
}

console.log(b);

let b = 20;: This line declares a variable b with the value 20. The scope of b is the block in which it is declared.

Block Scope:

{
    let b = 30;
    console.log(b);
}
  • let b = 30;: This line declares a new variable b inside a block with the value 30. This b is different from the b declared outside the block. The scope of this b is limited to this block.

  • console.log(b);: This line prints the value of b within the block, which is 30.

Outside the Block:

console.log(b);

console.log(b);: This line prints the value of the variable b declared outside the block. The value of this b is still 20 because the block-scoped b did not affect it.

Const


The const keyword in JavaScript is used to declare variables that are block-scoped and cannot be reassigned. This means that once a variable is assigned a value using const, it cannot be changed or reassigned. However, the properties of objects and elements of arrays declared with const can still be modified.

Let's break down and explain the provided JavaScript code step by step.

Variable a Declaration and Attempted Reassignment

const a = 10;
a = 20;
console.log(a);
  • const a = 10;: This line declares a variable a with the value 10. The scope of a is the block in which it is declared. const variables must be initialized at the time of declaration.

  • a = 20;: This line attempts to reassign the value of a to 20. Since a was declared with const, this will throw a TypeError because const variables cannot be reassigned.

  • console.log(a);: This line would not be reached due to the error thrown in the previous line.

Block Scope with const for Variable b

const b = 20;

{
    const b = 30;
    console.log(b);
}

console.log(b);

const b = 20;: This line declares a variable b with the value 20. The scope of b is the block in which it is declared.

Block Scope:

{
    const b = 30;
    console.log(b);
}
  • const b = 30;: This line declares a new variable b inside a block with the value 30. This b is different from the b declared outside the block. The scope of this b is limited to this block.

  • console.log(b);: This line prints the value of b within the block, which is 30.

Outside the Block:

console.log(b);

​​​​​​​console.log(b);: This line prints the value of the variable b declared outside the block. The value of this b is still 20 because the block-scoped b did not affect it.

Data type


In JavaScript, a datatype is a classification that specifies which type of value a variable can hold. Here are the types of data types in JavaScript:

  1. Primitive Data Types:

    • Number

    • String

    • Boolean

    • Undefined

    • Null

  2. Non-Primitive (Reference) Data Types:

    • Array

    • Object

Primitive Data Types


Primitive Data Types

Primitive data types are immutable and include the following:

  1. Number:

    • Represents both integer and floating-point numbers.
  • Example
  •   let age = 25;
      let pi = 3.14;
    
  1. String:
  1. Represents a sequence of characters enclosed in single quotes ('), double quotes ("), or backticks (` ).
  1. Example:
let greeting = "Hello, World!";
let name = 'John Doe';
let templateLiteral = `This is a string`;

Boolean:

  • Represents logical values: true or false.
  • Example
let isJavaScriptFun = true;
let isItRaining = false;

Undefined:

  • Represents a variable that has been declared but not assigned a value.

  • Example

let x;
console.log(x); // undefined

Null:

  • Represents the intentional absence of any object value.

  • Example

let y = null;

Non-Primitive Data Types

Non-primitive data types can hold collections of values and more complex entities.

  1. Object:

    • Represents collections of properties, which are key-value pairs.
  • Example:
  1.  let person = {
         name: 'Alice',
         age: 30,
         isStudent: false
     };
    

Array:

  • A special type of object used for storing ordered collections of values.

  • Example

let numbers = [1, 2, 3, 4, 5];
let mixedArray = [1, 'two', true, null];

Function:

  • Functions are objects that can be called to perform tasks or return values.

  • Example

function greet() {
    return "Hello!";
}

Non Primitive (object)


Object

In JavaScript, an object is a collection of properties, where each property is defined as a key-value pair. Objects allow you to group related data and functions together, making it easier to manage and manipulate complex data structures.

<script>
    const Student = {
        name: "Bisesh Adhikari",
        Semester: "6th semester",
        Roll_no: 21
    };
</script>

In this example:

  • Student is an object.
  • The object has three properties:

    • name: This property has a value of "Bisesh Adhikari", which is a string.
  • Semester: This property has a value of "6th semester", which is a string.
  • Roll_no: This property has a value of 21, which is a number.

You can access the properties of the Student object using dot notation or bracket notation. For example:

console.log(Student.name); // Output: Bisesh Adhikari
console.log(Student["Semester"]); // Output: 6th semester
console.log(Student.Roll_no); // Output: 21

The Student object not only contains properties but also a method. A method is a function that is a property of an object. This demonstrates how objects can encapsulate both data and behavior.

<script>
    const Student = {
        name: "Bisesh Adhikari",
        Semester: "6th semester",
        Roll_no: 21,
        write_code: function() { 
            console.log("write code");
        }
    };

    Student.write_code(); // Calls the write_code method
</script>

Explanation

  1. Properties:

    • name: Holds the value "Bisesh Adhikari", a string representing the student's name.
  • Semester: Holds the value "6th semester", a string representing the student's current semester.
  • Roll_no: Holds the value 21, a number representing the student's roll number.
  1. Method:

    • write_code: This is a method of the Student object. It is defined as a function that logs the string "write code" to the console when called.

Using the Method

The method write_code is called using the following syntax:

Student.write_code();

Conditional Statements


Conditional statements are used to perform different actions based on different conditions. In JavaScript, the most common conditional statements are if, else if, and else.

1. if Statement

The if statement is used to specify a block of code that will be executed if a specified condition is true.

if (condition) {
  // code to be executed if the condition is true
}

Example

let age = 18;

if (age >= 18) {
  console.log("You are an adult.");
}

In this example, the message "You are an adult." will be printed to the console if age is greater than or equal to 18.

2. else Statement

The else statement specifies a block of code to be executed if the same condition is false.

if (condition) {
  // code to be executed if the condition is true
} else {
  // code to be executed if the condition is false
}

For example:

let age = 16;

if (age >= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are a minor.");
}

3. else if Statement

The else if statement specifies a new condition to test if the first condition is false.

if (condition1) {
  // code to be executed if condition1 is true
} else if (condition2) {
  // code to be executed if condition1 is false and condition2 is true
} else {
  // code to be executed if both condition1 and condition2 are false
}

Example:

let score = 85;

if (score >= 90) {
  console.log("You got an A.");
} else if (score >= 80) {
  console.log("You got a B.");
} else {
  console.log("You need to study more.");
}

practical example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Voting Eligibility Checker</title>
</head>
<body>
  <h1>Voting Eligibility Checker</h1>
  <script src="script.js"></script>
</body>
</html>
// Ask the user for their age
let age = prompt("Enter your age:");

// Convert the input to a number
age = Number(age);

// Check if the user is eligible to vote
if (age >= 18) {
  console.log("You are eligible to vote!");
  document.write("<p>You are eligible to vote!</p>");
} else {
  console.log("You are not eligible to vote yet.");
  document.write("<p>You are not eligible to vote yet.</p>");
}

While Loop


Let's break down and analyze the given code snippets, focusing on the repetition and the use of loops.

Before Using the Loop

print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")
print("Bisesh Adhikari")

In this snippet, the same line of code print("Bisesh Adhikari") is repeated multiple times. Specifically, it is repeated nine times. This approach works but is not efficient or scalable, especially if you need to print the same statement many times.

After Using the Loop

let count = 0;
while(count <= 10) { 
    print("Bisesh Adhikari");
    count++;
}

Here, a loop is introduced to handle the repetition.

Explanation:

  1. Initialization: let count = 0;

    • A variable count is initialized to 0.
  2. Condition: while(count <= 10)

    • The while loop will run as long as the condition count <= 10 is true. Since count starts at 0 and goes up to 10, the loop will execute 11 times (from 0 to 10 inclusive).
  3. Body of the Loop:

    • print("Bisesh Adhikari");

      • The statement print("Bisesh Adhikari"); will be executed in each iteration of the loop.
    • count++;

      • After printing, the count variable is incremented by 1.

Comparison

  • Before Using the Loop:

    • Code is longer and repetitive.

    • Not efficient for a larger number of repetitions.

    • Harder to maintain and prone to errors if the number of repetitions needs to change.

  • After Using the Loop:

    • Code is shorter and more readable.

    • Efficient and scalable.

    • Easier to maintain; changing the number of repetitions requires only a single change in the loop condition.

In summary, using a loop to handle repetitive tasks makes the code more efficient, readable, and maintainable. In this case, the while loop is used to print the string "Bisesh Adhikari" 11 times, which is more concise and easier to manage than writing the print statement multiple times manually.

do while loop


General Explanation of a do...while Loop

In general terms, a do...while loop is a type of loop that ensures the block of code inside the loop is executed at least once before the condition is tested. This is useful when you want the code to run at least one time regardless of the condition.

Explanation of a do...while Loop in JavaScript

In JavaScript, a do...while loop is used to execute a block of code at least once and then continue to execute it as long as a specified condition evaluates to true. The condition is checked after the code block has been executed.

Syntax

do {
    // code block to be executed
} while (condition);

Example

Let's see a practical example of how a do...while loop works in JavaScript:

let count = 0;
do {
    console.log("Bisesh Adhikari");
    count++;
} while (count < 5);

Explanation of the Example

  1. Initialization:

    • let count = 0;

      • A variable count is initialized to 0.
  2. Loop Execution:

    • The code block inside the do section (console.log("Bisesh Adhikari"); count++;) is executed first, regardless of the condition.

    • This means "Bisesh Adhikari" will be printed, and count will be incremented by 1.

  3. Condition Check:

    • After executing the code block, the condition count < 5 is checked.

    • If the condition is true, the loop will execute the code block again.

    • This process repeats until the condition evaluates to false.

For loop


General Explanation of a for Loop

A for loop is a control flow statement that allows code to be executed repeatedly based on a condition. It is commonly used when the number of iterations is known before entering the loop.

Explanation of a for Loop in JavaScript

In JavaScript, a for loop repeats a block of code a specified number of times. It consists of three parts: initialization, condition, and increment/decrement.

Example

Let's see a practical example of how a for loop works in JavaScript:

for (let i = 0; i < 5; i++) {
    console.log("Bisesh Adhikari");
}

Explanation of the Example

  1. Initialization:

    • let i = 0;

      • A variable i is initialized to 0. This is executed once at the start of the loop.
  2. Condition:

    • i < 5;

      • The loop runs as long as this condition is true. If i is less than 5, the loop continues.
  3. Increment/Decrement:

    • i++

      • After each iteration of the loop, i is incremented by 1.
  4. Code Block:

    • console.log("Bisesh Adhikari");

      • This code block is executed each time the loop runs.

Using a for Loop with an Array

A for loop is often used to iterate over the elements of an array. Here's how you can do it:

Example with Array

const names = ["Bisesh", "Adhikari", "John", "Doe"];
for (let i = 0; i < names.length; i++) {
    console.log(names[i]);
}

Explanation of the Example

  1. Initialization:

    • let i = 0;

      • A variable i is initialized to 0.
  2. Condition:

    • i < names.length;

      • The loop runs as long as i is less than the length of the names array.
  3. Increment/Decrement:

    • i++

      • After each iteration, i is incremented by 1.
  4. Code Block:

    • console.log(names[i]);

      • This code block logs the current element of the array names to the console.

Summary

  • for Loop: Used when the number of iterations is known.

  • Syntax: Includes initialization, condition, and increment/decrement.

  • Array Iteration: The for loop is commonly used to iterate over arrays by using the array's length in the condition.

Functions In js


Introduction to Functions

Why Do We Need Functions?

Functions help to organize and reuse code. They allow you to divide your program into manageable pieces and reduce repetition. Here’s a simple example to illustrate the need for functions:

Without Functions:

# Calculate the square of numbers without using functions
number1 = 5
square1 = number1 * number1
print(f"The square of {number1} is {square1}")

number2 = 10
square2 = number2 * number2
print(f"The square of {number2} is {square2}")

number3 = 15
square3 = number3 * number3
print(f"The square of {number3} is {square3}")

With Functions:

# Define a function to calculate the square of a number
def calculate_square(number):
    square = number * number
    return square

# Call the function for different numbers
print(f"The square of 5 is {calculate_square(5)}")
print(f"The square of 10 is {calculate_square(10)}")
print(f"The square of 15 is {calculate_square(15)}")

Components of a Function

  1. Function Definition:

    • You define a function using the def keyword, followed by the function name and parentheses containing parameters.
  2. Parameters and Arguments:

    • Parameters are the variables listed inside the parentheses in the function definition.

    • Arguments are the actual values passed to the function when it is called.

  3. Function Body:

    • The code inside the function that performs the task. It is indented.
  4. Return Statement:

    • The return statement is used to send a result back to the caller of the function.

Example: Function Basics

Here’s an example demonstrating the basic structure and usage of a function:

# Define a function with parameters
def greet(name):
    # Function body
    message = f"Hello, {name}!"
    return message

# Call the function with an argument
greeting = greet("Alice")
print(greeting)  # Output: Hello, Alice!

More on Calling Functions

Functions can be called multiple times with different arguments:

print(greet("Bob"))    # Output: Hello, Bob!
print(greet("Carol"))  # Output: Hello, Carol!

Functions with Multiple Parameters

You can define functions with multiple parameters:

def add(a, b):
    result = a + b
    return result

print(add(3, 4))  # Output: 7
print(add(10, 20))  # Output: 30

Return Statement

The return statement ends the function execution and specifies what value to return to the caller. If no return statement is used, the function returns None.

def multiply(a, b):
    return a * b

result = multiply(4, 5)
print(result)  # Output: 20

Summary

  • Functions are used to organize and reuse code.

  • Parameters are placeholders in the function definition.

  • Arguments are the actual values passed to the function.

  • The return statement sends a result back to the caller.

Functions are fundamental in programming as they make code more modular, readable, and maintainable.

Arrow Functions


Arrow functions, also known as lambda functions, are a shorthand way of defining small, anonymous functions. They are commonly used in languages like JavaScript, Python, and others for creating concise function expressions. Here, we will cover arrow functions in both JavaScript and Python.

Arrow Functions in JavaScript

In JavaScript, arrow functions provide a compact syntax for writing functions. They are especially useful for inline functions.

Syntax

The basic syntax of an arrow function is as follows:

// Traditional function expression
let traditionalFunction = function(parameter1, parameter2) {
    // Function body
    return parameter1 + parameter2;
};

// Arrow function expression
let arrowFunction = (parameter1, parameter2) => {
    // Function body
    return parameter1 + parameter2;
};

If the function body contains only a single expression, you can omit the curly braces {} and the return statement:

let arrowFunction = (parameter1, parameter2) => parameter1 + parameter2;

Examples

  1. Simple Arrow Function:
let greet = name => `Hello, ${name}!`;
console.log(greet("Alice"));  // Output: Hello, Alice!

Arrow Function with Multiple Parameters:

let add = (a, b) => a + b;
console.log(add(3, 4));  // Output: 7
  1. Arrow Function with No Parameters:
let sayHello = () => "Hello, World!";
console.log(sayHello());  // Output: Hello, World!

square of a number

        // Using arrow function display the square of a number
        let square = (a)=>a*a

        console.log(square(10))

More from this blog

Bisesh's Blog

24 posts