0% found this document useful (0 votes)
108 views1 page

You Think Know Javascript

This article provides 13 useful JavaScript code snippets for everyday programming problems: 1. A one-line code to swap two variables without a temporary variable. 2. A snippet to get the byte size of any object. 3. A one-line code to reverse a string. 4. A snippet to check if all elements in an array are equal. 5. A function to randomly select an element from an array.

Uploaded by

Bleep News
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views1 page

You Think Know Javascript

This article provides 13 useful JavaScript code snippets for everyday programming problems: 1. A one-line code to swap two variables without a temporary variable. 2. A snippet to get the byte size of any object. 3. A one-line code to reverse a string. 4. A snippet to check if all elements in an array are equal. 5. A function to randomly select an element from an array.

Uploaded by

Bleep News
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

WRITE FOR US ARCHIVE ABOUT US OFFICIAL STORE

Dev Genius
Coding, Tutorials, News, UX, UI
and muchSign
moreinrelated
to yourto
account (ok__@g__.com) for your personalized experience.
development

Sign in with Google


Follow Not you? Sign in or create an account

15 This is your last free member-only story this month. Sign up for Medium and get an extra one

13 Useful JavaScript Snippets To


Code Like a Pro
Here is the JavaScript Snippets toolbox for your Everyday
Programming Problems

Haider Imtiaz Follow

Oct 7 · 4 min read

Designed by www.freepik.com

In this article, I will share 13 snippet codes for JavaScript. This is a


toolbox for the developers and you are allowed to freely use this snippet
code. So without wasting any further time let get started.

1. One-liner Swapping
Every Programmer knows swapping is done with a third variable name
temp. But in JavaScript, we can swap two values in one line without any
temp variable using the destructive method.

// Swapping

let x = 900;
let y = 1000;

[y, x] = [x, y];

console.log(x, y) // 1000 900

2. Get ByteSize
This snippet code will show you how to get the byte size of any object in
JavaScript using the built-in method.

// Get Byte Size of any Object

const ByteSize = data => new Blob([data]).size;

console.log(ByteSize("Yoo")) // 3
console.log(ByteSize(23244)) // 5

3. Pro Reversing
Now you no longer need to use loops to reverse a string, This snippet will
help you to reverse any string with one line of code. Take a look at the
below code example.

// Pro Reversing

const Reverse = str => str.split("").reverse().join("");

console.log(Reverse("Coding")) // gnidoC
console.log(Reverse("World")) // dlroW

4. Check AllEqual
This useful Snippet code will help you to check if the array elements are all
same or different. This comes in handy when you need to check an array of
duplicates elements.

const isEqual = arr => arr.every(val => val === arr[0]);

console.log(isEqual([10,10,11,11,12,13])) // false
console.log(isEqual([10,10,10,10])) // true

5. Random Selection
Sometimes we need to select the random data from an array. Let suppose
you are making a game in JavaScript and you want to add a function that
randomly selects data from the array. Then this snippet code will be a
helpful tool for you.

// Random Selection

function Random(array){
return array[Math.floor(Math.random() * array.length )];
}

let array = ["Google", "Youtube", "Twitter", "Instagram",


"Facebook"];

console.log(Random(array)); // Facebook

6. JSON Readability
Make your JSON data cleaner and easy to read by using the following
snippet code.

// JSON READABLE

const Jsontest = JSON.stringify({ name: 'Haider', age : 22, class: 12


}, null, '\t');
console.log(Jsontest)

// output
{
"name": "Haider",
"age": 22,
"class": 12
}

7. String Placeholding
You can include variables in String using this snippet code. We will do this
with the help of the ${} method. Take a look at the below code example.

// String Placeholder

let placeholder = "Front";


let placeholder2 = "Back"
console.log(`I'm a ${placeholder} End Developer`); // I'm a Front End
Developer

console.log(`I'm a ${placeholder2} End Developer`); // I'm a Back End


Developer

8. One-liner if Else Statment


You had probably used the if-else statement in JavaScript which is basically
multi-liner code. But do you know we can write an if-else statement in one
line? Check out the below code example.

// normal way

if (2 > 5){
console.log(true);
}
else{
console.log(false)
}

// One liner way

2 > 5 ? console.log(true) : console.log(false)

9. Rid of Duplicates
This snippet will help you remove the duplicates from the array. This comes
in handy when you have long elements of the array and it contains some
duplicate elements.

// Rid of Duplicates

function dup(array)
{
return [...new Set(array)];
}

console.log(dup([1, 1, 3, 3, 4, 5, 6, 7, 7, 7, 9])) // [1, 3, 4, 5,


6, 7, 9]

10. Split String into Array


This simple snippet will help you to split strings into array form. Take a look
at the below code example to know.

// split string into array

const string = "JavaScript"

const convertsion = [...string]

console.log(convertsion) // ["J", "a", "v", "a", "S", "c", "r", "i",


"p", "t"]

11. Sorting an Array


Sorting is a part of our everyday programming. You had probably used the
Loop method and algorithm to sort data. But this snippet code will show
how to sort in JavaScript with the sort() built-in method.

// Sorting

var array = ["F", "E", "D", "C", "B", "A"]

array.sort()

console.log(array) // ["A", "B", "C", "D", "E", "F"]

12. Capitalize the First letter


This snippet code will capitalize the first letter of your string. Check out the
code example below.

const capitalize = ([letter, ...rest]) => letter.toUpperCase() +


rest.join('');

console.log(capitalize("javascript")) // Javascript
console.log(capitalize("programming")) // programming

13. Get Current Time


This snippet code will get you the current time of your timezone in
JavaScript. Take a look at the code below.

// Current Time

var date = new Date(); // for now


let hour = date.getHours(); // => 9
let min= date.getMinutes(); // => 30
let sec = date.getSeconds(); // => 51

console.log(hour + ":" + min + ":" + sec) // 16:34:33

Final Thoughts
I hope you find this article helpful and enjoy reading it. Feel free to share
this article with your Programmer Friends. Happy JavaScript Coding!

You can support me by becoming a Medium member, check below. 👇

Join Medium with my referral link — Haider Imtiaz


As a Medium member, a portion of your membership fee goes to
writers you read, and you get full access to every story…
codedev101.medium.com

Never stop learning! Check out my other articles, hope you find them
interesting 😃

How to Send Gmail with Python step by step Guide


Gmail is the most widely used Personal and business email
worldwide, You had been used Gmail in your daily life for…
blog.devgenius.io

Build an Instagram Bot with Python


In this tutorial, you’ll learn how to build a bot with Python and
InstaPy, which automates your Instagram activities by…
blog.devgenius.io

How to Make a Chrome Extension


Build your first chrome extension with step by step guide
blog.devgenius.io

A Beginners Tutorial for OpenCV using Python


Getting started with OpenCV python and learn basics step by step
blog.devgenius.io

Creating Youtube Downloader in Javascript


Step by Step guide how to create youtube video downloader in
javascript.
blog.devgenius.io

Sign up for DevGenius Updates


By Dev Genius

Get the latest news and update from DevGenius publication Take a look.

Get this newsletter

JavaScript Programming Coding Software Development Nodejs

15

WRITTEN BY

Haider Imtiaz Follow

Top Writer, Programmer, UI Designer, Thinker, and Fitness and


Health expert ✌ | Love to write articles on different
Programming languages

Dev Genius Follow

Coding, Tutorials, News, UX, UI and much more related to


development

More From Medium

How to use bootstrap OnBoarding Instructions Who run the app world? Getting Started With
with Rails6 for Angular Developers React! React.js — Part 1
Chrisbradycode Jose Matos HUMAN INTERFACE Siddhant Varma in Better
TECHNOLOGIES Programming

Factories Are STILL Building an interactive Dealing with multiple Coding Serverless
Better Than Classes In Kiosk using Vue.js & Promises in JavaScript Functions in Idris
JavaScript Electron Edvinas Daugirdas in The Donald Pinckney
GreekDataGuy in JavaScript in Allen Oliver M Chun Startup
Plain English

Learn more. Make Medium yours. Write a story on Medium.


Medium is an open platform where 170 million readers come Follow the writers, publications, and topics that matter to you, If you have a story to tell, knowledge to share, or a
to find insightful and dynamic thinking. Here, expert and and you’ll see them on your homepage and in your inbox. perspective to offer — welcome home. It’s easy and free to
undiscovered voices alike dive into the heart of any topic and Explore post your thinking on any topic. Start a blog
bring new ideas to the surface. Learn more

About Write Help Legal

You might also like