Svelte Flashcards

1
Q

What is a component in Svelte, and how is it defined?

A

A component in Svelte is a reusable, self-contained block of code that encapsulates HTML, CSS, and JavaScript. It is defined in a .svelte file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How can you add data to a Svelte component?

A

To add data to a Svelte component, you can use a

 tag inside the component and declare variables. For example:
<script>
let name = 'Svelte';
</script>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you reference a variable in the markup of a Svelte component?

A

To reference a variable in the markup of a Svelte component, you use curly braces. For example:

<h1>Hello {name}!</h1>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Can you use JavaScript expressions inside the curly braces in Svelte markup?

A

Yes, you can use any JavaScript expression inside the curly braces. For example:

<h1>Hello {name.toUpperCase()}!</h1>

This will result in a shoutier greeting by converting the name to uppercase.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How can you use curly braces to control element attributes in a Svelte component?

A

In Svelte, you can use curly braces to control element attributes. For example:

<img src={src} />

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Why is it important to include the alt attribute for an <img></img> element in Svelte?

A

Including the alt attribute is important for accessibility (a11y) in web apps. It provides a description of the image for people using screen readers or those with slow or unreliable internet connections.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you use curly braces inside attributes in Svelte?

A

Curly braces inside attributes are used to include dynamic content. For instance:

<img src={src} alt=”A man dances.” />

You can replace the static text with dynamic content like variables declared in the

 block.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the shorthand Svelte provides for attributes when the name and value are the same?

A

Svelte provides a shorthand for attributes where the name and value are the same. For example:

<img {src} alt=”{name} dances.” />

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How can you render HTML directly into a Svelte component?

A

<p>{@html string}</p>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What caution should you take when using the {@html …} tag in Svelte?

A

When using the {@html …} tag in Svelte, it’s important to note that Svelte doesn’t perform any sanitisation of the expression inside {@html …}. If the content comes from untrusted sources, such as user-generated comments, manual escaping is crucial to prevent Cross-Site Scripting (XSS) attacks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Why is manual escaping necessary when using {@html …} in Svelte?

A

Manual escaping is necessary when using {@html …} in Svelte, especially for untrusted content like user comments. Without proper escaping, there is a risk of exposing users to Cross-Site Scripting (XSS) attacks. Svelte doesn’t automatically sanitize the content inside {@html …}.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

When might you use the {@html …} tag in a Svelte component?

A

The {@html …} tag in Svelte is useful when you need to render HTML directly into a component. It’s often used for scenarios like including HTML content from external sources or rendering dynamic HTML generated at runtime.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the core mechanism in Svelte that ensures synchronisation between the DOM and the application state?

A

Svelte relies on a powerful system of reactivity to maintain synchronisation between the DOM and the application state.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How does Svelte handle events and reactivity in the provided example involving a button?

A

In the given Svelte example, the on:click directive is used to wire up an event handler (increment) to the button’s click event. The increment function modifies the count variable, and Svelte’s reactivity system automatically updates the DOM to reflect the changes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the purpose of reactive declarations in Svelte, and how are they defined?

A

Reactive declarations in Svelte are used to compute values from other parts of a component’s state and automatically update when those parts change. They are defined using the syntax like $: doubled = count * 2;, where count is a variable being observed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

In Svelte, when does a reactive declaration run, and how does it impact the rendering process?

A

A reactive declaration in Svelte runs whenever any of the referenced values change. It runs after other script code and before the component markup is rendered. Reactive declarations help in computing values dynamically and keeping the DOM in sync with the changing state.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Why won’t array methods like push automatically trigger updates in Svelte, and what is the consequence of not handling this issue?

A

In Svelte, array methods like push won’t automatically trigger updates because Svelte’s reactivity is triggered by assignments. Failing to address this issue would result in changes to the array not reflecting in the DOM, causing the UI to be out of sync with the state.

<!-- Example of not triggering reactivity -->

<script>
let numbers = [];
  function addNumber() {
    numbers.push(numbers.length + 1);
    // Without additional assignment, this won't trigger reactivity
  }
</script>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is the idiomatic solution in Svelte to ensure reactivity when using array methods like push, and how does it work?

A

The idiomatic solution in Svelte is to use the spread operator to create a new array with the updated values. For example: numbers = […numbers, numbers.length + 1];. This ensures that reactivity is triggered, and the DOM is updated accordingly.

<!-- Idiomatic solution to ensure reactivity with array methods -->

<script>
let numbers = [];
  function addNumber() {
    numbers = [...numbers, numbers.length + 1];
    // This triggers reactivity in Svelte
  }
</script>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How can you handle reactivity when modifying arrays or objects in Svelte, and what is the simple rule of thumb to follow?

A

To handle reactivity when modifying arrays or objects in Svelte, you need to ensure that the variable name appears on the left side of the assignment. For example, instead of using obj.foo.bar = 2;, use obj = obj; after the modification to trigger reactivity.

<!-- Example of handling reactivity with object modification -->

<script>
let obj = { foo: { bar: 1 } };
  let foo = obj.foo;
  foo.bar = 2;
  obj = obj; // This triggers reactivity in Svelte
</script>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is the purpose of declaring properties (props) in Svelte components, and how are they declared?

A

In Svelte, declaring properties (props) is essential for passing data from a parent component to its children. Props are declared using the export keyword within a

 block in the child component.

<!-- Example of declaring a prop in Svelte -->

<script>
export let answer;
</script>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Why does the syntax for declaring props in Svelte, using the export keyword, differ from typical JavaScript module exports?

A

The syntax for declaring props in Svelte with the export keyword may seem unconventional compared to typical JavaScript module exports. However, this syntax is specific to Svelte and is designed to facilitate the passing of data from parent to child components.

<!-- Example of declaring a prop in Svelte -->

<script>
export let answer;
</script>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How can default values for props be specified in Svelte, and what is the purpose of providing default values?

A

In Svelte, default values for props can be specified using the export let variable = defaultValue; syntax. This allows a component to have a default value for a prop in case the prop is not explicitly provided when the component is used. Default values ensure that components work seamlessly even when certain props are omitted.

<!-- Example of specifying default values for props in Svelte -->

<script>
export let answer = 'a mystery';
</script>
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How does a component handle props that are not explicitly provided, and what is the behaviour when using default values?

A

When a component is used without explicitly providing a prop, it falls back to the default value specified for that prop. This ensures that the component can operate with sensible default values even if some props are not explicitly set by the parent component.

<!-- Example of using a component with and without explicitly providing a prop -->

<Nested answer={42}/>

<Nested></Nested>

<!-- Falls back to the default value 'a mystery' -->

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How can you pass multiple props to a Svelte component when the properties of an object correspond to the component’s expected props, and what is the benefit of using this approach?

A

In Svelte, you can use the ‘spread’ syntax ({…object}) to pass multiple props to a component when the properties of an object match the expected props of the component. This approach allows for a concise and readable way to pass all relevant properties without explicitly listing each one. It is particularly useful when the structure of the object aligns with the expected props of the component.

<!-- Example of spreading props onto a component -->

<script>
import PackageInfo from './PackageInfo.svelte';

	const pkg = {
		name: 'svelte',
		speed: 'blazing',
		version: 4,
		website: 'https://svelte.dev'
	};
</script>

<PackageInfo {…pkg} />

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What is the alternative method for referencing all the props passed into a component, including ones not declared with export, and when might this be used?
To reference all props passed into a component, including ones not declared with export, you can access $$props directly. While this approach is not generally recommended due to optimization challenges for Svelte, it can be useful in rare cases where you need to access all passed props, including those not explicitly declared in the component.
26
How can you conditionally render markup in a Svelte component, and what is the syntax for creating a conditional block?
In Svelte, you can conditionally render markup by using the {#if} block. The syntax involves wrapping the markup you want to conditionally render inside {#if condition} and {/if} tags. The content inside the block will only be rendered if the specified condition is true. {#if count > 10}

{count} is greater than 10

{/if}
27
What is the purpose of the {#if} block in Svelte, and how does it enable dynamic rendering based on a specified condition?
The {#if} block in Svelte enables dynamic rendering based on a specified condition. It allows you to conditionally include or exclude markup in the rendered output. If the condition inside the {#if} block evaluates to true, the content within the block is included; otherwise, it is excluded from the rendered output.
28
How can you dynamically generate and render a list of buttons in a Svelte component, and what block structure do you use for this purpose?
To dynamically generate and render a list of buttons in a Svelte component, you use the {#each} block. The expression inside the block is typically an array or array-like object, and it iterates over each item in the array. You can access the current item and its index within the block. What is the general structure of the {#each} block in Svelte?
{#each colors as color, i} {/each}
29
Explain the purpose of the {#each} block in Svelte and how it facilitates the creation of dynamic lists in a component.
The {#each} block in Svelte is used to iterate over items in an array or array-like object, facilitating the dynamic creation of lists in a component. It allows you to generate repeated markup for each item, with the ability to access the current item and its index. This block simplifies the process of rendering lists of data by providing a clean and concise syntax for handling iteration.
30
In Svelte, when using the {#each} block to iterate over items, why might it be important to specify a unique identifier or "key"? Provide an example and explain the purpose of using keys.
In Svelte's {#each} block, specifying a unique identifier or "key" is important to help Svelte efficiently update the DOM when items change. The key uniquely identifies each item and informs Svelte which DOM nodes correspond to specific components. Without a key, Svelte defaults to adding and removing items at the end of the block, which may lead to unintended behavior. How can you specify a key in the {#each} block, and why is it beneficial for updating components in a list? {#each things as thing (thing.id)} {/each}
31
In Svelte, how does the {#await} block handle asynchronous data, and what are the three main sections within this block? Provide an example to illustrate the syntax and usage of the {#await} block.
The {#await} block in Svelte is used to handle asynchronous data and has three main sections: {:then}, {:catch}, and the initial waiting block. The {:then} section executes when the promise resolves successfully, providing access to the resolved value. The {:catch} section executes in case of promise rejection, allowing you to handle errors. The initial block is displayed while the promise is pending. Here's an example illustrating the syntax and usage of the {#await} block: {#await promise}

...waiting

{:then number}

The number is {number}

{:catch error}

{error.message}

{/await}
32
In Svelte, how can components dispatch events, and what is the role of createEventDispatcher? Provide an example of creating and dispatching an event in a Svelte component.
Components in Svelte can dispatch events using createEventDispatcher from the 'svelte' module. This function creates an event dispatcher linked to the component instance. The dispatcher is then used to send custom events with specific data. Here's an example: In this example, createEventDispatcher is used to create the dispatch function in Inner.svelte. The component then dispatches a 'message' event with the data object { text: 'Hello!' }. In App.svelte, an on:message handler is used to listen for this event and execute the handleMessage function when it occurs.
33
How does Svelte handle the forwarding of component events in a nested component structure, and what shorthand does it provide for simplifying the process? Provide an example.
In Svelte, unlike DOM events, component events don't bubble up the component hierarchy. To listen to an event on a deeply nested component, intermediate components must forward the event. Svelte provides a shorthand for this forwarding process using the on:eventname event directive without a value, which means 'forward all events with the specified name'. Here's an example: In this example, the on:message event directive in Outer.svelte means that any 'message' events emitted by the Inner component will be automatically forwarded up the component hierarchy without the need for explicit event handlers.
34
How does Svelte allow the forwarding of DOM events in a component, and what is an example of forwarding a click event in a Svelte component?
Svelte allows the forwarding of DOM events in a component by simply using the on:eventname event directive. Here's an example of forwarding a click event in a Svelte component: In this example, the on:click event directive in BigRedButton.svelte forwards any click events that occur on the
35
In Svelte, what is the purpose of the bind:value directive, and how does it simplify the handling of data flow between a parent component and an input element?
The bind:value directive in Svelte simplifies data flow between a parent component and an input element. When applied to an input element, it establishes a two-way binding, ensuring that changes to the value of the input element automatically update the associated variable in the parent component, and vice versa. This eliminates the need for explicit event handlers and reduces boilerplate code.

Hello {name}!

36
How does the bind:value directive simplify handling the data flow with elements. When applied to a element automatically update the variable, and vice versa. However, it's important to note that until the binding is initialized, the associated variable remains undefined, so caution is needed when referencing it in the template before initialization.
37
How does the bind:value directive work in Svelte, and in what scenarios is it particularly useful?
The bind:value directive in Svelte establishes a two-way binding between a variable in the component's script and a form input element. Changes to the variable update the input value, and changes to the input value update the variable. This is particularly useful for managing the state of form elements, such as and
38
Explain the purpose of the on:change event handler when used in conjunction with the bind:value directive on a element, the on:change event handler is often added to handle changes in the selected value. The on:change event is triggered when the user makes a selection, and it allows for additional logic or side effects to be executed in response to the change. It's commonly used to update other parts of the component's state or trigger actions based on the user's selection.
39
How does the bind:value directive work with a element that has the multiple attribute, it creates a two-way binding with an array variable. Users can select multiple options from the dropdown, and the selected values are automatically stored in the bound array. This simplifies the handling of multiple selections and ensures that changes to the selected options are reflected in the array variable.
40
What is the purpose of the multiple attribute on a element in HTML allows users to select multiple options from the dropdown, rather than just a single option. In Svelte, when binding the value of a
41
What is the purpose of the onMount function in Svelte?
The onMount function in Svelte allows you to run code after a component is first rendered to the DOM, making it suitable for actions or setups needed when the component is displayed.
42
Why is it necessary to return a cleanup function from the onMount callback in this Svelte example?
Returning a cleanup function is essential to stop ongoing processes or animations initiated in the onMount callback. In this case, it cancels the animation frame to prevent it from persisting after the component is destroyed, avoiding memory leaks. onMount(() => { const canvas = document.querySelector('canvas'); const context = canvas.getContext('2d'); let frame = requestAnimationFrame(function loop(t) { frame = requestAnimationFrame(loop); paint(context, t); }); return () => { cancelAnimationFrame(frame); }; });
43
What is the purpose of the beforeUpdate and afterUpdate functions in Svelte?
The beforeUpdate function in Svelte schedules work to happen immediately before the DOM is updated, while afterUpdate is used for running code once the DOM is in sync with the component's data. They are helpful for imperatively handling tasks that are challenging to achieve in a purely state-driven way.
44
In the provided Svelte code snippet, what issue is being addressed, and how is it resolved using beforeUpdate and afterUpdate?
The issue being addressed is the inconvenience of manually scrolling the chat window in the Eliza chatbot. beforeUpdate calculates if the chat window is already scrolled to the bottom, and afterUpdate ensures automatic scrolling if needed, creating a smoother user experience. let div; let autoscroll = false; beforeUpdate(() => { if (div) { const scrollableDistance = div.scrollHeight - div.offsetHeight; autoscroll = div.scrollTop > scrollableDistance - 20; } }); afterUpdate(() => { if (autoscroll) { div.scrollTo(0, div.scrollHeight); } });
45
Why is it necessary to check for the existence of div before reading its properties in the beforeUpdate function?
beforeUpdate may run before the component has mounted, so checking for the existence of div ensures that properties are accessed only when the element is available, preventing errors.
46
What is the purpose of the 'tick' function in Svelte, and when is it typically used?
The 'tick' function in Svelte is used to ensure that any pending state changes have been applied to the DOM. It returns a promise that resolves when these changes are processed. It is typically used when you want to perform actions immediately before or after state changes to avoid unexpected behavior, especially when dealing with asynchronous tasks.
47
Explain the significance of using the tick function in the provided Svelte code snippet. What problem does it address?
In the given code snippet, the tick function is employed to address the issue of the cursor jumping to the end of a