Home >Web Front-end >JS Tutorial >avaScript One-Liners That Will Make You Look Like a Pro
Today we will be talking about some JavaScript cool tricks. These aren't just random code hacks – they're real solutions that can seriously clean up your programming.
Remember those old-school JavaScript days when we'd write out every single property?
const name = 'Sarah'; const age = 28; const user = { name: name, age: age };
Here's a better way to do it:
const user = { name, age };
Gone are those clunky lines where you'd repeat yourself.
Need to swap two variables? Use this:
[a, b] = [b, a];
The first time you see this, you'll do a double-take. Array destructuring turns variable swapping into something that looks almost too good to be true. No temp variables, no complex logic – just pure, elegant code.
Remember writing those lengthy default value checks?
const userPreference = input !== null && input !== undefined ? input : 'default';
Here's how the cool kids do it now:
const userPreference = input ?? 'default';
This little ?? operator has saved me from so many headaches. It only falls back to the default when the value is null or undefined – not when it's 0 or an empty string.
If you want to make your array unique, do this:
const unique = [...new Set(array)];
If it was before we'd use loop but now I just smile and spread that Set anytime I need it.
Instead of writing value === true or Boolean(value).
Here's a sure better way:
const isTrue = !!value;
Those double exclamation marks might look like you're really excited about something, but they're actually doing some clever type coercion.
If you want to convert a string to a number? Forget parseInt() for a second, use this instead:
const number = +'42';
That lonely plus sign is doing all the heavy lifting here and it accurately converts a string number to a number.
Don't do this again:
const userCity = user && user.address && user.address.city;
A much more better way:
const userCity = user?.address?.city;
This one feels like JavaScript finally understood our pain and decided to do something about it.
Coding shortcuts represent more than just fewer keystrokes.
They're about writing smarter, more intentional software. These techniques separate average developers from great coders. Use them wisely, sparingly, and with purpose.
Great code tells a story. It should be clear, powerful, and elegant. Don't just chase brevity – chase understanding.
That's all, now tell me what's your favorite JavaScript trick?
Share it with me even though you knew it before you read this article.
The above is the detailed content of avaScript One-Liners That Will Make You Look Like a Pro. For more information, please follow other related articles on the PHP Chinese website!