Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Interesting Facts About JavaScript
Next article icon

Interesting Code Snippets in JavaScript

Last Updated : 03 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

JavaScript is a flexible and powerful programming language that can solve problems in clever and simple ways. Here are some fun JavaScript code snippets that highlight its features and quirks. Whether you're a beginner or an experienced developer, these examples will spark your interest.

1. Flattening an Array

Want to flatten a nested array quickly? JavaScript's flat() method simplifies this task. The Infinity parameter ensures all levels of nesting are flattened.

JavaScript
let a= [1,2,[3,4],[[5,7]]];
let Flat= a.flat(Infinity);
console.log(Flat);

Output
[ 1, 2, 3, 4, 5, 7 ]

In this example

  • The flat() method is used to flatten the array a.
  • The Infinity parameter ensures that all levels of nesting are flattened.
  • The result is a single-level array.

2. Swapping Variables Without a Temporary Variable

Swap the values of two variables in a single line of code using array destructuring.

JavaScript
let n1 = 5;
let n2 = 10;
[n1, n2] = [n2, n1];
console.log(n1, n2); 

Output
10 5

In this example

  • Array destructuring is used to swap the values of n1 and n2.
  • No temporary variable is needed.
  • The variables a and b exchange their values directly.

3. Shuffling an Array

The Fisher-Yates algorithm is a common way to shuffle an array, but here’s a concise version using sort() and Math.random():

JavaScript
const a = [1, 2, 3, 4, 5];
const shuffled = a.sort(() => Math.random() - 0.5);
console.log(shuffled);

Output
[ 2, 3, 1, 4, 5 ]

In this example

  • The sort() method rearranges array elements in a.
  • Math.random() generates a random number to randomize the sorting.
  • Keep in mind, this method isn't perfectly random but works well for quick tasks.

4. Quick Array Filtering Using Boolean

Filtering out falsy values (like null, undefined, 0, false, "") is easy using the Boolean constructor.

JavaScript
const a = [0, "hello", false, null, 42, "", undefined];
const falsy = a.filter(value=>!value);
const truthy=a.filter(Boolean);
console.log(falsy);
console.log(truthy);

Output
[ 0, false, null, '', undefined ]
[ 'hello', 42 ]
  • By the use of Boolean contructor only the truthy value's can be returned from an array .
  • By the use of ! operator with any type of data can lead to keeping all the falsy value's in the array in this case the ! operator first convert's all the data to it's corresponding Boolean value's implicitly and then it apply' s negation to that value.

5. Unique Values in an Array

Use the Set object to quickly filter unique values from an array.

JavaScript
const a = [1, 2, 2, 3, 4, 4, 5];
const unique = [...new Set(a)];
console.log(unique);

Output
[ 1, 2, 3, 4, 5 ]

In this example

  • The Set object automatically removes duplicate values from a.
  • The spread operator ... converts the Set back into an array.
  • The result is an array with unique elements.

6. Short-Circuit Evaluation

Simplify conditional assignments using logical operators.

JavaScript
const logged = false;
const greet = logged && 'Welcome back!';
console.log(greet);

const fallback = logged || 'Please log in';
console.log(fallback);

Output
false
Please log in

In this example

  • && returns the second value if the first is truthy, otherwise it returns the first value.
  • || returns the first truthy value it encounters.
  • These operators simplify conditional logic.

7. Generate a Random Hex Color

Create random hex colors using JavaScript.

JavaScript
const random = () => `#${Math.floor(Math.random() * 16777215).toString(16)}`;
console.log(random()); 

Output
#2a3518

In this example

  • Math.random() generates a random number.
  • Math.floor() ensures the number is an integer.
  • The number is converted to a hexadecimal string to form a color code.

8. Debounce Function

Optimize performance by limiting the rate at which a function executes using debounce.

JavaScript
const debounce = (fn, delay) => {
    let timeout;
    return (...args) => {
        clearTimeout(timeout);
        timeout = setTimeout(() => fn(...args), delay);
    };
};

const log = debounce(() => console.log('Debounced!'), 1000);
window.addEventListener('resize', log);

In this example

  • The debounce function delays the execution of fn.
  • It clears the timeout if the function is called again within the delay period.
  • This prevents rapid, repeated function calls (e.g., during window resizing).

9. Memoization

Improve function efficiency by caching results of expensive calculations.

JavaScript
const memoize = fn => {
    const cache = {};
    return (...args) => {
        const key = JSON.stringify(args);
        if (!cache[key]) {
            cache[key] = fn(...args);
        }
        return cache[key];
    };
};

const fact = memoize(n => (n <= 1 ? 1 : n * fact(n - 1)));
console.log(fact(5)); // 120
console.log(fact(6)); // 720, but calculates faster

Output
120
720

In this example

  • The memoize function stores results of previous calculations in a cache object.
  • It checks the cache before running the function to save time.
  • This is useful for functions with repeated inputs.

10. Sleep Function

Simulate a sleep function in JavaScript using Promises.

JavaScript
const sleep = ms =>
    new Promise(resolve =>
        setTimeout(resolve, ms));

async function fun() {
    console.log('Start');
    await sleep(2000);
    console.log('End after 2 seconds');
}

fun();

In this example

  • The sleep function returns a promise that resolves after a delay.
  • await pauses the execution of the async function until the promise resolves.
  • This creates a delay between code executions.

Next Article
Interesting Facts About JavaScript

P

pranjalonj7
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • javascript-basics
  • JavaScript-Methods

Similar Reads

    Interesting Facts About JavaScript Strings
    Let's see some interesting facts about JavaScript strings that can help you become an efficient programmer.Strings are ImmutableIn JavaScript, strings are immutable, which means once you create a string, you cannot change its characters individually. Any operation that appears to modify a string, li
    2 min read
    Interesting Facts About JavaScript
    JavaScript (often abbreviated as JS) is one of the most popular programming languages in the world. It is an interpreted, high-level programming language that follows ECMAScript. It powers interactive websites and is packed with amazing features that make it special and powerful. Interesting Facts A
    5 min read
    Interesting Facts About JavaScript
    JavaScript (often abbreviated as JS) is one of the most popular programming languages in the world. It is an interpreted, high-level programming language that follows ECMAScript. It powers interactive websites and is packed with amazing features that make it special and powerful. Interesting Facts A
    5 min read
    Interesting Facts About JavaScript
    JavaScript (often abbreviated as JS) is one of the most popular programming languages in the world. It is an interpreted, high-level programming language that follows ECMAScript. It powers interactive websites and is packed with amazing features that make it special and powerful. Interesting Facts A
    5 min read
    Introduction to Javascript Engines
    JavaScript is a scripting language and is not directly understood by computer but the browsers have inbuilt JavaScript engine which help them to understand and interpret JavaScript codes. These engines help to convert our JavaScript program into computer-understandable language.  A JavaScript engine
    4 min read
    Introduction to JavaScript
    JavaScript is a versatile, dynamically typed programming language used for interactive web applications, supporting both client-side and server-side development, and integrating seamlessly with HTML, CSS, and a rich standard library.JavaScript is a single-threaded language that executes one task at
    7 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences