Variables:
JAVA SCRIPT
// Declare a variable with let let x = 5; // Declare a constant with const const y = 10; // Declare a variable without assigning a value let z;
Data types:
JAVA SCRIPT
// Number
let a = 5;
let b = 3.14;
// String
let c = "Hello";
let d = 'World';
// Boolean
let e = true;
let f = false;
// Undefined
let g;
// Null
let h = null;
// Object
let i = { name: "John", age: 30 };
// Array
let j = [1, 2, 3, 4];
Operators:
JAVA SCRIPT
// Arithmetic operators let a = 5 + 2; // 7 let b = 5 - 2; // 3 let c = 5 * 2; // 10 let d = 5 / 2; // 2.5 let e = 5 % 2; // 1 // Comparison operators let f = 5 == 5; // true let g = 5 === '5'; // false let h = 5 != 5; // false let i = 5 !== '5'; // true let j = 5 > 2; // true let k = 5 < 2; // false let l = 5 >= 5; // true let m = 5 <= 2; // false // Logical operators let n = true && false; // false let o = true || false; // true let p = !true; // false
Conditional statements:
JAVA SCRIPT
// If statement
let a = 5;
if (a > 2) {
console.log("a is greater than 2");
}
// If-else statement
let b = 1;
if (b > 2) {
console.log("b is greater than 2");
} else {
console.log("b is less than or equal to 2");
}
// If-else if-else statement
let c = 0;
if (c > 0) {
console.log("c is positive");
} else if (c < 0) {
console.log("c is negative");
} else {
console.log("c is zero");
}
Loops:
JAVASCRIPT
// For loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
// While loop
let j = 0;
while (j < 5) {
console.log(j);
j++;
}
// Do-while loop
let k = 0;
do {
console.log(k);
k++;
} while (k < 5);
// For-in loop (used to loop over properties of an object)
let person = { name: "John", age: 30 };
for (let key in person) {
console.log(key + ": " + person[key]);
}
// For-of loop (used to loop over elements of an array)
let arr = [1, 2, 3];
for (let value of arr) {
console.log(value);
}
Functions:
JAVASCRIPT
// Function declaration
function add(a, b) {
return a + b;
}
// Function expression
let multiply = function(a, b) {
return a * b;
};
//
No comments:
Post a Comment