-
- Check if a variable is an array:
function isArray(variable) {
return Array.isArray(variable);
}
console.log(isArray([])); // Output: true
console.log(isArray('Hello')); // Output: false
-
- Check if a variable is an object:
function isObject(variable) {
return typeof variable === 'object' && variable !== null && !Array.isArray(variable);
}
console.log(isObject({})); // Output: true
console.log(isObject([])); // Output: false
-
- Check if a variable is a function:
function isFunction(variable) {
return typeof variable === 'function';
}
console.log(isFunction(() => {})); // Output: true
console.log(isFunction('Hello')); // Output: false
-
- Convert a string to an integer:
var number = parseInt('42');
console.log(number); // Output: 42
-
- Convert a string to a floating-point number:
var number = parseFloat('3.14');
console.log(number); // Output: 3.14
-
- Round a number to a specified decimal place:
var roundedNumber = 3.14159.toFixed(2);
console.log(roundedNumber); // Output: 3.14
-
- Generate a random number between a specified range:
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomNumber(1, 10)); // Output: Random number between 1 and 10
-
- Get the current date:
var currentDate = new Date();
console.log(currentDate); // Output: Current date and time
-
- Get the current year:
var currentYear = new Date().getFullYear();
console.log(currentYear); // Output: Current year
-
- Get the current month:
var currentMonth = new Date().getMonth() + 1; // Month is zero-based
console.log(currentMonth); // Output: Current month (1-12)
-
- Get the current day:
var currentDay = new Date().getDate();
console.log(currentDay); // Output: Current day (1-31)
-
- Get the current time:
var currentTime = new Date().toLocaleTimeString();
console.log(currentTime); // Output: Current time
-
- Get the length of an array:
var arr = [1, 2, 3];
var length = arr.length;
console.log(length); // Output: 3
-
- Check if an array contains a specific element:
var arr = [1, 2, 3];
var containsElement = arr.includes(2);
console.log(containsElement); // Output: true
-
- Add an element to the end of an array:
var arr = [1, 2, 3];
arr.push(4);
console.log(arr); // Output: [1, 2, 3, 4]
-
- Remove the last element from an array:
var arr = [1, 2, 3];
arr.pop();
console.log(arr); // Output: [1, 2]
-
- Add an element to the beginning of an array:
var arr = [2, 3, 4];
arr.unshift(1);
console.log(arr); // Output: [1, 2, 3, 4]
-
- Remove the first element from an array:
var arr = [1, 2, 3];
arr.shift();
console.log(arr); // Output: [2, 3]
-
- Concatenate two arrays:
var arr1 = [1, 2];
var arr2 = [3, 4];
var concatenatedArray = arr1.concat(arr2);
console.log(concatenatedArray); // Output: [1, 2, 3, 4]
-
- Reverse the elements of an array:
var arr = [1, 2, 3];
arr.reverse();
console.log(arr); // Output: [3, 2, 1]
-
- Sort the elements of an array in ascending order:
var arr = [3, 1, 2];
arr.sort();
console.log(arr); // Output: [1, 2, 3]
-
- Sort the elements of an array in descending order:
var arr = [3, 1, 2];
arr.sort(function(a, b) {
return b - a;
});
console.log(arr); // Output: [3, 2, 1]
-
- Find the index of an element in an array:
var arr = [1, 2, 3];
var index = arr.indexOf(2);
console.log(index); // Output: 1
-
- Remove an element from an array by index:
var arr = [1, 2, 3];
arr.splice(1, 1);
console.log(arr); // Output: [1, 3]
-
- Copy an array:
var arr1 = [1, 2, 3];
var arr2 = arr1.slice();
console.log(arr2); // Output: [1, 2, 3]
-
- Iterate over an array using a for loop:
var arr = [1, 2, 3];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
-
- Iterate over an array using forEach:
var arr = [1, 2, 3];
arr.forEach(function(element) {
console.log(element);
});
-
- Iterate over the keys of an object using for...in loop:
var obj = { name: 'John', age: 30 };
for (var key in obj) {
console.log(key + ': ' + obj[key]);
}
-
- Iterate over the values of an array using for...of loop:
var arr = [1, 2, 3];
for (var value of arr) {
console.log(value);
}
-
- Create a new array with the results of applying a function to each element:
var arr = [1, 2, 3];
var multipliedArray = arr.map(function(element) {
return element * 2;
});
console.log(multipliedArray); // Output: [2, 4, 6]
-
- Filter elements of an array based on a condition:
var arr = [1, 2, 3, 4, 5];
var filteredArray = arr.filter(function(element) {
return element % 2 === 0;
});
console.log(filteredArray); // Output: [2, 4]
-
- Check if all elements in an array satisfy a condition:
var arr = [2, 4, 6];
var allEven = arr.every(function(element) {
return element % 2 === 0;
});
console.log(allEven); // Output: true
-
- Check if at least one element in an array satisfies a condition:
var arr = [1, 2, 3];
var hasEven = arr.some(function(element) {
return element % 2 === 0;
});
console.log(hasEven); // Output: true
-
- Reduce an array to a single value:
var arr = [1, 2, 3];
var sum = arr.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 6
-
- Find the maximum value in an array:
var arr = [3, 1, 2];
var max = Math.max(...arr);
console.log(max); // Output: 3
-
- Find the minimum value in an array:
var arr = [3, 1, 2];
var min = Math.min(...arr);
console.log(min); // Output: 1
-
- Convert an array to a string, separating the elements with a delimiter:
var arr = [1, 2, 3];
var str = arr.join(', ');
console.log(str); // Output: "1, 2, 3"
-
- Check if a string contains a substring:
var str = 'Hello, world!';
var containsSubstring = str.includes('world');
console.log(containsSubstring); // Output: true
-
- Check if a string starts with a specific prefix:
var str = 'Hello, world!';
var startsWithHello = str.startsWith('Hello');
console.log(startsWithHello); // Output: true
-
- Check if a string ends with a specific suffix:
var str = 'Hello, world!';
var endsWithWorld = str.endsWith('world!');
console.log(endsWithWorld); // Output: true
-
- Convert a string to uppercase:
var str = 'hello';
var uppercaseStr = str.toUpperCase();
console.log(uppercaseStr); // Output: "HELLO"
-
- Convert a string to lowercase:
var str = 'WORLD';
var lowercaseStr = str.toLowerCase();
console.log(lowercaseStr); // Output: "world"
-
- Get the length of a string:
var str = 'Hello, world!';
var length = str.length;
console.log(length); // Output: 13
-
- Replace all occurrences of a substring in a string:
var str = 'Hello, world!';
var replacedStr = str.replace('world', 'there');
console.log(replacedStr); // Output: "Hello, there!"
-
- Remove leading and trailing whitespace from a string:
var str = ' Hello, world! ';
var trimmedStr = str.trim();
console.log(trimmedStr); // Output: "Hello, world!"
-
- Check if a number is an integer:
var number = 42;
var isInteger = Number.isInteger(number);
console.log(isInteger); // Output: true
-
- Check if a number is finite (not NaN or Infinity):
var number = 42;
var isFiniteNumber = isFinite(number);
console.log(isFiniteNumber); // Output: true
-
- Check if a number is NaN (Not-a-Number):
var number = NaN;
var isNaNNumber = isNaN(number);
console.log(isNaNNumber); // Output: true
-
- Generate a random integer between a specified range (inclusive):
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomInt(1, 10)); // Output: Random number between 1 and 10
-
- Get the absolute value of a number:
var number = -42;
var absoluteValue = Math.abs(number);
console.log(absoluteValue); // Output: 42
-
- Round a number to the nearest integer:
var number = 3.7;
var roundedNumber = Math.round(number);
console.log(roundedNumber); // Output: 4
-
- Generate a random hexadecimal color:
function getRandomHexColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
console.log(getRandomHexColor()); // Output: Random hexadecimal color
-
- Get the current URL:
var currentURL = window.location.href;
console.log(currentURL); // Output: Current URL
-
- Redirect to a different URL:
window.location.href = 'https://www.example.com';
-
- Delay execution of code by a specified time (in milliseconds):
function delay(milliseconds) {
return new Promise(function(resolve) {
setTimeout(resolve, milliseconds);
});
}
delay(2000).then(function() {
console.log('Delayed code execution');
});
-
- Create a new object with specified properties and values:
var obj = {
name: 'John',
age: 30
};
console.log(obj); // Output: { name: 'John', age: 30 }
-
- Access the value of a property in an object:
var obj = {
name: 'John',
age: 30
};
console.log(obj.name); // Output: "John"
-
- Set the value of a property in an object:
var obj = {
name: 'John',
age: 30
};
obj.name = 'Jane';
console.log(obj.name); // Output: "Jane"
-
- Check if an object has a specific property:
var obj = {
name: 'John',
age: 30
};
var hasProperty = 'name' in obj;
console.log(hasProperty); // Output: true
-
- Delete a property from an object:
var obj = {
name: 'John',
age: 30
};
delete obj.age;
console.log(obj); // Output: { name: 'John' }
-
- Clone an object:
var obj1 = { name: 'John' };
var obj2 = { ...obj1 };
console.log(obj2); // Output: { name: 'John' }
-
- Merge two objects into a new object:
var obj1 = { name: 'John' };
var obj2 = { age: 30 };
var mergedObj = { ...obj1, ...obj2 };
console.log(mergedObj); // Output: { name: 'John', age: 30 }
-
- Create a new class (constructor function) in JavaScript:
function Person(name, age) {
this.name = name;
this.age = age;
}
var person = new Person('John', 30);
console.log(person.name); // Output: "John"
console.log(person.age); // Output: 30
-
- Add a method to a class (constructor function):
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log('Hello, my name is ' + this.name);
};
}
var person = new Person('John', 30);
person.greet(); // Output: "Hello, my name is John"
-
- Inherit properties and methods from a parent class:
function Animal(name) {
this.name = name;
}
Animal.prototype.greet = function() {
console.log('Hello, my name is ' + this.name);
};
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
var dog = new Dog('Buddy', 'Labrador');
dog.greet(); // Output: "Hello, my name is Buddy"
-
- Use a try...catch block to handle exceptions:
try {
// Code that might throw an exception
throw new Error('Something went wrong');
} catch (error) {
console.log(error.message);
}
-
- Execute a function repeatedly at a specified interval (milliseconds):
function repeat(func, interval) {
setInterval(func, interval);
}
function greet() {
console.log('Hello');
}
repeat(greet, 1000); // Output: "Hello" every second
-
- Convert an object to JSON string:
var obj = { name: 'John', age: 30 };
var jsonString = JSON.stringify(obj);
console.log(jsonString); // Output: "{"name":"John","age":30}"
-
- Convert a JSON string to an object:
var jsonString = '{"name":"John","age":30}';
var obj = JSON.parse(jsonString);
console.log(obj.name); // Output: "John"
console.log(obj.age); // Output: 30
-
- Check if a variable is defined (not undefined):
var variable;
var isDefined = typeof variable !== 'undefined';
console.log(isDefined); // Output: false
-
- Check if a variable has a value (not null or undefined):
var variable = null;
var hasValue = variable !== null && typeof variable !== 'undefined';
console.log(hasValue); // Output: false
-
- Check if a variable is a number:
var variable = 42;
var isNumber = typeof variable === 'number';
console.log(isNumber); // Output: true
-
- Check if a variable is a string:
var variable = 'Hello';
var isString = typeof variable === 'string';
console.log(isString); // Output: true
-
- Check if a variable is a boolean:
var variable = true;
var isBoolean = typeof variable === 'boolean';
console.log(isBoolean); // Output: true
-
- Check if a variable is an object:
var variable = { name: 'John' };
var isObject = typeof variable === 'object' && variable !== null;
console.log(isObject); // Output: true
-
- Check if a variable is a function:
var variable = function() {};
var isFunction = typeof variable === 'function';
console.log(isFunction); // Output: true
-
- Check if a variable is an array:
var variable = [1, 2, 3];
var isArray = Array.isArray(variable);
console.log(isArray); // Output: true
-
- Check if a variable is a date:
var variable = new Date();
var isDate = variable instanceof Date;
console.log(isDate); // Output: true
-
- Check if a variable is NaN (Not-a-Number):
var variable = NaN;
var isNaNNumber = Number.isNaN(variable);
console.log(isNaNNumber); // Output: true
-
- Check if a variable is a finite number (not NaN or Infinity):
var variable = 42;
var isFiniteNumber = Number.isFinite(variable);
console.log(isFiniteNumber); // Output: true
-
- Get the current timestamp (milliseconds since January 1, 1970):
var timestamp = Date.now();
console.log(timestamp); // Output: Current timestamp
-
- Format a number with commas as thousands separators:
var number = 1000000;
var formattedNumber = number.toLocaleString();
console.log(formattedNumber); // Output: "1,000,000"
-
- Get the current screen width and height:
var screenWidth = window.innerWidth;
var screenHeight = window.innerHeight;
console.log(screenWidth); // Output: Current screen width
console.log(screenHeight); // Output: Current screen height
-
- Detect the user's browser name and version:
var browserName = navigator.userAgent;
var browserVersion = navigator.appVersion;
console.log(browserName); // Output: User's browser name
console.log(browserVersion); // Output: User's browser version
-
- Detect the user's operating system:
var operatingSystem = navigator.platform;
console.log(operatingSystem); // Output: User's operating system
-
- Detect if the user is using a mobile device:
var isMobile = /Mobi|Android/i.test(navigator.userAgent);
console.log(isMobile); // Output: true or false
-
- Encode a URL component:
var url = 'https://www.example.com/?name=John Doe';
var encodedURL = encodeURIComponent(url);
console.log(encodedURL); // Output: "https%3A%2F%2Fwww.example.com%2F%3Fname%3DJohn%20Doe"
-
- Decode a URL component:
var encodedURL = 'https%3A%2F%2Fwww.example.com%2F%3Fname%3DJohn%20Doe';
var decodedURL = decodeURIComponent(encodedURL);
console.log(decodedURL); // Output: "https://www.example.com/?name=John Doe"
-
- Get the value of a query parameter from the URL:
var url = 'https://www.example.com/?name=John&age=30';
var searchParams = new URLSearchParams(new URL(url).search);
var name = searchParams.get('name');
console.log(name); // Output: "John"
-
- Get the current page scroll position:
var scrollX = window.pageXOffset;
var scrollY = window.pageYOffset;
console.log(scrollX); // Output: Current horizontal scroll position
console.log(scrollY); // Output: Current vertical scroll position
-
- Scroll to a specific position on the page:
window.scrollTo({
top: 0,
behavior: 'smooth'
});
-
- Detect if the user has scrolled to the bottom of the page:
window.addEventListener('scroll', function() {
if (window.innerHeight + window.pageYOffset >= document.body.offsetHeight) {
console.log('Reached the bottom of the page');
}
});
-
- Detect if the user has pressed a specific keyboard key:
window.addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
console.log('Enter key pressed');
}
});
-
- Detect if the user has clicked on an element:
var element = document.getElementById('myButton');
element.addEventListener('click', function() {
console.log('Button clicked');
});
-
- Add a CSS class to an element:
var element = document.getElementById('myElement');
element.classList.add('myClass');
-
- Remove a CSS class from an element:
var element = document.getElementById('myElement');
element.classList.remove('myClass');
-
- Toggle a CSS class on an element:
var element = document.getElementById('myElement');
element.classList.toggle('myClass');
-
- Create a new HTML element dynamically:
var newElement = document.createElement('div');
newElement.textContent = 'Hello, world!';
document.body.appendChild(newElement);
-
- Remove an HTML element from the document:
var element = document.getElementById('myElement');
element.remove();
-
- Execute a function when the DOM content has finished loading:
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM content loaded');
});
Thank you for reading. Follow me on twitter