Member-only story

10 Practical JavaScript Tips

aifou
2 min readFeb 2, 2024

--

1. Convert the arguments object to an array.

The arguments object is an array-like object accessible within a function, containing the values of the parameters passed to that function. However, it lacks the array methods. Fortunately, you can convert it to a regular array:

var argArray = Array.prototype.slice.call(arguments);

2. Sum all values in an array.

Instead of using a loop, you can use the reduce method:

var numbers = [3, 5, 7, 2];
var sum = numbers.reduce((x, y) => x + y);
console.log(sum); // returns 17

3. Conditional short-circuiting.

Instead of writing an explicit if statement:

if (hungry) {
goToFridge();
}

You can make it shorter using the && operator:

hungry && goToFridge();

4. Use logical OR with conditions.

Avoid declaring unnecessary variables to prevent getting undefined:

function doSomething(arg1){ 
arg1 = arg1 || 32; // Set arg1 to 32 if not already set
}

5. Comma operator.

The comma operator evaluates each operand from left to right and returns the value of the last operand:

let x = 1;
x = (x++, x);
console.log(x); // expected output: 2
x = (2, 3);
console.log(x); // expected output: 3

6. Resize an array using length.

Adjust the size or empty an array:

var array = [11, 12, 13, 14, 15];  
console.log(array.length); // 5
array.length = 3;
console.log(array.length); // 3
console.log(array); // [11, 12, 13]
array.length = 0;
console.log(array.length); // 0
console.log(array); // []

7. Swap values using array destructuring.

Swap values without using a temporary variable:

let a = 1, b = 2;
[a, b] = [b, a];
console.log(a); // -> 2
console.log(b); // -> 1

8. Shuffle elements in an array.

Randomly shuffle array elements:

var list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(list.sort(function() {
return Math.random() - 0.5;
}));
//…

--

--

aifou
aifou

Responses (4)