Menu Close
    Start a Project Request quote Reading list Switch to dark mode

    Destructuring assignment of variables

    Hi coders, we will know about a very interesting topic destructuring assignment of variables in this reading, and I hope somehow it will help you in daily coding challenge.

    The destructuring assignment of variable is a process to unpack the value from arrays, or properties from objects, into distinct variables, that looks similar to array or object literals.

    Here, we will see the examples in PHP and JavaScript syntax. If you are familiar with ES6, may very well aware of destructuring. Let’s first see the JavaScript destructuring assignment.

    Destructuring Assignment in JavaScript

    Normal variable values assignment-

    The destructuring assignment uses similar syntax, but on the left-hand side of the assignment to define what values to unpack from the sourced variable

    Without destructuring assignment, you might access the first three items in an array like this:

    Example for Destructuring assignment of Object-

    When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern as given in the above example. Be aware that a syntax error will be thrown if a trailing comma is used on the left-hand side with a rest element:

    We can also use destructuring assignment while calling a function like-

    You can also skip the starting values in the array being destructured like-

    Destructuring on empty object will assign undefined-

    Keep in mind, while destructuring assignment there must be keyword let, const or var because while destructuring, it declare variables first then assigns the values.

    Destructuring Assignment in PHP

    The Destructuring Assignment in PHP like in Javascript was introduced in PHP version 7.1.0. In PHP, the destructuring is only possible for Symmetric Array , not for Object. It is an alternative of PHP function list which now can be used with shorthand array syntax([]).

    Let’s take an example of list

    Using Destructuring Assignment-

    Destructuring in foreach loop-

    Destructuring using a function

    We can call get method of properties one by one to get a single property value but it may be somehow long methodology so here comes the Destructuring Assignment to reduce our code.

    I hope you really enjoyed this reading, Happy Codding.

    . . .


    Add Your Comment

    Be the first to comment.

    Back to Top
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again