Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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 Strings
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 Strings

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, l
    3 min read
  • JavaScript Course Interaction With User
    Javascript allows us the privilege to which we can interact with the user and respond accordingly. It includes several user-interface functions which help in the interaction. Let's take a look at them one by one. JavaScript Window alert() Method : It simply creates an alert box that may or may not h
    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. Here are some inter
    5 min read
  • Dynamic User Interfaces in JavaScript
    User interfaces (UIs) have evolved from static layouts to dynamic and interactive experiences and JavaScript is a versatile and powerful programming language that plays a significant role in creating dynamic UIs that respond to user actions in real-time. Below are the methods to create a dynamic use
    2 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
  • JavaScript Code Execution
    JavaScript is a synchronous (Moves to the next line only when the execution of the current line is completed) and single-threaded (Executes one command at a time in a specific order one after another serially) language. To know behind the scene of how JavaScript code gets executed internally, we hav
    4 min read
  • Code Golfing in JavaScript
    Code Golf in JavaScript refers to attempting a problem to solve using the least amount of characters possible. Like in Golf, the low score wins, the fewest amount of characters "wins". JavaScript is a fantastic language for code golfing due to backward compatibility, quirks, it is being a high-level
    4 min read
  • Interesting Facts about JavaScript Functions
    Let us talk about some interesting facts about JavaScript Functions that can make you an efficient programmer. Functions Are First-Class CitizensJavaScript treats functions as first-class citizens, meaning they can be: Stored in variablesPassed as arguments to other functionsReturned from other func
    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
    8 min read
  • JavaScript Coding Questions and Answers
    JavaScript is the most commonly used interpreted, and scripted Programming language. It is used to make web pages, mobile applications, web servers, and other platforms. Developed in 1995 by Brendan Eich. Developers should have a solid command over this because many job roles need proficiency in Jav
    15+ min read
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