• Stars
    star
    183
  • Rank 209,004 (Top 5 %)
  • Language
  • Created over 4 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A collection of JavaScript tips and tricks πŸ”₯πŸš€βš‘

JAVASCRIPT TIPS & TRICKS πŸ”₯πŸš€βš‘

A collection of JavaScript tips and tricks.

No particular order or path.

I add things as I discover them.

Check Codinghub.tips, too, for JavaScript tips. It's not my project but I like it. πŸ”₯

TABLE OF CONTENTS

OPTIONAL CHAINING

"Shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing." (Source: MDN)

const person = {
  name: "Catalin Pit",
  socialMedia: {
    twitter: "@catalinmpit",
    instagram: "@catalinmpit",
    linkedin: "@catalinmpit",
  },
  experience: "Junior",
  employed: true
};

if (person && person.socialMedia && person.socialMedia.twitter) {
  console.log(person.socialMedia.twitter);
}

// The same thing with optional chaining
if (person?.socialMedia?.twitter) {
  console.log(person.socialMedia.twitter); // outputs @catalinmpit
}

// or
console.log(person?.socialMedia?.twitter);

NULLISH COALESCING OPERATOR

"The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand." (Source: MDN)

const person = {
  name: "Catalin Pit",
  socialMedia: {
    twitter: "@catalinmpit",
    instagram: "@catalinmpit",
    linkedin: "@catalinmpit",
  },
  experience: "Junior",
  employed: true
};

console.log(person.socialMedia.facebook ?? 'No Facebook account found!'); // Outputs 'No Facebook account found!'
console.log(person.socialMedia.instagram ?? 'No Instagram account found!'); // Outputs '@catalinmpit'


/// Another example ///
let name;

console.log(name ?? 'No name assigned'); // Outputs 'No name assigned'

let name = 'Catalin Pit';

console.log(name ?? 'No name assigned'); // Outputs 'Catalin Pit'

MERGE OBJECTS TOGETHER - SPREAD OPERATOR

"Shallow-cloning (excluding prototype) or merging of objects is now possible using a shorter syntax than Object.assign()." (Source: MDN)

const user = {
  name: "Catalin Pit",
  role: "Junior Fullstack Developer",
  age: 23
};

const uses = {
  machine: "MacBook Pro 15 inch",
  editor: "VS Code",
  language: "JavaScript",
  phone: "Samsung Note 10"
};

const summary = {...user, ...uses};

console.log(summary); 

// Outputs //
const summary = {
  name: "Catalin Pit",
  role: "Junior Fullstack Developer",
  age: 23,
  machine: "MacBook Pro 15 inch",
  editor: "VS Code",
  language: "JavaScript",
  phone: "Samsung Note 10"
}

TWO WAYS TO CONVERT A STRING TO A CHARACTER ARRAY

These are two quick ways to convert your string to an array of characters.

const firstName = "Catalin";

const firstNameArr1 = firstName.split('');
console.log(firstNameArr1);

const firstNameArr2 = [...firstName];
console.log(firstNameArr2);

DEFAULT PARAMETERS

"Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed." (Source: MDN)

function add(x = 1, y = 2) {
  return x + y;
}

add();       // Returns 3
add(10);    // Returns 12
add(5, 5); // Returns 10

FILTER UNIQUE VALUES / REMOVE DUPLICATE VALUES

"Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set's collection." (Source: MDN)

// Strings
const names = ['Catalin', 'Catalin', 'Pit', 'Pit', 'Tom', 'Tom', 'John', 'John'];
const uniqueNames = [...new Set(names)];

console.log(uniqueNames); // Outputs ['Catalin', 'Pit', 'Tom', 'John']


// Numbers
const examScores = [50, 75, 100, 99, 95, 67, 43, 43, 43, 100, 99, 50, 50, 50, 50];
const uniqueExamScores = [...new Set(examScores)];

console.log(uniqueExamScores); // Outputs [50, 75, 100, 99, 95, 67, 43];

FILTER OUT FALSY VALUES

Remove falsy values such as null, undefined, 0, boolean and so on, from an array.

const myArray = ["Catalin", 1, "Macbook", false, true, "Car", "Peace", 191, false];

const filteredArray = myArray.filter(Boolean);

console.log(filteredArray) // Returns ["Catalin", 1, "Macbook", true, "Car", "Peace", 191]

REQUIRED PARAMETERS

Default parameters allows us to require an argument to be passed to the function.

We can create a function which throws an error and assign it as default value for required parameters.

const required = () => {
    throw new TypeError("You did not pass the required argument!");
};

const greet = (name = required()) => console.log(`Hello ${name}!`);

greet() // Returns "Uncaught TypeError: You did not pass the required argument!"
greet("Catalin Pit") // Returns "Hello Catalin Pit!"

PASS AN EMPTY PARAMETER

With the help of the spread syntax, we can now pass an empty parameter to a function.

"Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected." (Source: MDN)

function greet(fullName, instagramHandle, twitterHandle) {
    let message = `Hello, my name is ${fullName}.`;

    if (instagramHandle) {
        message += ` My Instagram handle is ${instagramHandle}.`;
    }

    if (twitterHandle) {
        message += ` My Twitter handle is ${twitterHandle}.`;
    }

    return message;
}

// Returns "Hello, my name is Catalin Pit."
console.log(greet("Catalin Pit")); 

// Returns "Hello, my name is Catalin Pit. My Instagram handle is @cpit. My Twitter handle is @catapit." 
console.log(greet("Catalin Pit", "@cpit", "@catapit")); 

// Returns "Hello, my name is Catalin Pit. My Twitter handle is @cpit."
greet(...['Catalin Pit', , '@cpit']);

// Returns "Hello, my name is Catalin Pit. My Instagram handle is @catapit."
greet(...['Catalin Pit', '@catapit']);

ACCEPT ANY NUMBER OF ARGUMENTS IN A FUNCTION

We are making use of the spread operator again to accept any number of arguments in a function.

function accumulator(...args) {
  let acc = 0;

  for (let val of args) {
    acc += val;
  }

  return acc;
}

accumulator() // Outputs 0
accumulator(5) // Outputs 5
accumulator(1, 5) // Outputs 6
accumulator(5, 9, 3) // Outputs 17
accumulator(1, 9, 2, 8) // Outputs 20
accumulator(8, 1, 9, 2, 1000) // Outputs 1020

CHECK IF EVERY ITEM FROM AN ARRAY PASSES A TEST CONDITION

"The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value." (Source: MDN)

let closeOffice = ['false', 'true', 'false', 'true'];
let closeOffice2 = ['true', 'true', 'true', 'true'];
let closeOffice3 = ['false', 'false', 'false', 'false'];

function doYouWorkFromHome(answer) {
  return answer == 'true';
}

closeOffice.every(doYouWorkFromHome);   // Returns false - We don't close the office
closeOffice2.every(doYouWorkFromHome);  // Returns true - We close the office
closeOffice3.every(doYouWorkFromHome);  // Returns false - We don't close the office

CHECK IF SOME ITEMS FROM AN ARRAY PASS A TEST CONDITION

"The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value." (Source: MDN)

let devTeam = ['junior', 'middle', 'middle', 'junior', 'senior', 'senior'];
let devTeam1 = ['junior', 'middle', 'middle', 'junior', 'junior', 'middle'];
let devTeam2 = ['junior', 'middle', 'middle', 'junior', 'senior', 'junior'];

function proceedWithProject(answer) {
  return answer == 'senior';
}

devTeam.some(proceedWithProject);    // Returns true - We can proceed with the project
devTeam1.some(proceedWithProject);   // Returns false - We cannot proceed with the project
devTeam2.some(proceedWithProject);   // Returns true - We can proceed with the project

More Repositories

1

OSS-Contribution

Learn how to contribute to open-source projects
126
star
2

git_tips_tricks

A repo containing only Git tips and tricks. πŸ”₯πŸš€βš‘
53
star
3

nodejs-tailwind

TailwindCSS With Node.js, Express And Pug Starter
CSS
27
star
4

catalinpit

The homepage of my GitHub profile
21
star
5

learning-react

Learning React by building an application
JavaScript
11
star
6

songs-api

An API built with Node.Js and PostgreSQL
JavaScript
9
star
7

notion-nodejs-api

Track job applications with Notion API, Node.js and FastifyJS
JavaScript
8
star
8

vote-tech-courses

The voting application allows people to vote courses from tech so people can find quality courses.
Vue
6
star
9

harperdb-fastifyjs-rest-api

A REST API built with Node.js, Fastify and HarperDB.
JavaScript
6
star
10

quoteGenerator

A random quote generator built with HTML, CSS and Vanilla JavaScript
CSS
5
star
11

vue3-intro

Learn the fundamentals of Vue with Vue 3
JavaScript
4
star
12

natours

Natours Project
CSS
4
star
13

hashnode

My Hashnode Articles
4
star
14

techcourses

techcourses
JavaScript
4
star
15

catalinpit.github.io

CSS
4
star
16

trillo

Trillo project
CSS
3
star
17

GitHub-Battle

A web application that compares two GitHub profiles. Makes use of the Github API.
JavaScript
3
star
18

ffproject

JavaScript
3
star
19

WeatherApp

An Iphone application build with Preact.
JavaScript
3
star
20

nextjs-typescript-tailwindss

A boilerplate for Next.js + TypeScript + TailwindCSS
TypeScript
2
star
21

VS-Code-Shortcuts

Visual Code Shortcuts πŸš€πŸ”₯⚑
2
star
22

notes-api

An API for managing personal notes
JavaScript
2
star
23

blog-css

The custom CSS used for my blog catalins.tech
CSS
1
star
24

qmulbookingapp

A NodeJS application that allows customers to book various services.
HTML
1
star
25

coursesintech

coursesIN.tech
CSS
1
star
26

hasura-actions

A repository containing Hasura actions
JavaScript
1
star
27

nodejs-mysql

Learn how to use a MySQL database with Node.js
JavaScript
1
star
28

JavaScript-COVID19

The best JavaScript COVID-19 project so far! ⚠️
HTML
1
star
29

rapidapi-example

Bare Express/Node.js skeleton
JavaScript
1
star
30

mess-with-react

Created with CodeSandbox
HTML
1
star