Web Designing
Module 2
JavaScript
Introduction to JavaScript:
JavaScript is a high-level programming language primarily used for web
development. It is used for client-side scripting, which allows you to make web
pages interactive and dynamic. JavaScript is used with HTML and CSS.
Variables: Variables are used to store data. let, const, or var is used to declare
variables in JavaScript.
Example:
javascript
let name = "Rahul";
console.log(name);
Output: Rahul
1. Statements: Statements are the instructions given to execute JavaScript.
Example:
javascript
let age = 25; // This is a statement
2. Operators: Operators are used to perform arithmetic, comparison or
logical operations.
Example:
javascript
let sum = 5 + 10; // use of + operator
console.log(sum);
Output: 15
3. Comments: Comments are used to give notes or explanations in the code.
They do not execute the code.
Example:
javascript
// This is a single-line comment
/* This is a multi-line comment */
4. Constructs: Constructs define the structure of programming, such as loops
and conditions.
5. Functions: Functions are reusable code blocks that perform specific tasks.
Example:
javascript
function greet() {
console.log("Hello!");
}
greet();
Output: Hello!
6. Expressions: Expressions are those codes that return a value.
Example:
javascript
let result = 10 * 5; // This is an expression
7. JavaScript Console: Console is used for debugging and viewing messages.
You can print messages using the console.log() function.
8. Scope: Scope defines the visibility of the variable. There is global scope
and local scope.
Variable scope means in which area the variable is accessible. It has two
main types: Global Scope and Local Scope.
1. Global Scope: When a variable can be accessed from any part of the
program, it is called a global variable. Global variables are declared
at the beginning of the program.
Example:
javascript
let globalVar = "I am a global variable"; // Global variable
function showGlobal() {
console.log(globalVar); // Accessible here
}
showGlobal(); // Output: I am a global variable
console.log(globalVar); // Output: I am a global variable
2. Local Scope: When a variable is declared inside a function, it is
called a local variable. Local variables are accessible only inside the
function where they are declared.
Example:
javascript
function showLocal(){
let localVar = "I am a local variable"; // Local variable
console.log(localVar); // Accessible here
}
showLocal(); // Output: I am a local variable
console.log(localVar); // This line will give an error because localVar
is not accessible here
9. Events: Events are used to handle user interactions, such as clicks or
keystrokes.
Example:
html
<button onclick="alert('Button clicked!')">Click me</button>
10.Strings: Strings represent text data.
Example:
javascript
let greeting = "Hello, World!";
console.log(greeting);
Output: Hello, World!
11.String Methods: There are methods to perform operations with strings.
Example:
javascript
let str = "JavaScript";
console.log(str.length); //Length method
Output: `10`
12.Numbers: Numbers represent numerical data.
Example:
javascript
let number = 42;
console.log(num);
Output: `42`
13.Number Methods: There are methods to perform operations with
numbers.
Example:
javascript
let num = 5.6;
console.log(num.toFixed(1)); //toFixed method
Output: 5.6
14.Dates: `Date` object is used to represent dates.
Example:
Javascript
let date = new Date();
console.log(date);
15.Date Formats: There are methods to display dates in different formats.
Example:
javascript
let date = new Date();]
console.log(date.toDateString());
16.Date Methods: There are methods to perform operations with dates.
Example:
javascript
let date = new Date();
console.log(date.getFullYear()); // Get current year
17.Arrays: Arrays are used to store multiple values.
Example:
javascript
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[1]); // Accessing array element
Output: Banana
18.Array Methods: There are methods to perform operations with arrays.
Example:
Javascript
let fruits = ["Apple", "Banana", "Cherry"];
fruits.push("Orange"); //Adding an element
console.log(fruits);
Operators:
Let's understand in detail about all these operators and statements:
1. Arithmetic Operators: These operators are used for mathematical
calculations.
Example:
+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
% (Modulus)
Example:
javascript
let a = 10;
let b = 5;
console.log(a + b); // 15
console.log(a - b); // 5
console.log(a * b); // 50
console.log(a / b); // 2
console.log(a % b); // 0
2. Assignment Operators: These operators are used to assign values to
variables.
Example:
= (Simple assignment)
+= (Addition assignment)
-= (Subtraction assignment)
Output Example:
javascript
let x = 10;
x += 5; // x = x + 5
console.log(x); //15
3. Comparison Operators: These operators do compare values and give a
boolean result (true or false).
Example:
== (Equal to)
=== (Strict equal to)
!= (Not equal to)
> (Greater than)
< (Less than)
Output Example:
javascript
console.log(5 == '5'); //true
console.log(5 === '5'); //true
console.log(5 > 3); //true
4. Logical Operators: These operators are used for logical operations.
Logical operators are used in programming and mathematics, whose job is
to manipulate boolean values (true or false). Using these operators, we
can combine or compare conditions.
The most common logical operators are: AND, OR, and NOT.
Let's see their examples:
1. AND Operator (&&):
When we check two or more conditions and both the conditions should
be true, then we use the AND operator.
Example:
- Condition 1: A = true
- Condition 2: B = true
- The result of A && B will be true because both the conditions are true.
- If A = true and B = false, then the result of A && B will be false.
2. OR Operator (||):
When we want result if only one condition is true, then we use OR
operator.
Example:
- Condition 1: A = true
- Condition 2: B = false
- The result of A || B will be true because A is true.
- If both A and B are false, then the result of A || B will be false.
3. NOT Operator (!):
This operator returns the opposite value of a condition. If the condition is
true, then using NOT operator we will get false and vice versa.
Example:
- Condition: A = true
- The result of !A will be false.
- If A = false, then the result of !A will be true.
5. Bitwise Operators:
Bitwise operators are those operators which work on the bits of numbers
in binary representation. They are used to perform logical operations,
such as AND, OR, NOT, XOR, etc. Let us understand them with an
example.
Suppose, we have two numbers:
A = 5 (binary: 0101)
B = 3 (binary: 0011)
1. Bitwise AND (&):
This operator returns 1 only when both the bits are 1.
A & B = 0101 & 0011 = 0001 (binary) = 1 (decimal)
2. Bitwise OR (|):
This operator returns 1 when at least one bit is 1.
A | B = 0101 | 0011 = 0111 (binary) = 7 (decimal)
3. Bitwise XOR (^):
This operator returns 1 when both bits are different.
A ^ B = 0101 ^ 0011 = 0110 (binary) = 6 (decimal)
4. Bitwise NOT (~):
This operator inverts the bits. Meaning, it converts 0 to 1 and 1 to 0.
~A = ~0101 = 1010 (binary) = -6 (decimal, in 2's complement
representation)
How it works?
The work of the bitwise NOT operator (~) is to invert the binary bits. It
means that it converts 0 to 1 and 1 to 0.
If we take the binary number 0101 and apply the bitwise NOT operator on
it, then:
~0101 = 1010
Now, to convert 1010 into decimal, first of all we have to understand that
it is 2's complement representation.
In 2's complement representation, if the first bit (leftmost bit) of the
binary number is 1, then it represents a negative number.
So, to convert 1010 into decimal, first of all take out the 2's complement
of this number:
1. Take the 1's complement of 1010:
0101
2. Now add 1 to it:
0101 + 0001 = 0110
Now convert 0110 into decimal:
- 0 * 2^3 = 0
- 1 * 2^2 = 4
- 1 * 2^1 = 2
- 0 * 2^0 = 0
Its total is: 0 + 4 + 2 + 0 = 6
But since the original number was 1010, which is negative, we write it as
-6
5. Left Shift (<<):
This operator shifts the bits to the left, which multiplies the number by 2.
A << 1 = 0101 << 1 = 1010 (binary) = 10 (decimal)
How it works?
Left shift operator shifts the bits towards left. When you shift a number to
left, it is equivalent to multiplying the number by 2.
For example:
A = 0101 (binary), which is 5 in decimal.
If we shift A 1 bit to left:
A << 1 = 0101 << 1 = 1010
Here, 0101 has been shifted one position to left. Now it becomes 1010,
which is 10 in decimal.
Its meaning is:
5 * 2 = 10
6. Right Shift (>>):
This operator shifts the bits towards right, which divides the number by 2.
A >> 1 = 0101 >> 1 = 0010 (binary) = 2 (decimal)
How it works?
1. Binary Representation:
A = 0101 (binary), which is equal to 5 in decimal.
2. Right Shift Operator:
When we right shift A by 1 bit, it means we are shifting its bits one
position to the right.
3. Shifting Bits:
A = 0101
When we right shift it:
- The first bit (0) is discarded.
- The remaining bits (101) are shifted one position to the right.
Like this:
0101 >> 1 = 0010
4. Resulting Binary:
Now the binary number we have is 0010.
5. Decimal Conversion:
0010 is the decimal value of binary 2.
This means:
5 / 2 = 2 (in integer division the remainder is discarded)
6. Conditional Statements: These statements perform different actions
based on conditions.
if else: The if-else statement in JavaScript is used to implement
conditional logic. This means that you check some conditions and perform
different actions based on them.
Syntax:
if (condition) {
// code block if condition is true
} else {
// code block if condition is false
}
Example:
javascript
let age = 18;
if (age >= 18) {
console.log("Adult");
} else {
console.log("Not an adult");
Output: "Adult"
switch: switch case is a programming construct used to handle multiple
conditions. It is an alternative to the if-else statement, which is more
readable and organized when you need to check multiple possible values
of a variable.
Syntax:
switch (expression) {
case value1:
// code block for value1
break;
case value2:
// code block for value2
break;
// more cases...
default:
// code block if none of the cases match
}
Example:
javascript
let days = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
case 3:
console.log("Wednesday");
break;
default:
console.log("Not a valid day");
Output: "Wednesday"
7. Loops: These statements execute a block of code repeatedly.
-while: In JavaScript, the while loop is used when you want to execute a
block of code repeatedly until a condition is true. Its basic syntax is:
Syntax:
while (condition) {
// code block to be executed
}
Here, as long as the condition is true, the code inside the loop will keep
on executing. If the condition becomes false, the loop ends.
Example:
javascript
let i = 0;
while (i < 5) {
console.log(i);
i++;
Output: 0, 1, 2, 3, 4
do while: Do while loop is also used in JavaScript, but there is a slight
difference in it. Do while loop is used when you want the code block to be
executed at least once, whether the condition is true or false.
Its syntax is:
javascript
do {
// code block to be executed
}
while (condition);
Here, the code block is executed first and then the condition is checked. If
the condition is true, then the loop will run again; if it is false, then the
loop will end.
Example:
javascript
let j = 0;
do {
console.log(j);
j++;
} while (j < 5);
Output: 0, 1, 2, 3, 4
For: For loop is a control structure in programming that allows you to
execute a code block a specific number of times. This loop is used when
you need to iterate over the elements of a sequence or array or run a loop
based on a condition.
Syntax:
javascript
for (initialization; condition; increment/decrement) {
// code block to be executed
}
Here there are three main parts of for loop:
1. Initialization: This part sets a variable before the loop starts.
let i = 0;
2. Condition: This part checks whether to run the loop or not. If the
condition is true, the loop will run; if it is false, the loop will end.
For example, i < 5;
3. Increment/Decrement: This part updates the variable after every iteration
of the loop. For example, i++ (i increases by 1).
Example:
javascript
for (let k = 0; k < 5; k++) {
console.log(k);
Output: 0, 1, 2, 3, 4
In this example:
1. let i = 0; initializes the loop and the value of i is set to 0.
2. i < 5; condition is checked. As long as the value of i is less than 5, the
loop will run.
3. i++ will increase the value of i by 1 every time at the end of the loop.
for...in & for…of loop:
In JavaScript, for...in and for...of loops are used to iterate over
collections (arrays, objects), but the work of both is different.
1. for...in loop:
- This loop iterates the keys of the properties of objects.
- You use it to access the properties inside the objects.
- This loop can also iterate the indices(location) of the array, but it
does not access the elements of the array directly.
Example:
javascript
const person = { name: "John", age: 30, city: "Mumbai" };
for (let key in person) {
console.log(key + ": " + person[key]);
}
This code means that you are iterating the properties of an object
person and printing its keys and values. Let's understand this code
step-by-step:
a. Object Declaration:
javascript
const person = { name: "John", age: 30, city: "Mumbai" };
Here person is an object which has three properties: name, age, and
city.
b. for...in Loop:
javascript
for (let key in person) {
This line starts the loop which will iterate the keys of each property of
person object. Here the key variable will store the name of the object's
property in every iteration.
c. Console Log:
javascript
console.log(key + ": " + person[key]);
This line uses the console.log function which prints the output on the
console. By using key, you are accessing the value of the object's
property. This happens through person[key], which returns the value
of the current key.
So when this code runs, the output will be:
name: John
age: 30
city: Mumbai
2. for...of loop:
- This loop iterates the values of iterable objects (like arrays, strings,
maps, sets).
- It is used to access the elements directly.
Example:
javascript
const fruits = ["Apple", "Banana", "Mango"];
for (let fruit of fruits) {
console.log(fruit);
}
Output:
Apple
Banana
Mango
Summary:
- The for...in loop is used to iterate the keys of the object's properties.
- for...of loop is used to iterate the values of iterable objects.
Loop Control Statements:
- break: This statement is used to terminate the loop.
Example:
``javascript
for (let i = 0; i < 5; i++) {
if (i === 3) {
break;
console.log(i);
Output:
0
1
- continue: This statement is used to skip the current iteration and
jump to the next iteration.
Example:
``javascript
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue;
console.log(i);
}
Output:
0
1
3
4
Labels: Labels are used to identify the loop so that we can apply break
or continue on a specific loop.
Example:
javascript
outerLoop: for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
if (i === 1 && j === 1) {
break outerLoop;
}
console.log(i, j);
}
}
Output:
00
01
02
10
Let us understand this code step by step.
1. Outer Loop:
- It starts with `outerLoop: for (let i = 0; i < 3; i++)`. This loop
increments `i` from 0 to 2. This means that this loop will run 3 times
(for 0, 1, and 2).
2. Inner Loop:
- There is another loop inside this outer loop: `for (let j = 0; j < 3; j++)`.
This loop increments `j` also from 0 to 2, meaning that this will also run
3 times.
3. Condition Check:
- Now we check the condition: `if (i === 1 && j === 1)`. It checks
whether the value of `i` is 1 and the value of `j` is also 1.
- If this condition is true, then `break outerLoop;` is executed. This
means that this statement will break the outer loop, i.e. you exit the
outer loop.
4. Console Output:
- Let us see the statement `console.log(i, j);`. This statement will print
the current values of `i` and `j`.
- This will keep printing as long as the condition is not true.
5. Execution Flow:
- When `i = 0` happens:
- `j = 0` → print: `0 0`
- `j = 1` → print: `0 1`
- `j = 2` → print: `0 2`
- When `i = 1` happens:
- `j = 0` → print: `1 0`
- `j = 1` → If the condition is true, then `break outerLoop` is executed
and you exit the outer loop. So `1 1` and the values beyond it are not
printed.
6. Final Output:
- On running this code the output will be this:
00
01
02
10