JavaScript Variables
JavaScript Variables can be declared in 4 ways:
● Automatically
● Using var
● Using let
● Using const
Example:
x = 5;
var i = 10;
let y = 6;
const o = 8;
z = x + y;
When to Use var, let, or const?
1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed (Arrays and Objects)
4. Only use let if you can't use const
5. Only use var if you MUST support old browsers.
Block Scope:
● Variables declared inside a { } block cannot be accessed from outside the block.
Global Scope:
● Variables declared with the var always have Global Scope.
● Variables declared with the var keyword can NOT have block scope.
Initializing arrays in JavaScript
const fruits = ['apple', 'orange', 'mango', 'grapes', 'pineapple'];
Initializing an object in JavaScript
const fruit = {
name: 'apple',
color: 'red',
taste: 'sweet',
};
JavaScript Conditional Statement Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}
Example:
x = 5;
if (x == 5) {
text = 'Hep Hep';
} else {
text = 'Hooray';
} //output Hep Hep
JavaScript Switch Statement Syntax
x = 6;
switch (x) {
case 5:
text = 'Hep Hep';
break;
case 6:
text = 'Hooray';
break;
default:
text = 'Hello World';
} //output Hooray
JavaScript For Loop Syntax
const fruits = ['apple', 'orange', 'mango', 'grapes', 'pineapple'];
for (let i = 0; i < fruits.length; i++) {
text += fruits[i] + ', ';
}
// Output: apple, orange, mango, grapes, pineapple,
JavaScript For Of Loop
The JavaScript for of statement loops through the values of an iterable object.
Syntax:
for (variable of iterable) {
// code block to be executed
}
Example:
const fruits = ['apple', 'orange', 'mango', 'grapes', 'pineapple'];
for (fruit of fruits) {
text += fruits[i] + ', ';
}
// Output: apple, orange, mango, grapes, pineapple,
JavaScript For In Loop
The JavaScript for in statement loops through the properties of an Object
Syntax:
for (key in object) {
// code block to be executed
}
Example:
const fruit = {
name: 'apple',
color: 'red',
taste: 'sweet',
};
for (key in fruit) {
text += key + ': ' + fruit[key] + ', ';
}
// Output: name: apple, color: red, taste: sweet,