javascript / beginner
Snippet
Optimizing Calculations with Cached Computed Values
Computed properties cache their evaluation based on reactive dependencies, preventing expensive array reductions from re-running during unrelated component re-renders.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
import { ref, computed } from 'vue';const rawScores = ref([88, 92, 79, 95, 100, 64]);// Performance benefit: computed caches results until dependencies mutateconst averageScore = computed(() => {if (rawScores.value.length === 0) return 0;const total = rawScores.value.reduce((sum, score) => sum + score, 0);return (total / rawScores.value.length).toFixed(1);});
vue
Breakdown
1
const rawScores = ref([88, 92, 79, 95, 100, 64]);
Maintains a reactive array of numeric test scores.
2
const averageScore = computed(() => {
Creates a cached computed property that recalculates only when rawScores changes.
3
const total = rawScores.value.reduce((sum, score) => sum + score, 0);
Uses the native reduce method to accumulate the sum of all score values.
4
return (total / rawScores.value.length).toFixed(1);
Divides the total by count and returns a formatted average string.