Consider this Svelte code snippet:
<script>
let name = 'Alice';
</script>
<input bind:value={name} />
<p>Hello {name}!</p>What happens when the user types "Bob" in the input?
<script> let name = 'Alice'; </script> <input bind:value={name} /> <p>Hello {name}!</p>
Think about what bind:value does in Svelte.
The bind:value directive creates a two-way binding between the input's value and the variable name. So as the user types, name updates immediately, and the paragraph reflects the change live.
Given this Svelte component:
<script>
let count = 0;
</script>
<button on:click={() => count += 1}>Increment</button>
<p>Count: {count}</p>What will be displayed after clicking the button two times?
<script> let count = 0; </script> <button on:click={() => count += 1}>Increment</button> <p>Count: {count}</p>
Each click increases count by 1.
Each button click runs the function that adds 1 to count. After two clicks, count is 2, so the paragraph shows 'Count: 2'.
Given a child component <Child /> with a prop value, which parent code correctly binds the parent's parentValue variable to the child's value prop for two-way binding?
Remember the Svelte syntax for binding props.
The correct syntax for two-way binding a prop is bind:propName={variable}. Option A uses this correctly.
Parent component code:
<script>
let text = 'Hello';
</script>
<Child bind:value={text} />
<p>Parent text: {text}</p>Child component code:
<script>
export let value;
</script>
<input type="text" value={value} />Why does typing in the child's input not update the parent's text?
Check how the child's input is connected to the prop.
In Svelte, to enable two-way binding, the child must bind the input's value to the prop using bind:value. Without it, changes in the input don't update the prop, so the parent variable stays unchanged.
Consider this parent component code:
<Child bind:value={42} />And the child component has:
<script>
export let value;
</script>
<input bind:value={value} />What will happen when the user types in the input?
Think about what binding means and if constants can be updated.
Binding requires a variable that can be updated. Binding to a constant like 42 is invalid and causes a runtime error because Svelte cannot assign a new value to a constant.