Pass by Value vs Reference (JavaScript): Memory, Functions, and more!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today we're covering pass by value versus pass by reference in javascript arguably a fundamental and critical topic to understanding and programming i'll be giving you a full understanding of how this works we'll go into depth on the differences between values and references step through some examples and we'll talk about why this is so important to understand and more importantly if you stick around to the end what knowing this enables you to do in the future to understand paths by value and pass by reference i feel it's important to understand a bit about how memory works at least roughly let's think of memory as this long array of values so let's just draw this as a big rectangle and you've got billions and billions of these slots that can fit a single byte which is 8 bits why 8 bits because this is often the smallest addressable thing in memory for most computers back to the drawing okay so you've got billions of bytes and you can imagine this as basically like an array which also means that each byte has an address in other words given an address you can look up a specific byte in memory so we're all good so far when you allocate a new variable what you're really doing is reserving a space in memory somewhere to store your variable and to refer back to that bit of memory you have the address obviously different types of data require more than a single byte so when you allocate something you may reserve a whole chunk of memory and of course the address will simply be the start of it for example allocating a number in javascript well the number in javascript is a double precision float which is 8 bytes so if you want to allocate memory for a number 64 bits or in other words 8 bytes are reserved and depending on the type more or less memory may be involved if you allocate a string well in javascript every character in a string is represented by a 16 bit number or two bytes so when you allocate a string the amount of memory needed is directly related to how many characters there are in the string in other words the longer the string the more memory it uses so what does this have to do with pass by value versus pass by reference we're building that let's talk about how calling functions works you're obviously familiar with using functions in javascript it's pretty easy so let's say i have this little function up here called calculate stuff and it takes two parameters x and y and does some calculations inside and returns a result now it doesn't matter what this function does what we're going to do is look at how it actually works underneath in other words in terms of what the computer and memory is doing how does calling a function work when you do a function call there's just a few key concepts that you want to take away you may be looking at some code that's running and then you go to call a function what happens when you call it is that you package up all the arguments somewhere it could be in memory it could be in registers it doesn't matter for the purposes of this explanation then you move execution of the code to the function the function unpacks the arguments the code in the function executes and it may be that you eventually return from the function and continue from where you left off and here's where passed by value versus pass by reference matters there's two common strategies for packaging up all those arguments for the function the first is pass by value so that what can happen is that you have this little package of arguments and what you did was you copied the actual values into it in terms of memory like we saw before we go and get the actual values and put them in the package and that brings us to the second way to package up these arguments which is pass by reference meaning instead of passing the values we pass the addresses of the values that's great but what does this mean so this is a subtle but important difference and it has profound implications which we'll explore now let's do a real world example let's say i have a document i've written and someone asked for access now i could of course just make a copy that's simple enough and obviously any edits or changes they make to the document don't get reflected in the original this would be passed by value i made an independent copy and gave it to them but i also have the option of sharing the actual document itself the one i'm working on in google docs i can go hit the share button put the address of whoever i want to share this with and voila now they can access my dock now if i edit the document they see the changes and if they edit the document i also see the changes this is passed by reference i gave them access to the same document i have and now we can both access it how does this work in javascript so i know my first question would be something like how do i choose which one to use in other languages like c plus you explicitly choose depending on your needs so it's not unusual to be browsing code that mixes pass by value and reference all over the place in javascript you don't it's chosen for you they've made it simple and easy straight from mozilla's docs primitive parameters such as a number are passed to functions by value the value is passed to the function but if the function changes the value of the parameter this change is not reflected globally or in the calling function if you pass an object i.e a non-primitive value such as an array or a user-defined object as a parameter and the function changes the object's properties that change is visible outside the function let's look at some easy examples of this in action i'm going to define this function up here let's call it try to change stuff and we'll leave the inside undefined for now let's start with some primitive data types so we'll begin with let x equal five then we can call try to change stuff with x and we'll add a console.log before and after the function call and what should happen here is that if x is the same before and after then x was passed by value and if it's different before and after the function call it means that x was passed by reference because the function was able to modify it and the change was visible outside of the function so now we run it and it's exactly as we expected no change before and after and this will be the same for every primitive type so if i make x a string and i make some changes to the function we should still expect no change before and after so if we run this we get exactly that the string stays the same before and after but if we use a non-primitive type let's say that x is now an array and of course we make some small changes to the function so that it modifies the array and let's log the contents of the array before and after the function this should be passed by reference meaning the changes from inside the function should be visible outside and once we run it we see that x before and after the function the contents have changed and this of course happens with the other non-primitive types too so let's change x to a dictionary and we can define some default values in there we'll also modify the function to modify the dictionary a bit changing one of the keys finally we run this and it's clear that the contents of x before and after the function have changed confirming this was passed by reference and an interesting note is that assignment works pretty much the same way for primitive types assignment is always by value we can quickly confirm this so let's make x back into a primitive value and instead of calling a function we'll create a second variable y and initialize it to equal to x then on the next line we'll just increment it by one and i'll add some additional logging so that we can see the value of y as well and after we run it we see that x is still one but y is two and this happens with any primitive type just like it did with functions if i use a string the original string isn't modified since assignment follows the same pattern as function arguments when we create a non-primitive type like an array so let x equal an array and then we create a second variable y and set it equal to x and proceed to modify y so let's say add a couple elements or do whatever we want it doesn't matter then you log the value of x before and after and voila it's changed why understanding this thoroughly is so important there's a few reasons really the first is pretty obvious understanding your code thoroughly not just on a superficial level will help you build applications where the behavior is clear consistent and can be reasoned about easily in other words it'll help you build programs with fewer bugs secondly the concept of past by value versus past by reference is something fundamental to many programming languages learning what's happening if only roughly under the hood will help you quickly and easily understand what's happening should you switch languages finally this ties into what does this enable you to do understanding concepts like this is critical for building towards understanding more complex ideas like data structures i'd like to move on to more topics especially data structures and their use in games but you really can't understand those to a high degree without knowing basics like how memory works without at least a passing understanding of memory you can only understand something like a linked list at a superficial level at best these all require a solid basis and fundamentals otherwise you're not thoroughly understanding the subject matter anyway hope this was interesting and you learned something see you next time cheers
Info
Channel: SimonDev
Views: 15,371
Rating: 4.9864254 out of 5
Keywords: simondev, game development, programming tutorial, value vs reference, pass by value, pass by reference, pass by value vs pass by reference javascript, pass by value vs pass by reference, value vs reference javascript
Id: jxaxyvHo8ZM
Channel Id: undefined
Length: 9min 6sec (546 seconds)
Published: Mon Dec 28 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.