Bird
Raised Fist0
Svelteframework~20 mins

Action update and destroy in Svelte - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Svelte Action Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when an action's update function changes the element's style?

Consider this Svelte action that updates the background color of an element when the parameter changes:

function highlight(node, color) {
  node.style.backgroundColor = color;
  return {
    update(newColor) {
      node.style.backgroundColor = newColor;
    },
    destroy() {
      node.style.backgroundColor = '';
    }
  };
}

If this action is used on a <div> with initial color 'yellow' and later updated to 'lightblue', what will be the background color after update?

AThe background color will be 'yellow' because update does not change it.
BThe background color will be 'yellow' until the element is destroyed.
CThe background color will be removed (empty) after update.
DThe background color will be 'lightblue' as the update function sets it.
Attempts:
2 left
💡 Hint

Think about what the update function does when called with a new parameter.

❓ lifecycle
intermediate
2:00remaining
When is the destroy function of a Svelte action called?

Given a Svelte action with a destroy method, when does Svelte call this method?

AWhen the element the action is attached to is removed from the DOM.
BEvery time the action's parameter updates.
CWhen the component using the action is first created.
DWhen the browser window is resized.
Attempts:
2 left
💡 Hint

Think about cleanup tasks and when they should happen.

📝 Syntax
advanced
2:00remaining
Which option correctly returns an action with update and destroy methods?

Choose the correct Svelte action syntax that includes both update and destroy methods.

Afunction action(node) { return { update() {}, destroy() {} } }
Bfunction action(node) { update() {}, destroy() {} }
Cfunction action(node) { return update() {}, destroy() {} }
Dfunction action(node) { return { update() {}, destroy() } }
Attempts:
2 left
💡 Hint

Remember the action must return an object with methods.

🔧 Debug
advanced
2:00remaining
Why does this Svelte action's update method not run on parameter change?

Look at this action:

function example(node, param) {
  console.log('init', param);
  return {
    update(newParam) {
      console.log('update', newParam);
    }
  };
}

When the parameter changes, the 'update' log never appears. What is the likely cause?

AThe console.log inside update is incorrect syntax.
BThe update method is missing a return statement.
CThe action was not re-applied with the new parameter, so update is not called.
DSvelte actions do not support update methods.
Attempts:
2 left
💡 Hint

Think about how Svelte knows to call update.

❓ state_output
expert
3:00remaining
What is the final text content after action update and destroy?

Consider this Svelte action and usage:

function textAction(node, text) {
  node.textContent = text;
  return {
    update(newText) {
      node.textContent = newText;
    },
    destroy() {
      node.textContent = 'Removed';
    }
  };
}

// Usage in a component:
// <div use:textAction={message}></div>

// Initial message = 'Hello'
// Then message changes to 'World'
// Then the div is removed from DOM

What is the text content of the div at each stage?

AInitially empty, then 'Hello', then 'World' after removal.
BInitially 'Hello', then 'World', then 'Removed' after removal.
CAlways 'Hello' regardless of updates or removal.
DInitially 'Hello', then 'World', then empty after removal.
Attempts:
2 left
💡 Hint

Remember what update and destroy do to the text content.

Practice

(1/5)
1. What is the main purpose of the destroy function in a Svelte action?
easy
A. To update the element's attributes when parameters change
B. To initialize the action when the element is created
C. To clean up resources when the element is removed from the DOM
D. To render the element on the page

Solution

  1. Step 1: Understand the role of destroy in Svelte actions

    The destroy function is called when the element using the action is removed from the DOM to clean up any side effects or event listeners.
  2. Step 2: Differentiate from other lifecycle functions

    update handles parameter changes, and initialization happens in the main action function, not in destroy.
  3. Final Answer:

    To clean up resources when the element is removed from the DOM -> Option C
  4. Quick Check:

    destroy cleans up on removal = A [OK]
Hint: Destroy cleans up when element leaves the page [OK]
Common Mistakes:
  • Confusing destroy with update
  • Thinking destroy initializes the action
  • Assuming destroy runs on parameter change
2. Which of the following is the correct syntax for returning an update and destroy function from a Svelte action?
easy
A. return [ update(params) {}, destroy() {} ];
B. return { update: (params) => {}, destroy: () => {} };
C. return function update(params) {}, function destroy() {};
D. return { onUpdate: () => {}, onDestroy: () => {} };

Solution

  1. Step 1: Recall the Svelte action return structure

    A Svelte action returns an object with optional update and destroy methods as properties.
  2. Step 2: Match the correct syntax

    return { update: (params) => {}, destroy: () => {} }; correctly returns an object with update and destroy as arrow functions. Other options use invalid syntax or wrong property names.
  3. Final Answer:

    return { update: (params) => {}, destroy: () => {} }; -> Option B
  4. Quick Check:

    Return object with update and destroy keys = B [OK]
Hint: Return an object with update and destroy keys [OK]
Common Mistakes:
  • Using arrays instead of objects
  • Wrong function syntax inside return
  • Using incorrect property names like onUpdate
3. Given this Svelte action code:
function highlight(node, color) {
  node.style.backgroundColor = color;
  return {
    update(newColor) {
      node.style.backgroundColor = newColor;
    },
    destroy() {
      node.style.backgroundColor = '';
    }
  };
}

What happens when the action's parameter changes from 'yellow' to 'lightblue'?
medium
A. The background color changes to 'lightblue'
B. The background color resets to empty string
C. Nothing changes because update is not called
D. The action throws an error

Solution

  1. Step 1: Understand the update function role

    The update method runs when the action's parameter changes, here it sets the background color to the new value.
  2. Step 2: Trace the parameter change effect

    Changing from 'yellow' to 'lightblue' triggers update, which sets node.style.backgroundColor to 'lightblue'.
  3. Final Answer:

    The background color changes to 'lightblue' -> Option A
  4. Quick Check:

    Parameter change triggers update = D [OK]
Hint: Update runs on parameter change to update styles [OK]
Common Mistakes:
  • Thinking destroy runs on parameter change
  • Assuming update does nothing
  • Confusing initial setup with update
4. Identify the error in this Svelte action code:
function logClicks(node) {
  function handleClick() {
    console.log('Clicked');
  }
  node.addEventListener('click', handleClick);
  return {
    update() {
      node.removeEventListener('click', handleClick);
    }
  };
}
medium
A. The update function incorrectly removes the event listener on every parameter change
B. The handleClick function is not defined properly
C. The event listener is added multiple times causing duplicates
D. The destroy function is missing to remove the event listener on element removal

Solution

  1. Step 1: Analyze the event listener management

    The action adds a click listener but does not clean it up when the element is removed.
  2. Step 2: Check lifecycle methods usage

    There is no destroy method to remove the listener on element removal, which can cause memory leaks.
  3. Final Answer:

    The destroy function is missing to remove the event listener on element removal -> Option D
  4. Quick Check:

    Missing destroy cleanup = C [OK]
Hint: Always clean event listeners in destroy [OK]
Common Mistakes:
  • Removing listeners in update instead of destroy
  • Not removing listeners at all
  • Confusing update with destroy lifecycle
5. You want to create a Svelte action that changes an element's text color based on a parameter and logs a message when the element is removed. Which code correctly implements update and destroy?
hard
A. function colorText(node, color) { node.style.color = color; return { update(newColor) { node.style.color = newColor; }, destroy() { console.log('Element removed'); } }; }
B. function colorText(node, color) { node.style.color = color; return { update() { console.log('Color updated'); }, destroy() { node.style.color = ''; } }; }
C. function colorText(node, color) { node.style.color = color; return { update(newColor) { node.style.backgroundColor = newColor; }, destroy() { console.log('Element removed'); } }; }
D. function colorText(node, color) { node.style.color = color; return { update(newColor) { node.style.color = newColor; } }; }

Solution

  1. Step 1: Check update function correctness

    The update method should take a newColor parameter and set node.style.color = newColor.
  2. Step 2: Verify destroy function behavior

    The destroy method should console.log('Element removed').
  3. Final Answer:

    function colorText(node, color) { node.style.color = color; return { update(newColor) { node.style.color = newColor; }, destroy() { console.log('Element removed'); } }; } -> Option A
  4. Quick Check:

    Update changes color, destroy logs message = A [OK]
Hint: Update changes style, destroy cleans or logs [OK]
Common Mistakes:
  • Updating wrong style property
  • Missing destroy method
  • Destroy resets style instead of logging
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard