10 consejos / trucos de Javascript que conviene saber

Escribe código más limpio con Javascript

Image for post
Image for post

Declaración de variables

function example() {
let a = 'foo';
console.log(a); // 'foo'
if (true) {
let a = 'bar';
console.log(a); // 'bar'
}
console.log(a); // 'foo'
}
function example(){
var a = 'foo';
console.log(a); // 'foo'
if (true) {
var a = 'bar';
console.log(a); // 'bar'
}
console.log(a); // 'bar'
}
function example(){
let a = 10;
let a = 20; // Error Message: Uncaught SyntaxError: Identifier ‘a’ has already been declared.
console.log(a);
}
function example(){
const a = 'foo';
a = 'bar' // Error Message : Uncaught TypeError: Assignment to constant variable.
}

Comparación de variables

Image for post
Image for post
3 == ‘3’ // true
3 === ‘3’ //false
[10] == 10   // is true
[10] === 10 // is false
'10' == 10 // is true
'10' === 10 // is false
[] == 0 // is true
[] === 0 // is false
'' == false // is true
'' === false // is false

¿Qué es considerado como false en Javascript?

¿Cómo vaciar un array?

let sampleArray = ['foo', 'bar', 'zeta'];
sampleArray.length = 0; // sampleArray becomes []

Redondear números

let n = 3.141592653;
n = n.toFixed(3); // computes n = "3.142"

Comprobar si un resultado es finito

isFinite(0/0);       // false
isFinite('foo'); // true
isFinite('10'); // true
isFinite(10); // true
isFinite(undefined); // false
isFinite(); // false
isFinite(null); // true

Switch / Case

Emplea “use strict”

(function () {
“use strict”;
a = 'foo';
// Error: Uncaught ReferenceError: a is not defined
})();

Emplear && y ||

let a = '' || 'foo'; // 'foo'let b = undefined || 'foo'; // 'foo'function doSomething () {
return { foo: 'bar' };
}
let expr = true;
let res = expr && doSomething(); // { foo: 'bar' }

Emplear el spread/rest operator

let first = ['foo', 'bar'];
let second = ['other foo', ...first, 'other bar'];
// ['other foo', 'foo', 'bar', 'other bar'
let first = { foo: 'foo' };let zeta = { ...first, bar: 'bar' }; // { foo: 'foo', bar: 'bar' }
function myFun(a, b, ...manyMoreArgs) {
console.log(a);
console.log(b);
console.log(manyMoreArgs);
}

myFun('one', 'two', 'three', 'four');
// 'one'// 'two'// ['three', 'four']

Bola Extra

¿Quieres recibir más artículos como este?

Written by

Entre paseo y paseo con Simba desarrollo en Symfony y React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store