Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Ellis
Ellis

Posted on • Edited on

     

#"/t/javascript">#javascript#webdev#react#vue

This guide offers a curated collection of JavaScript tricks designed to streamline your code, enhance readability, and empower you to write more efficient programs.

We'll venture beyond the fundamentals to explore ingenious JavaScript functionalities and techniques that unlock the true power of this versatile language.

javascript-from-es2015-to-es2023 👉Download eBook

1. Effortless Boolean Conversions:

Rapidly convert any value totrue orfalse using the double negation operator (!!).

letisTruthful=!!1;// trueletisFalsey=!!0;// false
Enter fullscreen modeExit fullscreen mode

2. Default Function Parameters:

Prevent undefined errors by setting default values for function parameters.

functiongreet(name="Guest"){return`Hello,${name}!`;}
Enter fullscreen modeExit fullscreen mode

3. Concise Conditionals with Ternary Operator:

Employ the ternary operator for a compact way to writeif-else statements.

letprice=100;letmessage=price>50?"Expensive":"Cheap";
Enter fullscreen modeExit fullscreen mode

4. Dynamic Strings with Template Literals:

Utilize template literals to seamlessly integrate expressions within strings.

letitem="coffee";letcost=15;console.log(`One${item} costs $${cost}.`);
Enter fullscreen modeExit fullscreen mode

5. Destructuring Assignment for Easy Access:

Effortlessly extract properties from arrays or objects using destructuring assignment.

let[x,y]=[1,2];let{name,age}={name:"Alice",age:30};
Enter fullscreen modeExit fullscreen mode

6. The Spread Operator: Masterful Cloning:

Clone arrays or objects to create new instances without referencing the originals using the spread operator.

letoriginalArray=[1,2,3];letclonedArray=[...originalArray];
Enter fullscreen modeExit fullscreen mode

7. Streamlined Execution with Short-circuit Evaluation:

Leverage logical operators (&& and||) for conditional execution, enhancing code flow.

letisValid=true;isValid&&console.log("Valid!");
Enter fullscreen modeExit fullscreen mode

8. Optional Chaining (?.) for Safe Navigation:

Access nested object properties securely without encountering errors if a reference isnull orundefined.

letuser={name:"John",address:{city:"New York"}};console.log(user?.address?.city);// "New York"
Enter fullscreen modeExit fullscreen mode

9. Nullish Coalescing Operator (??):

Provide a default value fornull orundefined using the nullish coalescing operator (??).

letusername=null;console.log(username??"Guest");// "Guest"
Enter fullscreen modeExit fullscreen mode

10. Array Manipulation Made Simple with map, filter, and reduce:

These array methods offer elegant alternatives to traditional loops for handling arrays.

  • map: Transforms each element in an array.
  • filter: Creates a new array with elements that pass a test.
  • reduce: Combines all elements in an array into a single value.

javascript-from-es2015-to-es2023 👉Download eBook

11. Tagged Template Literals for Customized String Processing:

Craft custom string processing functions using tagged template literals.

12. Object.entries() and Object.fromEntries() for Flexible Object Manipulation:

Convert between object and key-value pair representations for simpler modification.

13. Unique Elements with Set Objects:

Utilize theSet object to store unique values of any data type.

14. Dynamic Property Names in Objects:

Employ square brackets with object literal notation to create properties with dynamic names.

15. Function Currying with bind():

Generate new functions with a predeterminedthis context using thebind() method.

16. Array-like to Array Conversion with Array.from():

Transform array-like objects into true arrays.

17. Thefor…of Loop for Iterables:

Directly iterate over iterable objects, including arrays, maps, and sets.

18. Concurrent Promises withPromise.all():

Execute multiple promises simultaneously and wait for all to resolve.

19. Capturing Arguments with the Rest Parameter:

Capture an indefinite number of arguments as an array within a function.

20. Memoization for Performance Optimization:

Store function results to prevent redundant calculations and enhance performance.

21. Swapping Variables with Bitwise XOR (^):

Perform variable swaps without a temporary variable using the bitwise XOR operator (^). This approach is more concise but may be less readable for some developers.

leta=1,b=2;a^=b;b^=a;a^=b;// a = 2, b = 1
Enter fullscreen modeExit fullscreen mode

22. Effortless Array Flattening with flat():

Simplify the process of flattening nested arrays with theflat() method. You can optionally specify a depth level for flattening.

letnestedArray=[1,[2,[3,[4]]]];letflatArray=nestedArray.flat(Infinity);
Enter fullscreen modeExit fullscreen mode

23. Quick Conversions to Numbers with Unary Plus:

Swiftly convert strings or other values to numbers using the unary plus operator (+).

letstr="123";letnum=+str;// 123 as a number
Enter fullscreen modeExit fullscreen mode

24. Template Strings for Streamlined HTML Fragments:

Generate dynamic HTML content more effectively using template literals for creating HTML fragments.

letfruits=['apple','orange','banana'];lethtml=`<ul>${fruits.map(item=>`<li>${item}</li>`).join('')}</ul>`;
Enter fullscreen modeExit fullscreen mode

25. Merging Objects with Object.assign():

Combine properties from multiple source objects into a target object usingObject.assign().

letobj1={a:1},obj2={b:2};letcombined=Object.assign({},obj1,obj2);
Enter fullscreen modeExit fullscreen mode

26. Short-circuiting for Default Values:

Utilize logical operators to assign default values when dealing with potentially undefined or null variables.

letoptions=userOptions||defaultOptions;
Enter fullscreen modeExit fullscreen mode

27. Dynamic Property Access with Bracket Notation:

Access object properties dynamically using bracket notation. This is useful when the property name is stored in a variable.

letprop="name";letvalue=person[prop];// Equivalent to person.name
Enter fullscreen modeExit fullscreen mode

28. Presence Check with Array.includes():

Determine if an array contains a specific value using theincludes() method, offering a clearer alternative toindexOf().

if(myArray.includes("value")){// Do something}
Enter fullscreen modeExit fullscreen mode

29. Function Reusability withFunction.prototype.bind():

Create more reusable and modular code by binding a function to a specific context (this value) and partially applying arguments withbind().

constgreet=function(greeting,punctuation){return`${greeting},${this.name}${punctuation}`;};constgreetJohn=greet.bind({name:'John'},'Hello');console.log(greetJohn('!'));// "Hello, John!"
Enter fullscreen modeExit fullscreen mode

30. Immutable Objects with Object.freeze():

Prevent accidental modifications to an object by making it immutable usingObject.freeze(). Note that for deeper immutability, consider libraries specifically designed for this purpose.

letobj={name:"Immutable"};Object.freeze(obj);obj.name="Mutable";// Fails silently in non-strict mode
Enter fullscreen modeExit fullscreen mode

Conclusion

This collection of JavaScript tricks empowers you to enhance your coding proficiency, write cleaner and more efficient code, and unlock the full potential of this remarkable programming language. As you explore these techniques and delve deeper into JavaScript's capabilities, you'll be well-equipped to tackle more complex programming challenges and bring your creative projects to life.

👉Download eBook
javascript-from-es2015-to-es2023

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Ellis
  • Joined

More fromEllis

Spec Coder: The Ultimate VS Code Extension for Smarter, Faster Coding
#webdev#javascript#programming#react
Two-Way Data Binding in React.js: A Comprehensive Guide
#webdev#javascript#react#reactnative
React State Management: Comparing `useState` Hook and Class `setState()`
#react#webdev#javascript#programming
DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp