Skip to content

Instantly share code, notes, and snippets.

@harendra21
Last active July 7, 2023 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harendra21/6b9cf087317566db40622c84f70a89ba to your computer and use it in GitHub Desktop.
Save harendra21/6b9cf087317566db40622c84f70a89ba to your computer and use it in GitHub Desktop.
    1. 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
    1. 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
    1. 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
    1. Convert a string to an integer:
var number = parseInt('42');

console.log(number); // Output: 42
    1. Convert a string to a floating-point number:
var number = parseFloat('3.14');

console.log(number); // Output: 3.14
    1. Round a number to a specified decimal place:
var roundedNumber = 3.14159.toFixed(2);

console.log(roundedNumber); // Output: 3.14
    1. 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
    1. Get the current date:
var currentDate = new Date();

console.log(currentDate); // Output: Current date and time
    1. Get the current year:
var currentYear = new Date().getFullYear();

console.log(currentYear); // Output: Current year
    1. Get the current month:
var currentMonth = new Date().getMonth() + 1; // Month is zero-based

console.log(currentMonth); // Output: Current month (1-12)
    1. Get the current day:
var currentDay = new Date().getDate();

console.log(currentDay); // Output: Current day (1-31)
    1. Get the current time:
var currentTime = new Date().toLocaleTimeString();

console.log(currentTime); // Output: Current time
    1. Get the length of an array:
var arr = [1, 2, 3];
var length = arr.length;

console.log(length); // Output: 3
    1. Check if an array contains a specific element:
var arr = [1, 2, 3];
var containsElement = arr.includes(2);

console.log(containsElement); // Output: true
    1. 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]
    1. Remove the last element from an array:
var arr = [1, 2, 3];
arr.pop();

console.log(arr); // Output: [1, 2]
    1. 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]
    1. Remove the first element from an array:
var arr = [1, 2, 3];
arr.shift();

console.log(arr); // Output: [2, 3]
    1. Concatenate two arrays:
var arr1 = [1, 2];
var arr2 = [3, 4];
var concatenatedArray = arr1.concat(arr2);

console.log(concatenatedArray); // Output: [1, 2, 3, 4]
    1. Reverse the elements of an array:
var arr = [1, 2, 3];
arr.reverse();

console.log(arr); // Output: [3, 2, 1]
    1. Sort the elements of an array in ascending order:
var arr = [3, 1, 2];
arr.sort();

console.log(arr); // Output: [1, 2, 3]
    1. 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]
    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
    1. Remove an element from an array by index:
var arr = [1, 2, 3];
arr.splice(1, 1);

console.log(arr); // Output: [1, 3]
    1. Copy an array:
var arr1 = [1, 2, 3];
var arr2 = arr1.slice();

console.log(arr2); // Output: [1, 2, 3]
    1. 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]);
}
    1. Iterate over an array using forEach:
var arr = [1, 2, 3];
arr.forEach(function(element) {
  console.log(element);
});
    1. 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]);
}
    1. Iterate over the values of an array using for...of loop:
var arr = [1, 2, 3];
for (var value of arr) {
  console.log(value);
}
    1. 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]
    1. 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]
    1. 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
    1. 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
    1. 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
    1. Find the maximum value in an array:
var arr = [3, 1, 2];
var max = Math.max(...arr);

console.log(max); // Output: 3
    1. Find the minimum value in an array:
var arr = [3, 1, 2];
var min = Math.min(...arr);

console.log(min); // Output: 1
    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"
    1. Check if a string contains a substring:
var str = 'Hello, world!';
var containsSubstring = str.includes('world');

console.log(containsSubstring); // Output: true
    1. Check if a string starts with a specific prefix:
var str = 'Hello, world!';
var startsWithHello = str.startsWith('Hello');

console.log(startsWithHello); // Output: true
    1. Check if a string ends with a specific suffix:
var str = 'Hello, world!';
var endsWithWorld = str.endsWith('world!');

console.log(endsWithWorld); // Output: true
    1. Convert a string to uppercase:
var str = 'hello';
var uppercaseStr = str.toUpperCase();

console.log(uppercaseStr); // Output: "HELLO"
    1. Convert a string to lowercase:
var str = 'WORLD';
var lowercaseStr = str.toLowerCase();

console.log(lowercaseStr); // Output: "world"
    1. Get the length of a string:
var str = 'Hello, world!';
var length = str.length;

console.log(length); // Output: 13
    1. 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!"
    1. Remove leading and trailing whitespace from a string:
var str = '   Hello, world!   ';
var trimmedStr = str.trim();

console.log(trimmedStr); // Output: "Hello, world!"
    1. Check if a number is an integer:
var number = 42;
var isInteger = Number.isInteger(number);

console.log(isInteger); // Output: true
    1. Check if a number is finite (not NaN or Infinity):
var number = 42;
var isFiniteNumber = isFinite(number);

console.log(isFiniteNumber); // Output: true
    1. Check if a number is NaN (Not-a-Number):
var number = NaN;
var isNaNNumber = isNaN(number);

console.log(isNaNNumber); // Output: true
    1. 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
    1. Get the absolute value of a number:
var number = -42;
var absoluteValue = Math.abs(number);

console.log(absoluteValue); // Output: 42
    1. Round a number to the nearest integer:
var number = 3.7;
var roundedNumber = Math.round(number);

console.log(roundedNumber); // Output: 4
    1. 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
    1. Get the current URL:
var currentURL = window.location.href;

console.log(currentURL); // Output: Current URL
    1. Redirect to a different URL:
window.location.href = 'https://www.example.com';
    1. 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');
});
    1. Create a new object with specified properties and values:
var obj = {
  name: 'John',
  age: 30
};

console.log(obj); // Output: { name: 'John', age: 30 }
    1. Access the value of a property in an object:
var obj = {
  name: 'John',
  age: 30
};

console.log(obj.name); // Output: "John"
    1. Set the value of a property in an object:
var obj = {
  name: 'John',
  age: 30
};

obj.name = 'Jane';

console.log(obj.name); // Output: "Jane"
    1. Check if an object has a specific property:
var obj = {
  name: 'John',
  age: 30
};

var hasProperty = 'name' in obj;

console.log(hasProperty); // Output: true
    1. Delete a property from an object:
var obj = {
  name: 'John',
  age: 30
};

delete obj.age;

console.log(obj); // Output: { name: 'John' }
    1. Clone an object:
var obj1 = { name: 'John' };
var obj2 = { ...obj1 };

console.log(obj2); // Output: { name: 'John' }
    1. 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 }
    1. 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
    1. 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"
    1. 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"
    1. 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);
}
    1. 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
    1. 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}"
    1. 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
    1. Check if a variable is defined (not undefined):
var variable;
var isDefined = typeof variable !== 'undefined';

console.log(isDefined); // Output: false
    1. 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
    1. Check if a variable is a number:
var variable = 42;
var isNumber = typeof variable === 'number';

console.log(isNumber); // Output: true
    1. Check if a variable is a string:
var variable = 'Hello';
var isString = typeof variable === 'string';

console.log(isString); // Output: true
    1. Check if a variable is a boolean:
var variable = true;
var isBoolean = typeof variable === 'boolean';

console.log(isBoolean); // Output: true
    1. Check if a variable is an object:
var variable = { name: 'John' };
var isObject = typeof variable === 'object' && variable !== null;

console.log(isObject); // Output: true
    1. Check if a variable is a function:
var variable = function() {};
var isFunction = typeof variable === 'function';

console.log(isFunction); // Output: true
    1. Check if a variable is an array:
var variable = [1, 2, 3];
var isArray = Array.isArray(variable);

console.log(isArray); // Output: true
    1. Check if a variable is a date:
var variable = new Date();
var isDate = variable instanceof Date;

console.log(isDate); // Output: true
    1. Check if a variable is NaN (Not-a-Number):
var variable = NaN;
var isNaNNumber = Number.isNaN(variable);

console.log(isNaNNumber); // Output: true
    1. 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
    1. Get the current timestamp (milliseconds since January 1, 1970):
var timestamp = Date.now();

console.log(timestamp); // Output: Current timestamp
    1. Format a number with commas as thousands separators:
var number = 1000000;
var formattedNumber = number.toLocaleString();

console.log(formattedNumber); // Output: "1,000,000"
    1. 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
    1. 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
    1. Detect the user's operating system:
var operatingSystem = navigator.platform;

console.log(operatingSystem); // Output: User's operating system
    1. Detect if the user is using a mobile device:
var isMobile = /Mobi|Android/i.test(navigator.userAgent);

console.log(isMobile); // Output: true or false
    1. 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"
    1. 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"
    1. 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"
    1. 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
    1. Scroll to a specific position on the page:
window.scrollTo({
  top: 0,
  behavior: 'smooth'
});
    1. 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');
  }
});
    1. Detect if the user has pressed a specific keyboard key:
window.addEventListener('keydown', function(event) {
  if (event.key === 'Enter') {
    console.log('Enter key pressed');
  }
});
    1. Detect if the user has clicked on an element:
var element = document.getElementById('myButton');
element.addEventListener('click', function() {
  console.log('Button clicked');
});
    1. Add a CSS class to an element:
var element = document.getElementById('myElement');
element.classList.add('myClass');
    1. Remove a CSS class from an element:
var element = document.getElementById('myElement');
element.classList.remove('myClass');
    1. Toggle a CSS class on an element:
var element = document.getElementById('myElement');
element.classList.toggle('myClass');
    1. Create a new HTML element dynamically:
var newElement = document.createElement('div');
newElement.textContent = 'Hello, world!';
document.body.appendChild(newElement);
    1. Remove an HTML element from the document:
var element = document.getElementById('myElement');
element.remove();
    1. 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment