JavaScript Array Destructuring and Defaults
20 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

Given the following code snippet, what will be the value of a and b after the code is executed?

let a = 111;
let b = 999;
const obj = { a: 23, b: 7, c: 14 };
({ a, b } = obj);

  • a = 23, b = 999
  • a = 23, b = 7 (correct)
  • a = 111, b = 7
  • a = 111, b = 999
  • In JavaScript, the spread operator(...) can be used for passing separated data of an ________ into a function.

    array

    Consider the following JavaScript code:

    const nested = [1, [2, 3], 4];
    const [a, [b, c], d] = nested;
    console.log(a, b, c, d);
    

    What will be the output of console.log(a, b, c, d)?

  • 1, 2, 3, 4 (correct)
  • 1, 2, undefined, 4
  • Error: Invalid destructuring assignment
  • 1, [2, 3], undefined, 4
  • The spread operator (...) can be used to create a deep copy of an object in JavaScript.

    <p>False (B)</p> Signup and view all the answers

    Describe how array destructuring can be used to swap the values of two variables a and b in JavaScript. Include a brief code example.

    <p>Array destructuring allows swapping variable values without a temporary variable. <code>[a, b] = [b, a];</code></p> Signup and view all the answers

    Given the following code:

    const HP = ['harry','hermion','ron',...['dambeldor','Snape','mackgolagan']]; const [name,...rest] = HP;

    What will console.log(rest) output?

    <p><code>['hermion', 'ron', ['dambeldor', 'Snape', 'mackgolagan']]</code> (C)</p> Signup and view all the answers

    The spread operator can be used on non-iterable objects directly without creating a new array.

    <p>False (B)</p> Signup and view all the answers

    Explain the difference between the || operator and the ?? (nullish coalescing) operator in JavaScript, particularly focusing on what values they consider 'falsy'.

    <p>The <code>||</code> operator returns the first truthy value. It considers <code>0</code>, <code>''</code>, <code>null</code>, <code>undefined</code>, <code>NaN</code>, and <code>false</code> as falsy. The <code>??</code> operator returns the first value that is not nullish (i.e., not <code>null</code> or <code>undefined</code>).</p> Signup and view all the answers

    In the context of function parameters, the ______ parameter must always be the last one defined.

    <p>rest</p> Signup and view all the answers

    Match the operator with its description:

    <p><code>...</code> (spread operator) = Expands an iterable (like an array) into individual elements. <code>...</code> (rest parameter) = Collects multiple elements into a single array. <code>||</code> = Returns the first truthy value. <code>??</code> = Returns the first non-nullish value (null or undefined).</p> Signup and view all the answers

    What is the index and value that will be logged to the console for the second element in the following code snippet?

    const arr = ['Newt', 'Tina', 'Jacob Kowalski', 'Queenie']; for(const item of arr.entries()) {console.log(item)}

    <p><code>[1, 'Tina']</code> (D)</p> Signup and view all the answers

    In enhanced object literals, the shorthand for assigning a property named seasons with the value of the variable seasons is simply _________.

    <p>seasons</p> Signup and view all the answers

    Consider the following code: const seasonNum = [1,2,3,4,5]; const seasons = { [seasonNum]: { episode: 13, realeased: {First: '20 September 2008', Last: '13 December 2008'} } }; What does seasons[seasonNum].episode evaluate to?

    <p><code>13</code> (C)</p> Signup and view all the answers

    The following code snippet will cause an error because the seasonNum array is used as a property key:

    const seasonNum =[1,2,3,4,5]; const seasons = { [seasonNum]: { episode:13, realeased:{First:'20 September 2008 ', Last:'13 December 2008'} } };

    <p>False (B)</p> Signup and view all the answers

    In the serie object, how is the getInfo method defined using ES6 syntax, and what does it log to the console?

    <p>getInfo(){ console.log(<code>it is ${this.name}.it has a ${this.type} story.the main copel are ${</code>) }</p> Signup and view all the answers

    Which of the following statements accurately describes the behavior of the nullish coalescing operator (??) in JavaScript, as demonstrated by the example serie.risoto?.(10,12) ?? console.log('the method does not exist');?

    <p>It executes <code>console.log('the method does not exist')</code> only if <code>serie.risoto</code> is <code>null</code> or <code>undefined</code>, preventing a potential error when calling a non-existent method. (B)</p> Signup and view all the answers

    Given the code:

    const openinghours = {
      sat: { open: '10 am', close: '10 pm' },
      sun: { open: '11 am', close: '9 pm' },
      mon: { open: '6 am', close: '12 pm', shift: 'harry' }
    };
    
    const values = Object.values(Object.keys(Object.values(openinghours)));
    console.log(values);
    

    The values variable will contain an array of the opening and closing times for each day.

    <p>False (B)</p> Signup and view all the answers

    Explain how the concept of optional chaining (?.) and nullish coalescing (??) operators can be combined to safely access nested object properties and provide a default value if the property is missing.

    <p>Optional chaining (<code>?.</code>) allows you to safely access properties of an object that may be <code>null</code> or <code>undefined</code> without causing an error. Nullish coalescing (<code>??</code>) then provides a default value if the result of the chained property access evaluates to <code>null</code> or <code>undefined</code>. For example: <code>obj?.prop1?.prop2 ?? 'default'</code>.</p> Signup and view all the answers

    In JavaScript, the Object.entries() method returns an array of a given object's own enumerable string-keyed property ______, in the format [key, value].

    <p>pairs</p> Signup and view all the answers

    Match the following JavaScript code snippets with their described outcomes:

    <pre><code class="language-javascript">const singers = new Set(['NF','lady gaga','NF']); console.log(singers.size); ``` = Outputs the number of unique elements in a Set ```javascript const journey=new Map(); journey.set('paris','24 journey 2020'); console.log(journey.has('paris')); ``` = Outputs true if the key exists; otherwise, false. ```javascript const obj = {a: 1, b: 2}; for (const k of Object.keys(obj)) { console.log(k); } ``` = Iterates through the keys of an object. ```javascript const singers = new Set(['NF']); const topSingers=[...singers]; console.log(topSingers); ``` = Converts a Set to an Array. </code></pre> Signup and view all the answers

    Flashcards

    Array Destructuring

    A feature to unpack values from arrays into distinct variables.

    Default Values in Destructuring

    Assign default values when the array elements are undefined.

    Swapping Variables

    Use destructuring to swap values of two variables easily.

    Returning Multiple Values

    Functions can return arrays to provide multiple values at once and destructured immediately.

    Signup and view all the flashcards

    Spread Operator

    Spread elements of an iterable like an array into individual elements.

    Signup and view all the flashcards

    Rest Parameter

    Gathers remaining arguments into an array.

    Signup and view all the flashcards

    Nullish Coalescing Operator

    Returns the right-hand operand if the left is null or undefined.

    Signup and view all the flashcards

    Logical Assignment Operators

    Combines assignment with logical operations.

    Signup and view all the flashcards

    For...of Loop

    Iterates over iterable objects like arrays.

    Signup and view all the flashcards

    Array.entries()

    Returns an iterator with key/value pairs of an array.

    Signup and view all the flashcards

    Computed Property Names

    Allows dynamic creation of object property names using expressions.

    Signup and view all the flashcards

    Enhanced Object Literals

    Simplifies the creation of objects with concise syntax.

    Signup and view all the flashcards

    Optional Chaining

    Allows safe access to deeply nested properties without errors.

    Signup and view all the flashcards

    Method Shorthand

    A concise syntax for defining methods within object literals.

    Signup and view all the flashcards

    Looping Objects

    Use for...of or for...in to iterate over object properties and values.

    Signup and view all the flashcards

    Set Data Structure

    Stores unique values without any specific order, preventing duplicates.

    Signup and view all the flashcards

    Map Data Structure

    Stores key-value pairs where both keys and values can be any type and have a specific order.

    Signup and view all the flashcards

    Object.entries()

    Creates an array of an object's own enumerable string-keyed property [key, value] pairs.

    Signup and view all the flashcards

    Study Notes

    Array Destructuring

    • ES6 feature: Allows extracting values from arrays into distinct variables.
    • Example: const arr = [1, 2, 3]; const [x, y, z] = arr;
    • Skipping elements: const [a, , c] = arr; skips the second element.
    • Default values: const [a = 10, b = 20, c = 30] = numbers; provides default values if the array is shorter.

    Default Values

    • Setting Defaults: Assign default values to array elements.
    • Example: Setting default values for elements that don't exist.

    Nested Arrays

    • Destructuring: Extracting elements from nested arrays.
    • Example: const nested = [1, [2, 3], 4]; const [a, [b, c], d] = nested;

    Destructuring Objects

    • Swapping/Mutating Data: Allows swapping variables or changing data.
    • Example: let a = 111; let b = 999; [a, b] = [b, a]; swaps the values of a and b.
    • Example: const obj = {a: 23, b: 7, c: 14 }; {a, b} = obj;
    • Mutating Objects: const obj = {a:23,b:7,c=14}; a= 25

    Returning Multiple Values

    • From a Function: Functions can return multiple values as an array.
    • Destructuring: Extract the returned values into variables.
    • Example: function getMultipleValues() { return [10, 20, 30]; }; const [a, b, c] = getMultipleValues();

    Spread Operator

    • Passing separated data: Use the spread operator (...) to pass separated array data into a function.
    • Example: const orders = ['salad', 'kebab', 'cola']; restaurantOrder(...orders);
    • Copying arrays: Creates a shallow copy of an array const otherOrder =['donat','pizza','abali'];, const copyOfOtherOrder = [...otherOrder];
    • Concatenating arrays: Combines two arrays const allOrders = [...otherOrder, ...orders];

    Object Literals

    • Enhanced Literals: Computed property names to create objects from variable values.
    • Example: const seasonNum = [1,2,3]; const seasons=[...,seasonNum[0]:{...}] to add values computed by a variable

    Optional Chaining

    • Checking for Existence: Safely access nested object properties.
    • Example: console.log(serie?.seasons?.[0]?.episode) safely checks for properties (without errors if one does not exist).
    • Example alternate: console.log(serie?.seasons?.[6]?.released?.First);

    for...of Loop

    • Iterating: Loop through the elements of an iterable.
    • Example: for(const item of arr){console.log(item)};

    for...of and entries

    • Iterating over Arrays: Looping and getting index when iterating over an array
    • Example: for(const [i, el] of arr.entries){console.log(index,el)};

    Sets

    • Unique Values: Stores only unique values.
    • No order: Elements have no specific order.

    Maps

    • Key-Value Pairs: Store key-value pairs where keys and values can be of any type.
    • Creating: Constructing maps using new Map().
    • Getting values: Getting values using .get(key)
    • Adding values: Adds values using .set(key,value)

    String Methods

    • String Iterables: Access string elements individually.
    • Useful Methods: Includes string methods like .length, .indexOf, .slice, .toLowerCase, .trim, .replaceAll, and .repeat.

    Studying That Suits You

    Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

    Quiz Team

    Related Documents

    Description

    Test your knowledge on JavaScript ES6 features such as array destructuring, setting default values, and working with nested arrays. This quiz will cover examples that demonstrate how to effectively extract values from arrays and objects. Perfect for those looking to strengthen their understanding of modern JavaScript.

    More Like This

    Array Data Structures Quiz
    5 questions
    Advanced Array Knowledge Quiz
    5 questions

    Advanced Array Knowledge Quiz

    SweepingNovaculite6226 avatar
    SweepingNovaculite6226
    JavaScript ES6 Array Destructuring
    38 questions

    JavaScript ES6 Array Destructuring

    BlamelessFeministArt5874 avatar
    BlamelessFeministArt5874
    Use Quizgecko on...
    Browser
    Browser