Java Script Topics with Examples
for loop iterating Array
for loop iterating Object
forEach Example 1
forEach Example 2
for in Array Example 1
for in Array Example 2
for in Object Example 1
for in Object Example 2
Nested for loop Example
function Example 1
function Example 2
for loop iterating Array
let carsArray = ['BMW','Audi']
for (let i = 0; i < carsArray.length; i++) {
console.log(carsArray[i]);
}
Output
BMW
Audi
for loop iterating Object
let carObject = {'name':'BMW','year':'2002'}
let carKeys = Object.keys(carObject); //['name','year']
for (let i = 0; i < carKeys.length; i++) {
console.log(carObject[carKeys[i]]);
}
Output
BMW
2002
forEach Example 1
let carsArray = ['BMW','Audi']
carsArray.forEach(e=> {
console.log(e)
})
Output
BMW
Audi
forEach Example 2
let carsArray = ['BMW','Audi']
carsArray.forEach((e,index) => {
console.log(e,'-',index)
})
Output
BMW - 0
Audi - 1
for in Array Example 1
for in looping give you access to the index in the array, not the actual element
let carsArray = ['BMW','Audi']
for (let i in carsArray) {
console.log(i);
}
Output
0
1
for in Array Example 2
let carsArray = ['BMW','Audi']
for (let i in carsArray) {
console.log(carsArray[i]);
}
Output
BMW
Audi
for in Object Example 1
let carObject = {'name':'BMW','year':'2002'}
for (let i in carObject) {
console.log(i);
}
Output
name
year
for in Object Example 2
let carObject = {'name':'BMW','year':'2002'}
for (let i in carObject) {
console.log(carObject[i]);
}
Output
BMW
2002
Nested for loop Example
let text = "";
for (let i = 0; i < 3; i++) {
text += i + " ";
for (let j = 10; j < 13; j++) {
text += j + " ";
}
console.log(text);
}
Output
0 10 11 12
0 10 11 12 1 10 11 12
0 10 11 12 1 10 11 12 2 10 11 12
function Example 1
let number1 = 4, number2 = 3;
var x = myFunction(number1, number2);
console.log(x);
function myFunction(a, b) {
return a * b;
}
Output
12
function Example 2
demo = "The temperature is " + toCelsius(77) + " Celsius";
console.log(demo)
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
Output
The temperature is 25 Celsius