Startec

Startec

Unleash the Power of JavaScript: Master the Best Practices and Write Top-Notch Code

Mai 26, às 15:36

·

4 min de leitura

·

0 leituras

1- Use const and let instead of var Const declares a variable whose value cannot be changed. Let has block scope instead of function scope like var. Using const and let improves readability and avoid...
Unleash the Power of JavaScript: Master the Best Practices and Write Top-Notch Code

Cover image for Unleash the Power of JavaScript: Master the Best Practices and Write Top-Notch Code

1- Use const and let instead of var

Const declares a variable whose value cannot be changed. Let has block scope instead of function scope like var. Using const and let improves readability and avoid bugs.


const myName = "Mohammad";
myName = "Ali"; // Error, can't reassign const
let myAge = 30; 
if (true) {
 let myAge = 40; // Different variable
 console.log(myAge); // 40
}
console.log(myAge); // 30

Enter fullscreen mode Exit fullscreen mode


2- Avoid global variables

Global variables can lead to namespace collisions and unintended side effects in large apps. Use local variables instead.


3- Use arrow functions

Arrow functions have a shorter syntax and lexically bind the this, arguments, super, and new. Target keywords.

// An Arrow function
const add = (a, b) => a + b;
// A function declaration
function add(a,b)=>{
 return a+b
};

Enter fullscreen mode Exit fullscreen mode


4- Use spread operator

The spread operator expands an array into its individual elements. It is a concise way to combine arrays or objects.


const fruits = ["apple", "banana", "orange"];
const moreFruits = [...fruits, "mango"]; 
console.log(moreFruits) // ["apple", "banana", "orange", "mango"]

Enter fullscreen mode Exit fullscreen mode


5- Use destructuring

Destructuring allows you to extract multiple values from arrays or properties from objects into distinct variables.


const [a, b] = [1, 2]; 
// a = 1, b = 2
const {name, age} = {name: "Omar", age: 30}; 
// name = "Omar", age = 30

Enter fullscreen mode Exit fullscreen mode


6- Use template literals

Template literals use backticks () and ${} to embed expressions in a string.

const greeting = (name) => return `Hello, my name is ${name}!`;

Enter fullscreen mode Exit fullscreen mode


7- Use default parameters

Default parameters allow named parameters to be initialized with default values if no value is passed.

const add = (a = 1, b = 2) => return a + b; 
add(10); // 12

Enter fullscreen mode Exit fullscreen mode


8- Use object property shorthand

This shorthand allows you to initialize an object with variables.

const name = "Ahmed";
const age = 30;
const person = { name, age }; 
// {name: "Ahmed", age: 30}

Enter fullscreen mode Exit fullscreen mode


9- Use promise and async/await

Promises and async/await make asynchronous code look synchronous and more readable.


10- Use JavaScript modules

Modules allow you to break up your code into separate files and reuse in other files or projects.


Continue lendo

Showmetech

Motorola Razr Plus é o novo dobrável rival do Galaxy Z Flip
Após duas tentativas da Motorola em emplacar — novamente — telefones dobráveis, eis que temos aqui a terceira, e aparentemente bem-vinda, tentativa. Estamos falando do Motorola Razr Plus, um smartphone...

Hoje, às 15:20

DEV

Mentoring for the LGBTQ+ Community
Once unpublished, all posts by chetanan will become hidden and only accessible to themselves. If chetanan is not suspended, they can still re-publish their posts from their dashboard. Note: Once...

Hoje, às 15:13

TabNews

IA: mais um arrependido / Déficit de TI / Apple: acusação grave · NewsletterOficial
Mais um pioneiro da IA se arrepende de seu trabalho: Yoshua Bengio teria priorizado segurança em vez de utilidade se soubesse o ritmo em que a tecnologia evoluiria – ele junta-se a Geoffr...

Hoje, às 14:37

Hacker News

The Analog Thing: Analog Computing for the Future
THE ANALOG THING (THAT) THE ANALOG THING (THAT) is a high-quality, low-cost, open-source, and not-for-profit cutting-edge analog computer. THAT allows modeling dynamic systems with great speed,...

Hoje, às 14:25

TabNews

[DISCUSÃO/OPINIÕES] – Outsourcing! O que, para quem, por que sim, por que não! · dougg
Quero tentar trazer nesta minha primeira publicação, uma mistura de um breve esclarecimento sobre o que são empresas de outsourcing, como elas funcionam e ganham dinheiro, mas também, ven...

Hoje, às 13:58

TabNews

Duvida: JavaScript - Desenvolver uma aplicação que vai ler um arquivo *.json · RafaelMesquita
Bom dia a todos Estou estudando javascript e me deparei com uma dificuldade e preciso de ajuda *Objetivo do estudo: *desenvolver uma aplicação que vai ler um arquivo *.json Conteudo do in...

Hoje, às 13:43

Showmetech

Automatize suas negociações com um robô de criptomoedas
Índice Como o robô de criptomoedas Bitsgap funciona?Qual a vantagem de utilizar um robô de criptomoedas?Bitsgap é confiável? O mercado de trading tem se tornado cada vez mais popular e as possibilidades de...

Hoje, às 13:13

Hacker News

Sketch of a Post-ORM
I’ve been writing a lot of database access code as of late. It’s frustrating that in 2023, my choices are still to either write all of the boilerplate by hand, or hand all database access over to some...

Hoje, às 13:11

Showmetech

14 chuveiros elétricos para o banho dos seus sonhos
Índice Chuveiro ou Ducha?Tipos de chuveiro elétrico9 fatores importantes para considerar na hora de comprar chuveiros elétricosMelhores chuveiros elétricosDuo Shower LorenzettiFit HydraAcqua Storm Ultra...

Hoje, às 11:00

DEV

Learn about the difference between var, let, and const keywords in JavaScript and when to use them.
var, let, and const: What's the Difference in JavaScript? JavaScript is a dynamic and flexible language that allows you to declare variables in different ways. You can use var, let, or const keywords to...

Hoje, às 10:21