javascript / beginner
Snippet
Tracking Primitive and Reference Data Types with Svelte State
JavaScript distinguishes between primitive data types (like numbers, strings, and booleans) and reference types (like objects). Svelte makes reactive tracking simple by automatically updating the view when primitive or object properties are reassigned.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script>let score = 0;let user = { name: "Taylor", active: true };function updateProfile() {score += 10;user.active = score < 50;}</script><p>Player: {user.name} (Type: {typeof user.name})</p><p>Points: {score} (Type: {typeof score})</p><p>Status: {user.active ? 'Active' : 'Archived'} (Type: {typeof user.active})</p><button on:click={updateProfile}>Add Points</button>
svelte
Breakdown
1
let score = 0;
Initializes a primitive number variable for tracking scores.
2
let user = { name: "Taylor", active: true };
Initializes a reference object containing a string and a boolean property.
3
{typeof user.name}
Uses the JavaScript typeof operator to evaluate and display the string type at runtime.
4
user.active = score < 50;
Assigns the boolean result of a numerical comparison to an object property.