We will learn about
- Variable Scope
- Block Scope
- Global Scope
- Loops
- for loop
- while loop
- do…while loop
- for…of loop
- for…in loop
- Object
Variable Scope
At its core, scope in JavaScript refers to the context or environment in which variables are declared and can be accessed. A solid grasp of scope is indispensable because it can affect how your code behaves and interacts with other parts of your application.
Block Scope
Variables declared inside a block { } cannot be accessed from outside the block.
{
let b = 10;
console.log(b);
}
console.log(b); // gives error
console.log(b);
written outside the block will give error because "b"
is decalred inside a block and can only be used inside that block.
Output:
10
Uncaught ReferenceError: b is not defined
If we want to use "b"
outside the block, we have to declare it using var
keyword. var keyword has a global scope.
{
var b = 10;
console.log(b);
}
console.log(b);
Output:
10
10
Global Scope
Variables declared outside a block has global scope.
let a = 5;
{
console.log("inside a block",a);
}
console.log("outside a block",a);
variable can be accessed anywhere because it is declared globally and not inside the block.
Output:
inside a block 5
outside a block 5
Loops
Loops offer a quick and easy way to do something repeatedly. There are many different kinds of loops, but they all essentially do the same thing: they repeat an action some number of times.
The various loop mechanisms offer different ways to determine the start and end points of the loop. There are various situations that are more easily served by one type of loop over the others.
For example, if I have to display something 5 times, I have to write
console.log("Welcome to my blog");
console.log("Welcome to my blog");
console.log("Welcome to my blog");
console.log("Welcome to my blog");
console.log("Welcome to my blog");
Here I am writing "Welcome to my blog"
5 times. Imagine if I have to write it thousand times. I have to write console.log("Welcome to my blog");
thousand times. Instead of this, I can use a loop which will make my code compact.
for(int i = 1; i <= 5; i++){
console.log("Welcome to my blog");
}
Both of the above codes will produce the same output.
JavaScript provides the following loops:
- for loop
- while loop
- do…while loop
- for…of loop
- for…in loop
for loop
A for
loop repeats until a specified condition evaluates to false. The JavaScript for
loop is similar to the Java and C for
loop.
Syntax
for (initialization; condition; updation){
statement(s)
}
Initialization: This part is executed once before the loop begins. It’s typically used to initialize a variable (often a counter) that will be used to control the loop’s iterations. For example, int i = 1;
initializes a variable i
to 1.
Condition: This expression is evaluated before each iteration. If the condition is true, the code within the loop body is executed. If it’s false, the loop terminates. Common conditions involve comparisons like i <= 5
Updation: This expression is executed after each iteration, regardless of whether the condition is true or false. It’s often used to modify the value of the counter variable, ensuring the condition eventually becomes false and the loop ends. Common updations involve increments like i++
or decrements like i--
.
How Loop Works:
When a for
loop executes, the following occurs:
- The initializing expression
initialization
, if any, is executed. This expression usually initializes one or more loop counters. This expression can also declare variables. - The
condition
expression is evaluated. If the value ofcondition
is true, the loop statements execute. Otherwise, thefor
loop terminates. (If thecondition
expression is omitted entirely, the condition is assumed to be true.) - The
statement
executes. To execute multiple statements, use a block statement ({ }
) to group those statements. - If present, the update expression
updation
is executed. - Control returns to Step 2.
Code:
for (let i = 0; i < 5; i++) {
console.log(i);
}
- Initialization: The variable
i
is initialized to 0. - Condition: The loop continues as long as
i
is less than 5. - Body: The value of
i
is printed to the console usingconsole.log(i)
. - Updation: The value of
i
is incremented by 1. - Steps 2-4 are repeated until the condition
i < 5
becomes false.
Output:
0
1
2
3
4
while loop
A while
statement executes its statements as long as a specified condition evaluates to true
.
Syntax
while (condition)
{
statement(s)
}
The condition test occurs before statement
in the loop is executed. If the condition returns true
, statement
is executed and the condition
is tested again. If the condition returns false
, execution stops, and control is passed to the statement following while
.
Code:
let n = 0;
let sum = 0;
while (n < 3) {
n++; // n = n + 1
sum += n; //sum = sum + n
}
console.log(sum);
With each iteration, the loop increments n
and adds that value to sum. Therefore, sum and n
take on the following values:
- After the first pass:
n = 1
andsum = 1 (0 + 1)
- After the second pass:
n = 2
andsum = 3 (1 + 2)
- After the third pass:
n = 3
andsum = 6 (3 +3)
After completing the third pass, the condition n < 3
is no longer true
, so the loop terminates. After the loop finishes, the final value of sum
is printed to the console using console.log(sum);
Output:
6
do…while loop
The do...while
statement repeats until a specified condition evaluates to false.
A do...while
statement looks as follows:
Syntax
do {
statement(s)
}
while (condition);
statement
is always executed once before the condition is checked. If condition
is true
, the statement executes again. At the end of every execution, the condition is checked. When the condition is false
, execution stops, and control passes to the statement following do...while
.
Code:
let i = 0;
do {
i += 1;
console.log(i);
} while (i < 5);
1.Inside the do Block:
i += 1
: This line increments the value of i
by 1. So, in the first iteration, i
becomes 1.
console.log(i)
: This line prints the current value of i
to the console. In this case, it prints 1.
2.while (i < 5)
:
This line checks the loop condition. Since i
is now 1 and 1 is less than 5, the condition is true.
Since the condition is true, the code jumps back to the do
block and repeats steps 1.
In the second iteration, i
becomes 2, it gets printed, and the condition is checked again. This repeats until i
reaches 5.
When i
becomes 5, the condition i < 5
becomes false.
Since the condition is false, the loop terminates.
Output:
1
2
3
4
5
for…of loop
for…of statement iterates over the values of an iterable object (like String, Array etc)
for…of loop makes it easy to loop through the elements without needing to handle the index or iteration logic which makes the code short and easier to understand.
Syntax
for ( variable of iterableObjectName) {
statement(s) to be executed
}
variable – For every iteration the value of the next property is assigned to the variable. Variable can be declared with const
, let
, or var
.
iterableObjectName – An object that has iterable properties (e.g String).
We already know about strings. Lets take an example of how for…of loop works.
Code:
let name = "Peter";
for (let i of name) {
console.log(i);
}
Each individual letter of string is called character like “P” “e” “t” “e” “r” are 5 characters of Peter
.
for...of
loop iterates over the characters of the string name
.
let i
: This declares a variable namedi
within the loop. In each iteration,i
will hold the current character of the string.of name
: This specifies that the loop will iterate over the values of thename
string.console.log(i)
: Inside the loop, this line prints the current character (i
) to the console.
Output:
P
e
t
e
r
Before understanding for…in loop we should know the basic concept of objects.
Object
JavaScript object is a data-type that allows you to store collection of different variables/data types.
JavaScript variables can contain single value. But objects can contain many values.
For example, a student
has many properties like name, age, roll number, cgpa etc. A student object will be created like this.
const student = {
name: "Peter",
age : 21,
cgpa : 3.5,
isPass : true,
};
Student object has two things here i.e. keys
and values.
name
, age
, cgpa
and isPass
are keys.
Peter
, 21
, 3.5
and true
are the values of keys.
console.log(student);
will display the object.
Output:
{name: 'Peter', age: 21, cgpa: 3.5, isPass: true}
We can access and manipulate individual key. We can access it by two ways:
console.log(student["name"]);
console.log(student.name);
Output:
Peter
Peter
We can also change values of keys.
student.name = "Tony";
student.age = 14;
Now the student object will look like this
Output:
{name: 'Tony', age: 14, cgpa: 3.5, isPass: true}
Now we know what objects are and how they works. Let’s dive in to for...in loop
for…in loop
The for...in
statement iterate over the properties(keys) of an object. It returns the keys of an object.
Rest of the working is similar to for...of
loop.
Syntax
for ( variable in object) {
statement(s) to be executed
}
Code:
const student = {
name: "Peter",
age : 21,
cgpa : 3.5,
isPass : true,
};
for (let i in student) {
console.log(i);
}
Output:
name
age
cgpa
isPass
Once we have the keys, we can also get their values.
for (let i in student) {
console.log("key=", i ,"and value=",student[i]);
}
Output:
key= name and value= Peter
key= age and value= 21
key= cgpa and value= 3.5
key= isPass and value= true
Leave a Reply