oUR TOPIC

JavaScript

JavaScript is a programming language that executes on the browser. It turns static HTML web pages into interactive web pages by dynamically updating content, validating form data, controlling multimedia, animate images, and almost everything else on the web pages.

Basic information

  • JavaScript is the third most important web technology after HTML and CSS. JavaScript can be used to create web and mobile applications, build web servers, create games.
  • In early 1995, Brendan Eich from Netscape designed and implemented a new language for non-java programmers to give newly added Java support in Netscape navigator. It was initially named Mocha, then LiveScript, and finally JavaScript.
  • Nowadays, JavaScript can execute not only on browsers but also on the server or any device with a JavaScript Engine. For example, jsis a framework based on JavaScript that executes on the server.
  • Ecma Internationalis a non-profit organization that creates standards for technologies. ECMA International publishes the specification for scripting languages is called ‘ECMAScript’. ECMAScript specification defined in ECMA-262 for creating a general-purpose scripting language.
  • JavaScript is officially maintained by ECMA (European Computer Manufacturers Association) as ECMAScript. 
  • JavaScript is an object-oriented language, and it also has some similarities in syntax to Java programming language.

ROLES OF JAVASCRIPT :

  • You can modify the content of a web page by adding or removing elements.
  • You can change the style and position of the elements on a web page.
  • You can monitor events like mouse click, hover, etc. and react to it.
  • You can perform and control transitions and animations.
  • You can create alert pop-ups to display info or warning messages to the user.
  • You can perform operations based on user inputs and display the results.
  • You can validate user inputs before submitting it to the server.

    Basic Rules for JavaScript :

  • JavaScript is case-sensitive. This means that variables, language keywords, function names, and other identifiers must always be typed with a consistent capitalization of letters.
  • Each line must be terminate by semicolon . ;
  • Extension JavaScript file is “.js”.

JavaScript Operators

Operators are symbols or keywords that tell the JavaScript engine to perform some sort of actions. For example, the addition (+) symbol is an operator that tells JavaScript engine to add two variables or values, while the equal-to (==), greater-than (>) or less-than (<) symbols are the operators that tells JavaScript engine to compare two variables or values, and so on.

Types of Operators

Arithmetic Operators
(+, -, *, /, %)
Assignment Operators
(=, +=, -=, *=, /=, %=)
Comparison Operators
(>, =, <=, ==, !=)
String Operators
(+, +=)​
Increment/Decrement Operators
(++x, --x, x++, x--)
Logical Operators
(&&, ||, !)
Bitwise Operator
(&, |, ^, ~, <>)

Arithmetic Operators

The Arithmetic operators are used to perform common arithmetical operations, such as addition, subtraction, multiplication, division,  and modulus. 

OperatorsDescription
+Addition
-Subtraction
*Multiplication
/Division
%Modulus

         <script>

                    var a,b;

                    a=15;

                    b=3;

                    document.write(“<br>First Value : “,a);

                    document.write(“<br>Second Value : “,b);

                    var c=a+b;

                    document.write(“<br>Addition : “,c);

                    var d=a-b;

                    document.write(“<br> Subtraction : “,d);

                    var e=a*b;

                    document.write(“<br> Multiplication : “,e);

                    var f=a/b;

                    document.write(“<br> Division : “,f);

                    var g=a%b;

                    document.write(“<br> Modulus : “,g);

          </script>

<html>

           <head>

                       <title> Arithmetic Operator Example</title>

          </head>

          <body>    

         <script>

                    var a,b;

                    a=15;

                    b=3;

                    document.write(“<br>First Value : “,a);

                    document.write(“<br>Second Value : “,b);

                    var c=a+b;

                    document.write(“<br>Addition : “,c);

                    var d=a-b;

                    document.write(“<br> Subtraction : “,d);

                    var e=a*b;

                    document.write(“<br> Multiplication : “,e);

                    var f=a/b;

                    document.write(“<br> Division : “,f);

                    var g=a%b;

                    document.write(“<br> Modulus : “,g);

          </script>

         <body>

</html>

 

Assignment: Predict the Output.

     Objective: Understand arithmetic operators by analyzing and predicting the output of JavaScript code snippets.

Instructions:

  • Read the JavaScript code snippet carefully.
  • Predict what the output will be.
  • Run the code in the browser console (if needed) to verify your answer.
Questions:
  • What will be printed?
    • let x = 12;
    • let y = 8;
    • console.log(x + y);
  • Find the output:
    • let a = 25;
    • let b = 5;
    • console.log(a – b);
  • What is the result?
    •  let num1 = 7;
    • let num2 = 3;
    • let product = num1 * num2;
    • console.log (product);
  • Guess the output:
    • let total = 40;
    • let people = 4;
    • console.log (total / people);
  • What will this print?
    • let remainder = 19 % 5;
    • console.log(remainder);
  • What will be printed when using increment operator?
    • let count = 10;
    • count++;
    • console.log(count);
  • What happens here?
    • let value = 15;
    • value – -;
    • console.log(value);
  • Predict the output when using mixed operations:
    • let result = (5 + 3) * 2 – 4 / 2;
    • console.log(result);
  • Find the answer for this power operation:
    • let power = 3 ** 3;
    • console.log(power);
  • What will be the final value of x?
    • let x = 10;
    • x += 5;
    • console.log(x);

Expected Learning Outcomes:

  • Understanding of basic arithmetic operators: +, -, *, /, %, **
  • Increment (++) and decrement (–) operators
  • Operator precedence in expressions
  • Compound assignment operators (+=, -=)

Assignment Operators

Assignment operators assign values to left operand based on right operand, equal (=) operator is used to assign a values.

Operators Description Example
= Assign X=Y
+= Add and Assign X+=Y
-= Subtract and Assign X-=Y
*= Multiply and Assign X*=Y
/= Divide and Assign X/=Y
%= Divide and Assign Modulus X%=Y

Example 1: Understanding Different Assignment Operators

This example demonstrates the usage of +=, -=, *=, /=, and %= operators step by step.

<script>

    var num = 10; 

  document.write(“<br> Initial value: ” + num);

    num += 5;  // num = num + 5

  document.write(“<br> After num += 5 : ” + num);

    num -= 3;  // num = num – 3

 document.write(“<br> After num -= 3 : ” + num);

    num *= 2;  // num = num * 2

    document.write(“<br> After num *= 2 : ” + num);   

    num /= 4;  // num = num / 4

 document.write(“<br> After num /= 4 : ” + num);

    num %= 3;  // num = num %  document.write(“<br> After num %= 3 : ” + num);

</script>

Expected Outcome: 

  • Initial value: 10
  • After num += 5 : 15
  • After num -= 3 : 12
  • After num *= 2 : 24
  • After num /= 4 : 6
  • After num %= 3 : 0

Concepts Covered:

  • Addition Assignment (+=)

  • Subtraction Assignment (-=)

  • Multiplication Assignment (*=)

  • Division Assignment (/=)

  • Modulus Assignment (%=)

Example 2: Using Assignment Operators in a Real-Life Scenario

This example simulates a store adding and removing stock using assignment operators.

<script>
var stock = 50;
document.write(“<br> Initial stock: ” + stock);

stock += 20; // Received new stock
document.write(“<br> After receiving 20 items: ” + stock);

stock -= 10; // Sold 10 items
document.write(“<br> After selling 10 items: ” + stock);

stock *= 2; // Double stock due to high demand
document.write(“<br> After doubling stock: ” + stock);

stock /= 5; // Distributed stock to 5 stores equally
document.write(“<br> After distributing to 5 stores: ” + stock);
</script>

 

Expected Outcome

  • Initial stock: 50
  • After receiving 20 items: 70
  • After selling 10 items: 60
  • After doubling stock: 120
  • After distributing to 5 stores: 24

Concepts Covered:

  • How assignment operators work in practical situations

  • Using them in real-world calculations

Assignment 1: Salary Increment Calculation

💡 A company gives its employees a yearly increment based on their performance. Use assignment operators to update an employee’s salary.

Task:

  1. Initialize a variable salary with 50000.

  2. Increase the salary by 10% using the += operator.

  3. Deduct 5000 for taxes using the -= operator.

  4. Double the salary if the employee gets a promotion using the *= operator.

  5. Divide the salary equally among 4 months using /=.

  6. Display the salary after each update.

  • Expected Output:
  • Initial Salary: 50000
  • After 10% Increment: 55000
  • After Tax Deduction: 50000
  • After Promotion: 100000
  • Monthly Salary: 25000

Assignment 2: Shopping Cart Calculation

💡 You are developing a shopping cart system that updates the total cost dynamically.

Task:

  1. Initialize a variable totalCost with 0.

  2. Add the price of three items (e.g., 200, 150, 100) using the += operator.

  3. Apply a discount of 10% using the -= operator.

  4. Multiply the total by 2 if the customer wants a second set using *=.

  5. Split the total bill between 4 friends using /=.

  6. Display the total cost after each step.

Expected Output (Example):

  • Initial Total Cost: 0
  • After adding items: 450
  • After 10% Discount: 405
  • After Buying 2 Sets: 810
  • Each Friend Pays: 202.5

Comparison operator

Assignment operators assign values to left operand based on right operand, equal (=) operator is used to assign a values.

Operator Name Example Results
== Equal X==Y True if X is wqual to Y.
=== Identical X===Y True if X is equal to Y, and they are of the same type
!= Not Equal X!=Y True if X is not equal to Y
!== Not Identical X!==Y True if X is not equal to Y, or they are not of the same type.
< Less than X True if X is less than Y.
> Greater than X>Y True if X is greater than Y.
>= Greater than or Equal to X>=Y True if X is greater than or equal to Y.

Example 1: Easy Level (Number Comparison)

💡 This example checks whether two numbers are equal, greater, or smaller.

 

<script>
var a = 10;
var b = 5;

document.write(“Is a equal to b? ” + (a == b) + “<br>”);
document.write(“Is a not equal to b? ” + (a != b) + “<br>”);
document.write(“Is a greater than b? ” + (a > b) + “<br>”);
document.write(“Is a less than b? ” + (a < b) + “<br>”);
</script>

Expected Output:

  • Is a equal to b? false
  • Is a not equal to b? true
  • Is a greater than b? true
  • Is a less than b? false

 Concepts Covered:

  • == (Equal to)
  • != (Not equal to)
  • > (Greater than)
  • < (Less than)

Example 2: Medium Level (Voting Eligibility Check)

💡 This example checks if a person is eligible to vote based on their age.

 

<script>
var age = prompt("Enter your age:"); // Taking input from the user

if (age >= 18)

{
document.write(“You are eligible to vote.”);
}

else

{
document.write(“You are NOT eligible to vote.”);
}
</script>

 

How It Works?

  1. The script asks the user to enter their age.

  2. It compares if the age is greater than or equal to 18.

  3. If true, it prints "You are eligible to vote."

  4. Otherwise, it prints "You are NOT eligible to vote."

Concepts Covered:

  • >= (Greater than or equal to)

  • if-else condition

  • Using prompt() to take user input

Assignment 1: Temperature Check

💡 Write a JavaScript program to check if the temperature is too hot, cold, or moderate.

 

Task:
  1. Initialize a variable temperature with any value (e.g., 30).

  2. Use Comparison Operators to check:

    • If temperature > 35, print "It's too hot!"

    • If temperature < 15, print "It's too cold!"

    • Otherwise, print "The weather is moderate."

Example Code:

<script>
var temperature = 30; // Change this value to test
if (temperature > 35)
{
document.write("It's too hot!");
}
else if (temperature < 15)
{
document.write("It's too cold!");
}
else
{ document.write("The weather is moderate.");
} </script>

 

Expected Output :

The weather is moderate.

Assignment 2: Student Grade Checker (Medium Level)

💡 Create a JavaScript program to check whether a student has passed or failed.

 

Task:
  1. Initialize a variable marks with any value between 0-100.

  2. Use Comparison Operators to check:

    • If marks >= 90, print "Grade: A"

    • If marks >= 75, print "Grade: B"

    • If marks >= 50, print "Grade: C"

    • If marks < 50, print "You failed"

Example Code:

<script>

var marks = prompt(“Enter your marks:”); // Taking input from user

if (marks >= 90) {

document.write(“Grade: A”);

}

else if (marks >= 75) {

document.write(“Grade: B”);

}

else if (marks >= 50) {

document.write(“Grade: C”); } else { document.write(“You failed”);

}

</script>

 

Expected Output:

Grade: B

String operators

There are two operators which can also use for strings.

Operator Description Example Results
+ Concatention Str1=Str2 Concatention of Str1 and str2
+= Concatention Assignment Str1+=Str2 Appends the Str2 to the Str1

Example 1: Easy Level (String Concatenation)

💡 This example demonstrates how to combine two strings using the + operator.

 

<script>
var firstName = "John";
var lastName = "Doe";
var fullName = firstName + " " + lastName; // Concatenation
document.write("Full Name: " + fullName);
</script>
 

Expected Output:

Full Name: John Doe

Example 2: Medium Level (Combining Strings Dynamically)

💡 This example takes user input and displays a greeting message using String Operators.

 

<script>
var userName = prompt(“Enter your name:”); // Taking user input

var greeting = “Hello, ” + userName + “! Welcome to our website.”;
document.write(greeting);
</script>

 

How It Works?

  1. The script asks the user to enter their name using prompt().

  2. It concatenates the name with a greeting message.

  3. The final message is displayed on the screen.

Expected Output:

Hello, Alex! Welcome to our website.

Assignment  # 1: Create a Full Name (Easy Level)

  1. Create two variables: firstName and lastName.

  2. Concatenate them to create a fullName variable.

  3. Display the full name on the webpage using document.write().

Example Output:

Full Name: John Doe

 

Starter Code:

script>

var firstName = “John”;

var lastName = “Doe”;

var fullName = firstName + ” ” + lastName; // Concatenation

document.write(“Full Name: ” + fullName);

</script>

Assignment # 2: Personalized Welcome Message (Medium Level)

  1. Ask the user to enter their first name using prompt().

  2. Concatenate the input with a welcome message.

  3. Display the personalized message using document.write().

Example Output (If user enters “Alex”):

Hello, Alex! Welcome to our website.

 

Starter Code:

<script>
var userName = prompt("Enter your name:"); // Taking user input
var message = "Hello, " + userName + "! Welcome to our website.";
document.write(message);
</script>

Increment and Decrement Operator

There are two operators which can also use for strings.

Operator Name Effect
++X Pre-Increment Increment X by one, then returns X
X++ Post-Increment Returns X, then increments X by one
--X Pre-Decrement Decrements X by one, then returns X
X-- Post-Decrement Returns X, then decrements X by one

Example 1: Increment Operator (Easy Level)

💡 This example demonstrates the use of the increment (++) operator.

 

<script>
var count = 5;
document.write("Initial Value: " + count + "<br>");
count++; // Increments by 1
document.write("After Increment: " + count);
</script>
 

Expected Output:

Initial Value: 5
After Increment: 6

Example 2: Decrement Operator (Easy Level)

💡 This example demonstrates the use of the decrement (--) operator.

 

<script>

var count = 10;
document.write("Initial Value: " + count + "<br>");
count--; // Decrements by 1
document.write("After Decrement: " + count);
</script>
 

Expected Output:

Initial Value: 10
After Decrement: 9

Assignment #  1: Simple Counter (Easy Level)

  1. Create a variable named count and set it to 0.

  2. Increment the value by 1 using the ++ operator.

  3. Display the updated value using document.write().

  4. Decrement the value by 1 using the -- operator.

  5. Display the final value.

Example Output:

Initial Value: 0
After Increment: 1
After Decrement: 0

 

Starter Code:

<script>
var count = 0;
document.write("Initial Value: " + count + "<br>");
count++;
document.write("After Increment: " + count + "<br>"); count--;
document.write("After Decrement: " + count);
</script>

 

Assignment #

2: Understanding Pre-Increment & Post-Increment (Medium Level)

  1. Create a variable x and set it to 10.

  2. Use post-increment (x++) and assign it to y.

  3. Display both x and y after the operation.

  4. Use pre-increment (++x) and assign it to z.

  5. Display both x and z.

Example Output:

  • Initial Value of x: 10
  • After PostIncrement (y = x++): x = 11, y = 10
  • After PreIncrement (z = ++x): x = 12, z = 12

Starter Code:

 

<script>
var x = 10;
document.write("Initial Value of x: " + x + "<br>");

var y = x++; // Post-increment
document.write(“After Post-Increment (y = x++): x = “ + x + “, y = “ + y + “<br>”);

var z = ++x; // Pre-increment

document.write("After Pre-Increment (z = ++x): x = " + x + ", z = " + z);
</script>

Logical Operator

Logical operators are typically used to combine conditional statements.

Operator Description Example Results
&& AND X&&Y True if both X and Y are true
|| OR X||Y True if either X or Y is true
! NOT !X True if X is not true

Example 1: Logical AND (&&) Operator (Easy Level)

Returns true only if both conditions are true.

 

<script>
var age = 20;
var hasID = true;
if (age >= 18 && hasID) {
document.write("You are allowed to enter.");
} else {
document.write("Access denied.");
}
</script>
 

Expected Output:

You are allowed to enter.

Example 2: Logical OR (||) Operator (Medium Level)

Returns true if at least one condition is true.

 

<script>
var username = "admin";
var password = "1234";
if (username == "admin" || password == "admin123") {
document.write("Login successful!"); }
else {
document.write("Incorrect credentials.");
}
</script>
 

Expected Output:

Login successful!

Example 3: Logical NOT (!) Operator

Reverses the Boolean value.

 

<script>

var hasPermission = false;

document.write(!hasPermission ? “Access Denied” : “Access Granted”);

</script>

 

Expected Output:

Access Denied

Question 1: Logical AND (&&)

Create a program where:

  • If a user has completed their profile (isProfileComplete = true), display "Profile is ready!"

  • Otherwise, display an empty string.

📌 Expected Output:

Profile is ready!
 
 Question 2: Logical OR (||)

Write a program where:

  • If the userInput is empty, display "Default Value"

  • Otherwise, display the user’s input.

📌 Example:
If userInput = "", output should be:

Default Value

 

If userInput = "John", output should be:

John

 

Question 3: Logical NOT (!)

Write a program where:

  • If a isDarkMode variable is false, display "Light mode is active"

  • If isDarkMode is true, display "Dark mode is active"

Example Outputs:

Light mode is active

or

Dark mode is active

 

Bitwise Operator

Bitwise operators evaluate and perform specific bitwise expression.

Operator Description Description
& Bitwise AND Return bitwise AND operation for given two operands
| Bitwise OR Return Bitwise OR operation for given two operands
^ Bitwise XOR Return Bitwise XOR operation for given two operands
~ Bitwise NOT Return bitwise NOT operation for given two operands
<< Bitwise shift left Return left shift for given operands
>> Bitwise shift right return right shift of given operands

Bitwise AND(&) : It accepts two operands. Bitwise (&) return 1 if both the bits are set to 1.

A B (A&B)
0 0 0
0 1 0
1 0 0
1 1 1

Bitwise OR (|) : It accepts two operands. Bitwise OR (|) return 1 if any of the operand is set 1 and 0 in any other case.

A B (A|B)
0 0 0
0 1 1
1 0 1
1 1 1

Bitwise XOR (^) : It accepts two operands. Bitwise XOR (^) returns 1 if both the operand is different and 0 in any other case.

A B (A^B)
0 0 0
0 1 1
1 0 1
1 1 0

Bitwise NOT (~) : It is unary operator i.e. accepts single operands. Bitwise (~) flips the bits i.e. 0 becomes 1 and 1 becomes 0.

A (~A)
0 1
1 0

Example 1: Bitwise AND (&)

Returns 1 if both bits are 1, otherwise 0.

 

<script>
var a = 5; // 5 in binary: 0101
var b = 3; // 3 in binary: 0011
var result = a & b; // Bitwise AND
document.write("Result of 5 & 3: " + result);
</script>
 

Binary Calculation:

0101 (5)
& 0011 (3)
------------
0001 (1) Output: 1
 

Expected Output:

Result of 5 & 3: 1

Example 2: Bitwise OR (|)

Returns 1 if at least one bit is 1.

<script>
var a = 5; // 0101
var b = 3; // 0011

var result = a | b; // Bitwise OR

 

document.write("Result of 5 | 3: " + result);
</script>
 

Binary Calculation:

  0101 (5)
| 0011 (3)
------------

0111 (7) Output: 7
 

Expected Output:

Result of 5 | 3: 7

Example 3: Bitwise XOR (^)

Returns 1 if bits are different, otherwise 0.

<script>
var a = 5; // 0101
var b = 3; // 0011

var result = a ^ b; // Bitwise XOR

 

document.write("Result of 5 ^ 3: " + result);
</script>
 

Binary Calculation:

0101 (5)
^ 0011 (3)
------------

0110 (6) Output: 6
 

Expected Output:

Result of 5 ^ 3: 6

Example 4: Bitwise NOT (~)

Inverts all bits (flips 1 to 0 and 0 to 1).

 

<script>
var a = 5; // 5 in binary: 0101
var result = ~a; // Bitwise NOT
document.write("Result of ~5: " + result);
</script>

 

Binary Calculation:

0101 (5)
------------
1010 (Negative representation of -6)
 

Expected Output:

Result of ~5: -6

Conditional Statement in JavaScript

Conditional statements are used to decide the flow of execution based on different conditions. If a condition is true, you can perform one action and if the condition is false, you can perform another action.

Different types of conditional statements

If statement
If…else statement
If….else if….else statement
Switch

If Statement

The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.

 

Syntax:

If(condition){

Code to be executed if condition is true

}

 

Example

<script>

                 var a=4;  

                 if(a>=0) {

                          document.write(“Positive Number”);

                 }

</script>

Write a script to check whether the person’s age is eligible for vote or not.

The else statement

Use the else statement to specify a block of code to be executed if the condition is false

Syntax:

If(condition) {

         //code to be executed if the condition is true

}  else  {

         //block of code to be executed if the condition is false

}

Example  #1:

   <script>

                          var x=4;

                          if(x>=0)   {

                          document.write(“This is Positive Number”);

                          }  else      {

                          document.write(“This is Negative Number”);      

                          }

                 </script>

 

Example  #2:

                <script>

                          var x=5;

                          if(x%2==0){

                                  document.write(x+” Even Number”);

                          }  else        {

                                  document.write(x+” Odd Number”);        

                          }

                 </script>

If…..else if….else statement

The if…else…if statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions.

Syntax:

if(condition1){

         Lines of code to be executed if condition 1 is true

} else if(condition2)  {

         Lines of code to be executed if condition 2 is true

}  else  {

Lines of code to be executed if condition 1 and condition 2 is false

}            

 

Example #1:

   <script>

                          var v=10;

                          if(v==1)    {

                                  document.write(“Monday”);

                          }   else if(v==2)   {

                                  document.write(“Tuesday”);

                          }  else if(v==3)   {

                                  document.write(“Wednesday”);

                          }   else if(v==4)   {

                                  document.write(“Thursday”);

                          }   else if(v==5)   {

                                  document.write(“Friday”);

                          }   else if(v==6)   {

                                  document.write(“Saturday”);

                          }   else if(v==7)   {

                                  document.write(“Sunday”);

                          }   else   {

                                  document.write(“Invalid Number”);        

                          }

                 </script>

Switch

 The JavaScript switch statement is used to execute one code from multiple expressions. It is just like else if statement, but it is convenient than if…else…if because it can be used with numbers, characters, etc.

Syntax:

switch(expressions)   {

         case value1:

         code to be executed;

         break;

         case value2:

         code to be executed;

         break;

         default:

         code to be executed if above values are not matched;

         break;

         }

 

Example:

        <script>

                          var v=5;

                          switch(v) {

                                  case 1: document.write(“Monday”);

                                  break;

                                  case 2: document.write(“Tuesday”);

                                  break;

                                  case 3: document.write(“Wednesday”);

                                  break;

                                  case 4: document.write(“Thursday”);

                                  break;

                                  case 5: document.write(“Friday”);

                                  break;

                                  case 6: document.write(“Saturday”);

                                  break;

                                  case 7: document.write(“Sunday”);

                                  break;

                                  default:

                                  document.write(“Invalid Number”);

                                  break;

                          }      

        </script>

Display Popup Message Box

JavaScript popup provides different built-in functions to display popup messages for different purposes e.g. to display a simple message and take user’s confirmation on it or display a popup to take user’s input value. 

Alert Box

To use alert() function it display a popup message to the user. This popup will have OK button to close the popup.

Syntax:

         alert(“sometext goes here”)

 

Example:

<script>
alert(“Hello! Welcome to our website.”);
</script>

Confirm Box

A confirm box is often used if you want the use to verify or accept something. When a confirm box pops up the user will have to click either OK or cancel to proceed. If the user click OK, the box returns true. If the user click Cancel, the box returns false.

Syntax:

       confirm(“Query here”);

 

Example:

<script>
  var userResponse = confirm(“Do you want to continue?”);
  document.write(userResponse ? “You clicked OK!” : “You clicked Cancel!”);
</script>

Prompt box

JavaScript Prompt Box is often use to get a value from user and after using the specify purpose can be process.

Syntax:

       Prompt(“Input Message”);

Example:

<script>
    var userName = prompt(“What is your name?”);
    document.write(userName ? “Hello, ” + userName + “!” : “You didn’t enter a name.”);
</script>

Project area to show.

Loop form taib notes

Loops in JavaScript

Loops are used to execute a block of code repeatedly until a specified condition is met.

Types of Loops (Entry Control & Exit Control Loops)

  • Entry control Loops: the condition is checked before executing the loop body. 
  • Example: for, While loops.
  • Exit Control Loops: The condition is checked after executing the loop body at least once. 
  • Example:  do…while loop. 
  1. While loop (Entry control Loo).

the while loop executes a block of code as long as the condition is true. 

Syntax:

while(condition) {

// code to execute

}

Example: 

let a=1;

while (a<=5){

console.log(a);

a++;

}

Output:

1

2

3

4

5

2.  do…while loop (Exit control loop). 

the do…while loop executes at least once, even if the condition is false. 

Syntax: 

do{

//code to execute

}While (condition);

Example: 

let a=1;

do{

console.log(a);

a++;

} while (a-10);

Even if a=10, the loop will execute once before checking the condition. 

JavaScript Array

A JavaScript array is a special variable that can store multiple values in a single variable. Arrays allow you to store lists of items such as numbers, strings, objects, or even other arrays.

1️⃣ Creating an Array Using Square Brackets []  (Most Common Method)

This is the simplest and most widely used way to create an array.

Syntax:

    var array_name = [data1, data2, data3, …];

Example:

    var fruits = [“Apple”, “Banana”, “Cherry”]; console.log(fruits); // Output: [“Apple”, “Banana”, “Cherry”]

2️⃣ Creating an Array Using the  New Array() Constructor

This method uses the JavaScript Array() constructor function.

Syntax:

    var array_name = new Array(data1, data2, data3, …);

Example:

    var numbers = new Array(10, 20, 30);

    console.log(numbers); // Output: [10, 20, 30]

Note:

   If you use new Array(5), it creates an empty array of length 5 instead of an array containing [5]:

      var arr = new Array(5);

      console.log(arr); // Output: [empty × 5]

To avoid confusion, it’s best to use square brackets [].

 

3️⃣ Creating an Empty Array and Adding Elements

You can create an empty array and then add elements dynamically.

Example:

var cars = [];

cars[0] = "BMW";
cars[1] = "Tesla";
cars[2] = "Audi";

Console.log(cars); // Output: [“BMW”, “Tesla”, “Audi”]

 

4️⃣ Array with Mixed Data Types

JavaScript allows arrays to contain different data types.

Example:

var mixedArray = ["Hello", 42, true, {name: "John"}, [1, 2, 3]];
console.log(mixedArray);
// Output: ["Hello", 42, true, {name: "John"}, [1, 2, 3]]

Accessing the elements of an Array

Array elements can be accessed by their index using the square bracket notation. An index is a number that represents an element’s position in an array.

<script>

                          var a=[3,5,2,1,6,7,5,13];

                          var names=[“Aditya”,”Kirti”,”Armaan”,”Ananya”];

                          document.write(a[5]);

                          document.write(“<br>”+names[0]);

                          var colors=new Array(“Red”,”Green”,”Blue”,”Orange”);

                          document.write(“<br>”+colors[1]);

                 </script>

Length of the array

The length property returns the length of an array, which is the total number of elements contained in the array.

var names=[“Aditya”,”Kirti”,”Armaan”,”Ananya”];

document.write(“<br>Number of values : “+names.length);

Array with Length

Example:

<script>

                          var a;

var colors=[“Pink”,”Red”,”Yellow”,”Green”,”Blue”];      

                          for(a=0;a<colors.length;a++)

                          {

                                  document.write(“<br>”+colors[a]);

                          }

                 </script>

Unshift()

This add value at the beginning of the array.

For Example:

var colors=[“Pink”,”Red”,”Yellow”,”Green”,”Blue”];

colors.unshift(“White”);

 

pop() Removes the value from the last position

shift()Removes the first value of the array

                           colors.pop();

                          colors.shift();

Example

<html>

         <head>

         <title>Array</title>

         </head>

         <body>

         <script>

         var a=[12,56,33,45,21];

         var b=90;

         document.write(a);

         a.unshift(b);

         document.write(“<br>After adding value<br>”);

         document.write(a);

         a.pop();

         document.write(“<br>After removing value<br>”);

         document.write(a);

         a.shift();

         document.write(“<br>After removing first value<br>”);

         document.write(a);

         </script>

         </body>

</html>

Want to join?

Find a team of digital marketers you can rely on. Every day, we build trust through communication, transparency, and results.

Scroll to Top