javascript / beginner
Snippet
Inspecting Primitive Data Types and Handling Defaults with Typeof
The typeof operator in JavaScript returns a string indicating the type of the unevaluated operand. Using typeof inside control flow checks ensures that operations specific to strings (such as .trim() or .length) are only called when the data type is valid, preventing runtime type errors.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script>let userInput = '42';let inspectionResult = '';function inspectValue() {if (typeof userInput === 'string' && userInput.trim() !== '') {inspectionResult = `String with length ${userInput.length}`;} else {inspectionResult = 'Invalid or non-string value';}}</script><input bind:value={userInput} /><button on:click={inspectValue}>Inspect Type</button><p>{inspectionResult}</p>
svelte
Breakdown
1
let userInput = '42';
Initializes a component variable holding a string value.
2
if (typeof userInput === 'string' && userInput.trim() !== '') {
Guards against non-string types and empty input before processing string methods.
3
inspectionResult = `String with length ${userInput.length}`;
Constructs a template string containing properties accessible on string primitives.