Datatypes:
Data types are attributes that define the type of information a variable can store. They are important because they allow computers to understand and process data.
Uses of datatypes:
--> Data types are the language that computers use to understand data.
--> Data types tell the Memory Management Unit (MMU) how much memory is needed to store data.
JavaScript has 8 Datatypes,
- String
- Number
- Bigint
- Boolean
- Undefined
- Null
- Symbol
- Object
Variable:
In JavaScript, a variable is a named container that stores values. Variables are used to store and manage data, perform calculations, and make code dynamic.
JavaScript Variables can be declared in 4 ways:
- Automatically(Ex:
x = 5;
) - Using var(Ex:
var x = 5;
) - Using let(Ex:
let x = 5;
) - Using const(Ex:
const x = 5;
)
When to Use var, let, or const?
Always declare variables
Always use const if the value should not be changed
Always use const if the type should not be changed (Arrays and Objects)
Only use let if you can't use const.Let cannot be redeclared but can be reassigned.
Only use var if you MUST support old browsers.Var can be redeclared.
Refer: https://www.w3schools.com/js/js_variables.asp
JavaScript Operators:
Javascript operators are used to perform different types of mathematical and logical computations.
Conditional Statements:
In JavaScript we have the following conditional statements:
- Use if to specify a block of code to be executed, if a specified condition is true
Ex:
if (hour < 18) {
greeting = "Good day";
}
Output:
Good day
- Use else to specify a block of code to be executed, if the same condition is false
Ex:
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
Output:
Good day
- Use else if to specify a new condition to test, if the first condition is false
Ex:
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
Output:
Good day
- Use switch to specify many alternative blocks of code to be executed
Loops:
Loops can execute a block of code as long as a specified condition is true.
1) While Loop
--> The while loop loops through a block of code as long as a specified condition is true.
--> Instead of multiple if conditions we can use while loop.
Example:
let count = 0;
while (count<5) {
console.log(1);
count += 1;
Output:
1
1
1
1
1
TASK:
1) Get output : 5 4 3 2 1
let no = 5;
while (no >0) {
console.log(no);
no -= 1;
}
Output:
5
4
3
2
1
2) Get output : 1 2 3 4 5
let no = 1;
while (no <= 5) {
console.log(no);
no += 1;
}
Output:
1
2
3
4
5
3) Get output : 0 2 4 6 8 10
let no = 0;
while (no<=10) {
console.log(no);
no += 2;
}
Output:
0
2
4
6
8
10
4) Get output : 10 8 6 4 2 0
let no = 10;
while (no>=0) {
console.log(no);
no -= 2;
}
Output:
10
8
6
4
2
0
Top comments (0)