Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mknparreira/f5744dcb9df2180b38baa04e4e1dbab3 to your computer and use it in GitHub Desktop.
Save mknparreira/f5744dcb9df2180b38baa04e4e1dbab3 to your computer and use it in GitHub Desktop.
Javascript | 10 Useful JavaScript One-Liners That You Should Know

1. Random ID Generation

const a = Math.random().toString(36).substring(2);
console.log(a)
----------------------------
72pklaoe38u

2. Generating a Random Number Within a Range

max = 20
min = 10
var a = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(a)
-------------------------
17

3. Shuffle an array

let arr = ["A", "B", "C","D","E"];
console.log(arr.slice().sort(() => Math.random() - 0.5))
------------------------------
[ 'C', 'B', 'A', 'D', 'E' ]

4. Getting a Random Boolean

const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());
---------------------------------------
false

5. Swapping Two Variables

let a = 5
let b = 7

[a,b] = [b,a];

console.log("A=",a)
console.log("B=",b)

6. Checking for Even and Odd

const isEven = num => num % 2 === 0;
console.log(isEven(2));
----------------------------------
false

7. FizzBuzz

This problem is one of the famous interview questions that is used to check the core of a programmer. In this quiz, we need to write a program that prints the numbers from 1 to 100. But for multiples of three, print “Fizz” instead of the number, and for the multiples of five, print “Buzz”.

for(i=0;++i<10;console.log(i%5?f||i:f+'Buzz'))f=i%3?'':'Fizz'
----------------------------------
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz

8. Checking whether all the elements in an array meets a certain condition

const hasEnoughSalary = (salary) => salary >= 30000const salarys = [70000, 19000, 12000, 30000, 15000, 50000]
result = salarys.every(hasEnoughSalary) 
console.log(result)
-------------------------------
falseconst salarys = [70000, 190000 ,120000, 30000, 150000,50000]
result = salarys.every(hasEnoughSalary) // Results in false
console.log(result)
---------------------------------
true

9. Merging multiple arrays

const cars = ['A', 'B'];
const trucks = ['C', 'D'];
const combined = cars.concat(trucks);
console.log(combined)

10. Clone an Array

let oldArray = [1,4,2,3]
let newArray = oldArray.slice(0);
console.log(newArray)
------------------------------------
[1,4,2,3]