// Using var (function-scoped)
var x = 5;
// Using let (block-scoped)
let y = 10;
// Using const (block-scoped, cannot be reassigned)
const PI = 3.14159;
// Number
let num = 42;
let float = 3.14;
// String
let str = "Hello, World!";
// Boolean
let isTrue = true;
let isFalse = false;
// Undefined
let undefinedVar;
// Null
let nullVar = null;
// Symbol
let sym = Symbol("unique");
// BigInt
let bigInt = 1234567890123456789012345678901234567890n;
// Object
let obj = {name: "John", age: 30};
// Array
let arr = [1, 2, 3, 4, 5];
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (this is a known bug in JavaScript)
console.log(typeof Symbol()); // "symbol"
console.log(typeof {}); // "object"
console.log(typeof []); // "object"
console.log(typeof function(){}); // "function"
let a = 10, b = 5;
console.log(a + b); // Addition: 15
console.log(a - b); // Subtraction: 5
console.log(a * b); // Multiplication: 50
console.log(a / b); // Division: 2
console.log(a % b); // Modulus: 0
console.log(a ** b); // Exponentiation: 100000
// Increment and Decrement
let c = 5;
console.log(c++); // 5 (post-increment)
console.log(++c); // 7 (pre-increment)
console.log(c--); // 7 (post-decrement)
console.log(--c); // 5 (pre-decrement)
let x = 5, y = '5';
console.log(x == y); // true (loose equality)
console.log(x === y); // false (strict equality)
console.log(x != y); // false (loose inequality)
console.log(x !== y); // true (strict inequality)
console.log(x > 3); // true
console.log(x < 3); // false
console.log(x >= 5); // true
console.log(x <= 5); // true
let a = true, b = false;
console.log(a && b); // false (AND)
console.log(a || b); // true (OR)
console.log(!a); // false (NOT)
// Short-circuit evaluation
console.log(true && 'Hello'); // 'Hello'
console.log(false && 'Hello'); // false
console.log(true || 'Hello'); // true
console.log(false || 'Hello'); // 'Hello'
let x = 10;
x += 5; // x = x + 5
console.log(x); // 15
x -= 3; // x = x - 3
console.log(x); // 12
x *= 2; // x = x * 2
console.log(x); // 24
x /= 4; // x = x / 4
console.log(x); // 6
x %= 4; // x = x % 4
console.log(x); // 2
x **= 3; // x = x ** 3
console.log(x); // 8
let age = 18;
if (age >= 18) {
console.log("You are an adult");
} else if (age >= 13) {
console.log("You are a teenager");
} else {
console.log("You are a child");
}
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the work week");
break;
case "Friday":
console.log("End of the work week");
break;
case "Saturday":
case "Sunday":
console.log("Weekend");
break;
default:
console.log("Midweek");
}
for (let i = 0; i < 5; i++) {
console.log(i);
}
// Output: 0, 1, 2, 3, 4
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
// Output: 0, 1, 2, 3, 4
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
// Output: 0, 1, 2, 3, 4
let arr = ['a', 'b', 'c'];
for (let item of arr) {
console.log(item);
}
// Output: 'a', 'b', 'c'
let obj = {a: 1, b: 2, c: 3};
for (let prop in obj) {
console.log(prop + ': ' + obj[prop]);
}
// Output: 'a: 1', 'b: 2', 'c: 3'
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("John")); // Output: "Hello, John!"
const greet = function(name) {
return "Hello, " + name + "!";
};
console.log(greet("Jane")); // Output: "Hello, Jane!"
const greet = (name) => {
return "Hello, " + name + "!";
};
// Shorter syntax for single expression
const greetShort = name => "Hello, " + name + "!";
console.log(greetShort("Alice")); // Output: "Hello, Alice!"
function greet(name = "Guest") {
return "Hello, " + name + "!";
}
console.log(greet()); // Output: "Hello, Guest!"
console.log(greet("Bob")); // Output: "Hello, Bob!"
function sum(...numbers) {
return numbers.reduce((total, num) => total + num, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // Output: 15
let fruits = ['apple', 'banana', 'orange'];
let numbers = new Array(1, 2, 3, 4, 5);
let arr = [1, 2, 3, 4, 5];
// Adding elements
arr.push(6); // Adds to the end
arr.unshift(0); // Adds to the beginning
// Removing elements
arr.pop(); // Removes from the end
arr.shift(); // Removes from the beginning
// Finding elements
console.log(arr.indexOf(3)); // Returns 2
console.log(arr.includes(3)); // Returns true
// Transforming arrays
let doubled = arr.map(num => num * 2);
let evenNumbers = arr.filter(num => num % 2 === 0);
let sum = arr.reduce((total, num) => total + num, 0);
// Iterating
arr.forEach(num => console.log(num));
// Sorting
arr.sort((a, b) => a - b); // Ascending order
// Adding/Removing elements at specific positions
arr.splice(2, 0, 6, 7); // Adds 6 and 7 at index 2: [1, 2, 6, 7, 3, 4, 5]
arr.splice(3, 2); // Removes 2 elements starting from index 3: [1, 2, 6, 4, 5]
let person = {
name: "John",
age: 30,
greet: function() {
console.log("Hello, my name is " + this.name);
}
};
// Accessing properties
console.log(person.name); // "John"
console.log(person['age']); // 30
// Calling method
person.greet(); // "Hello, my name is John"
let keys = Object.keys(person); // ['name', 'age', 'greet']
let values = Object.values(person); // ['John', 30, [Function: greet]]
let entries = Object.entries(person); // [['name', 'John'], ['age', 30], ['greet', [Function: greet]]]
// Merging objects
let obj1 = {a: 1, b: 2};
let obj2 = {c: 3, d: 4};
let merged = Object.assign({}, obj1, obj2);
// Or using spread operator
let mergedSpread = {...obj1, ...obj2};
// Array destructuring
let [a, b, c] = [1, 2, 3];
console.log(a, b, c); // 1 2 3
// Object destructuring
let {name, age} = {name: "John", age: 30};
console.log(name, age); // "John" 30
let arr1 = [1, 2, 3];
let arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]
let obj1 = {a: 1, b: 2};
let obj2 = {...obj1, c: 3}; // {a: 1, b: 2, c: 3}
let name = "John";
let greeting = `Hello, ${name}!`;
console.log(greeting); // "Hello, John!"
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
let john = new Person("John", 30);
john.greet(); // "Hello, my name is John"
let element = document.getElementById('myId');
let elements = document.getElementsByClassName('myClass');
let elements = document.getElementsByTagName('div');
let element = document.querySelector('.myClass');
let elements = document.querySelectorAll('div');
element.innerHTML = 'New content';
element.setAttribute('class', 'newClass');
element.style.color = 'red';
let newDiv = document.createElement('div');
newDiv.innerHTML = 'Hello, World!';
document.body.appendChild(newDiv);
element.parentNode.removeChild(element);
// Or
element.remove();
element.addEventListener('click', function(event) {
console.log('Element clicked!');
});
function fetchData(callback) {
setTimeout(() => {
callback('Data fetched');
}, 1000);
}
fetchData(result => console.log(result));
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data fetched');
}, 1000);
});
}
fetchData()
.then(result => console.log(result))
.catch(error => console.error(error));
async function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data fetched');
}, 1000);
});
}
async function getData() {
try {
const result = await fetchData();
console.log(result);
} catch (error) {
console.error(error);
}
}
getData();
try {
// Code that may throw an error
throw new Error('Something went wrong');
} catch (error) {
console.error(error.message);
} finally {
console.log('This always runs');
}
class CustomError extends Error {
constructor(message) {
super(message);
this.name = 'CustomError';
}
}
try {
throw new CustomError('This is a custom error');
} catch (error) {
console.error(error.name + ': ' + error.message);
}
2024 © All rights reserved - buraxta.com