Reference Vs Value In JavaScript

Поділитися
Вставка
  • Опубліковано 23 гру 2024

КОМЕНТАРІ • 374

  • @taragilesbie94
    @taragilesbie94 Рік тому +81

    Thank you! I was struggling with this concept, but now I understand it. Passing by value is like if I were to draw a picture, then make a paper copy of it and give it to you. We have two different sheets of paper, even though they look identical, so if you draw on it or cut it up, it doesn't modify mine at all. On the other hand, passing by reference is like using a Google Doc shared with a link. We both use the link to view the same single document, so if you make changes to the document, I can see them too.

    • @dharma276
      @dharma276 Рік тому +3

      That's a great analogy!

  • @Duibhshith
    @Duibhshith 3 роки тому +39

    I never realised why arrays could be const variables before. It's because the memory reference is constant and its just the value stored in the memory that changes! Thanks Kyle!

  • @warrentait4610
    @warrentait4610 4 роки тому +133

    I've been studying for 7 months and I finally understand this *crying*

    • @buddimalliyanapathirana1767
      @buddimalliyanapathirana1767 3 роки тому +8

      Now only I fully understood what this means . I'm in the 3rd year of my degree lmao

    • @BobbyBundlez
      @BobbyBundlez 2 роки тому +1

      I’m about 3 years into coding and finally understand this. Especially after fucking around with redux and usecontext and constantly messing up because I didn’t understand what immutability was or why we needed it

    • @priyankbhalani
      @priyankbhalani Рік тому

      Same goes for me today…😅

  • @nerdiloo9863
    @nerdiloo9863 5 років тому +75

    Good stuff. And this why, when you check the MDN docs for methods to perform on arrays/objects (e.g. slice, splice), they tell you whether or not a NEW object is returned. That way you can choose the appropriate method. More often than not, returning an object (and not overwriting the old) is the pattern used for non-primitives.

    • @WebDevSimplified
      @WebDevSimplified  5 років тому +16

      Very true. Pass by reference and pure functions which I covered in my last video are very closely linked together. I much prefer pure functions that return a new object almost always.

    • @BobbyBundlez
      @BobbyBundlez 2 роки тому +2

      Yes. Same goes for redux and other state management!

  • @HeatherLeigh44
    @HeatherLeigh44 3 роки тому +9

    You seriously have a gift for taking complicated concepts and explaining them so clearly.

  • @ghabrielmielli5858
    @ghabrielmielli5858 3 роки тому +50

    this content is like... SO IMPORTANT! So many bugs are caused by mistakes involving this ;-;

    • @domxon
      @domxon 3 роки тому

      @Ghabriel Mielli ua-cam.com/video/746xBN3Fs9k/v-deo.html

    • @RR-et6zp
      @RR-et6zp Рік тому

      you can learn it like in 5 sec lol. referencing vs assigning

  • @AwSomeWookie1
    @AwSomeWookie1 2 роки тому +1

    13:34
    So how i understood it is that the parameter variable array used to point at the same memory address as c when you passed it in to the add(c,3) call, they both were pointing at memory address 0x01. But then you assigned [element] which has a new memory address 0x02 to the parameter variable named array.
    Now, let c still points to memory address 0x01 and parameter variable array now points to memory address 0x02 instead of memory address 0x01 like let c did. That's why when you did console.log a second time it was still c = [1,2]

  • @ZZZZ65362
    @ZZZZ65362 5 років тому +84

    Hey, thank you for such a great and informative video. Every second of it was a pure gold for me.

    • @WebDevSimplified
      @WebDevSimplified  5 років тому +8

      You're welcome! I'm really glad you enjoyed it.

    • @josephgarza5973
      @josephgarza5973 3 роки тому

      @@WebDevSimplified Thank you very much for this helpful tutorial along with all the others that you make. They are very very helpful indeed. I have one question I hope you can help me with.
      "Why am I getting a different output entirely different to what you get?" I get this: c = ${c } / c =${c}. I checked and rechecked my code and it is exactly as you typed it. What gives?
      Thanks in advance for your kind help.

  • @SherryTheNerd
    @SherryTheNerd 2 роки тому

    This is the clearest tutorial I’ve ever watched which’s about calling by refs/value

  • @elisa_musik
    @elisa_musik Рік тому

    This video just connected several dots for me. Questions I had and questions I did not even knew I had! Thanks Kyle!

  • @23LS023
    @23LS023 2 роки тому +7

    I could not even find such words to thank you, to be honest nobody ever could explain me so easy , you are the best teacher, please keep recording, more and more videos from you, even more likes from us )) P.s. hello from Armenia )))

  • @aazamben
    @aazamben 3 роки тому

    This guy has explained things in a way that you can easily and simply understand, not like other tutorial guys who confuse you for no reason at all.
    But I want to make a point here.
    In JavaScript, every function is passed by value, not by reference. Tthe values itself changes when we put them as parameter and access those value in console.log. Try manipulating an object with two functions.
    I know this may sound confusing right now, but when ya work with it in a big project or other languages you will get this point.

  • @sanjibdey01
    @sanjibdey01 3 роки тому

    The emphasis on "overwriting the value" (in reference type), is the "aha" moment I've been missing in other blogs or tutorials.
    Thank you Kyle.

  • @atsglobalservices6136
    @atsglobalservices6136 2 роки тому

    Ive been studying javascript for 2 months, finally understood the difference. Thank you

  • @tuanchu8022
    @tuanchu8022 4 роки тому +2

    Knowing the concept of pointer will help clear the confusion between passing by value and passing by reference.

    • @Zen-lz1hc
      @Zen-lz1hc 3 роки тому

      C was my introduction to pointers a couple of years ago...

  • @stevebob240
    @stevebob240 3 роки тому +2

    Ah I was used to using pointers in C but confused as to how JS handled pass by reference. Very concise explanation.

  • @ProgrammingPolyglot-gm7zm
    @ProgrammingPolyglot-gm7zm Місяць тому

    These are the kind of things that makes computer science & programming immensely gratifying and rewarding. Thank you for the wonderful explanation on reference vs value in JavaScript. Liked and subscribed.

  • @DojoDyo
    @DojoDyo 6 місяців тому

    been studying javascript for 1 month and this made it clear for me thank you Kyle best teacher !

  • @hyfydistro
    @hyfydistro 4 роки тому +6

    This has been one of JavaScript's "Gotchas". 😀 Thank you. ❤️

  • @maxxinmaze4501
    @maxxinmaze4501 2 роки тому +1

    This is was one of your best videos, The visual explanation at the start really helped!!

  • @xilongzhang6856
    @xilongzhang6856 3 роки тому +3

    13:32 why is here the output not "c= 3"? If the array as now assigned a new value, why it does nothing...

  • @karthicodings3896
    @karthicodings3896 5 років тому +35

    Thank you, you fulfilled my request 🙏🙏

  • @tatolela1234
    @tatolela1234 3 роки тому

    THIS IS THE MOST HELPFUL VIDEO IVE SEEN ON MY ENTIRE LIFE

  • @linuslexy3161
    @linuslexy3161 3 роки тому +1

    Thank you! Finally object references are starting to become clear.

  • @xiam5941
    @xiam5941 3 роки тому +4

    i dont get the part u start explaining from 12:54... how come when you make the function array = [element] it doesnt change the second console log after you run the 3 into the functions argument?

    • @namanbhardwaj3621
      @namanbhardwaj3621 Місяць тому

      One is a var variable and another one is argument they are different

  • @ernestliu64
    @ernestliu64 4 роки тому +12

    13:04 why is c not equals to an array [3] instead of [1,2]?

    • @furreos4811
      @furreos4811 4 роки тому +23

      because as soon as he assigned the parameter (array) to [3], the array was assigned to a new address. when used, the assignment operator (=) assigns a new memory address to any variable (array, in this case). as soon as that happened, array and c were not pointing to the same address anymore so the value [3] assigned to array will only be present in that array. nothing happens to c. the address is what matters. if they're the same between two variables, both variables will affect each other's values. so if he changes the values in array, values in c change too. but as soon as he *assigned* (means that he assigned a new memory) array with a value, array loses the memory address that it shared with c.

    • @danielurizar7629
      @danielurizar7629 2 роки тому

      Actually it could never be [3] as long the function doesn't return nothing or is undefined if: let d = add(c, 3). Buuuut, if you add 'return array' to the function ... voalá console.log(d) = [3]

  • @michellesalas6175
    @michellesalas6175 2 роки тому +3

    Thank you so much for making this video. I was having a hard time trying to understand this topic but your explanation was so clear I got it all right!

  • @vonshitz
    @vonshitz 3 роки тому +5

    You're a smart kid always give great content and you have a great way of delivering!!! Thanks a lot form a student programmer struggling to learn javascript. 5 months in but we're getting there!!!

  • @santra528
    @santra528 4 роки тому +11

    Hey Kyle! Thank you very much. You have cleared my doubt about one of the most confusing topics in programming. Thank you Sir!

  • @tusharcreates
    @tusharcreates 2 роки тому

    I didn't manage to get all this because everything was happening in background. You cleared all of my doubts regarding this. I thought I'd master JavaScript concepts by my own in less time but it does take time to understand such type of concepts. I've gone through articles and videos but couldn't find any video this much explanatory. Thank you man!

  • @fluffydoggo
    @fluffydoggo 5 років тому +2

    I have never actually encountered this before in my one and a half years of coding in JavaScript. Well, you did teach me something new, so that's good. Now I can go back to my old code and fix it lol

  • @ajassharafudeen
    @ajassharafudeen 7 місяців тому

    This explanation perfectly aligns with the channel name. Thank you for helping me understand this concept.

  • @sinnvollerkommentar263
    @sinnvollerkommentar263 3 роки тому

    I would have needed this just one day earlier. Today I found it by scrolling through your videos. Thankfully a quick google helped me yesterday because I knew what to search. Thanks for your content

  • @stevieholland3579
    @stevieholland3579 2 роки тому

    Bro, I am a very visual learner and this helped tons. For some reason, this concept was really confusing me, but this made it click. I can't thank you enough.

  • @busyrand
    @busyrand 2 роки тому

    Thank you... I just learning to use const and let properly. I've always used let for everything. I understand const better now.

  • @andrew.schaeffer4032
    @andrew.schaeffer4032 2 роки тому +1

    Great explanation thank you. I don't know why so many other smart people struggle to explain this.

  • @syntaxed4365
    @syntaxed4365 4 роки тому

    This video is fantastic. I have been working with Javascript for a while and this video clearly answered my question: "Why do so many constants seem variable?" Lol, good stuff.

  • @highallthetime6138
    @highallthetime6138 3 роки тому

    thank you. I'm a junior dev and i've been using React for the past 6 months and i never really learned the bases, this really is important

  • @ThomasCasserly
    @ThomasCasserly Рік тому

    Best explanation I've found so far for this, just need to watch the bit at the end on passing variables into functions a few more times to get it clearly into my brain. Thank you so much ; - )

  • @sportcoconut354
    @sportcoconut354 2 роки тому +1

    In 12:07 why not both "c" print out to: 1,2,3 ? Since both point to adress 0x01 where new value is stored?

  • @Unknown-840
    @Unknown-840 2 роки тому

    This make a ton of sense because I learned pointers and call by value vs call by reference in C way back

  • @lesbiancake
    @lesbiancake 3 роки тому

    This was the most informative thing I could find in trying to understand pass by reference, thank you!

  • @jkk9829
    @jkk9829 4 роки тому +3

    it's easy to understand and has clarified a lot of my doubt! worth watching:)

  • @outside7
    @outside7 2 роки тому

    This is actually simplified. :) It's basically correct though. Indeed almost anything in JS is an object and therefore a rference, except for small integers. The difference is that compound values are mutable, so you can actually use them by reference. Whereas when you assign a new value to a variable, it is always copy by value - in case of objects you just copy the reference.

  • @JoshKonoff1
    @JoshKonoff1 3 роки тому +1

    Kyle, thank you for this exceptional video. Watching this was the highlight of my year so far!

  • @amoghs1342
    @amoghs1342 3 роки тому

    This is gold. Really important to get the concept right.

  • @aadilvalconi9972
    @aadilvalconi9972 Рік тому

    Although not specified, this is also a great explanation of how pointers work in C.

  • @AlexTechie
    @AlexTechie 5 років тому +6

    Great video! I always try to guess the result of some syntax before it's revealed and this one showed me that my understanding of primitive variables was wrong. I thought setting `a = 10`, then `c = a`, then adding 1 to `c`, would also result in the value of `a` being changed, because they referenced the same memory address. But, it seems it creates a new memory address when you set `c = a`. I'll add these exercises to my lab. Thanks, Kyle!

    • @WebDevSimplified
      @WebDevSimplified  5 років тому +2

      You are very welcome! This is one of the most confusing topics in programming, so I am glad this video was able to help clear up some confusion for you.

  • @threeone6012
    @threeone6012 4 роки тому

    Best programming channel on UA-cam.

  • @mollaconan
    @mollaconan 5 років тому

    Unfortunately I can only give one like. I'd like to give another like for you never say "er...", "um..." etc., which always distract me, and another for your well-organized presentation. As a self-taught web developer, I'm learning a lot from your videos. Thank you.

    • @WebDevSimplified
      @WebDevSimplified  5 років тому

      Thank you so much. I do a lot of editing and practicing to make sure all downtime is cut out of my videos and I am really glad you appreciate that effort.

  • @PildorasMusicales
    @PildorasMusicales 4 роки тому

    Very interesting!! And now I understand why the three points d = [...c] to make a new copy of an array.

  • @marsdwarf
    @marsdwarf 3 роки тому

    The best explanation I found mate. Thanks for posting! Put the address as comments helped with understanding as well.

  • @ahndeux
    @ahndeux 2 роки тому

    This is a good concept to understand. If you program in C for a memory limited device like an Arduino, you have to understand the concept well when dealing with cstrings and passing the string variable pointers into functions.

  • @alexfrancis6091
    @alexfrancis6091 3 роки тому

    Sir, I do not know if you'd read this but thank you so much......This was very informative. Thank you for that

  • @diveshkswn
    @diveshkswn 3 роки тому

    You are sooo good in explaining JS . I have been taking KT from some people and made me confuse even more.

  • @jeromelawrence9819
    @jeromelawrence9819 2 роки тому

    I should cry right now... I finally understand this weird javascript concept that has been kicking my ass..

  • @ignaciorosenberg5175
    @ignaciorosenberg5175 2 роки тому

    way easier to understand than the course that I'm doing... thx!

  • @Madmann16
    @Madmann16 2 роки тому

    You're a big help to the IT industry kyle, thank you so much

  • @aqibmalik6313
    @aqibmalik6313 Рік тому +1

    LAST BIT ABOUT WHY WE CAN EDIT CONST WAS BOOM😇😇😇

  • @earnestdavis
    @earnestdavis 2 роки тому +4

    great explanation bro! it still is helpful even after 3 years

  • @yusiff
    @yusiff 2 роки тому

    the best explanation I have ever seen. thanks, teacher.

  • @mohammedalmukhtar8949
    @mohammedalmukhtar8949 5 років тому +4

    Thanks for this useful video, Kyle! as always, your effort is appreciated.

  • @liveyourdreamsdotbe
    @liveyourdreamsdotbe 5 років тому +1

    Awesome how simple you clarify this difference
    Easy to understand and so important indeed
    Thank you so much

  • @eddievargas7680
    @eddievargas7680 2 роки тому

    As a new student to javascript....I understood half of this. The second half, homeboy forgot that this is supposed to be "simplified". Still good info to keep in mind for the future.

  • @Emilytigerkitty
    @Emilytigerkitty 3 роки тому

    Thank you so much for this. I was absolutely stuck before I watched this.

  • @cba88
    @cba88 3 роки тому

    you are the best teacher, your are gifted

  • @StrangeIndeed
    @StrangeIndeed 4 роки тому +3

    For some reason, C++'s pointers and references make a lot more sense to me c:

    • @fernandosalas4885
      @fernandosalas4885 3 роки тому

      Thats so true, Data structures in C are easier to understand than JS.

  • @YDDRGtHdDKS75Xw
    @YDDRGtHdDKS75Xw Рік тому

    배열이 아닌 변수 : 일치하는 값을 배정 당하는 형식 다른 변수에 복사 후 값을 변경하면 둘의 방해 x
    배열은 주소를 공유, 배열 복사시 함수 사용
    같은 요소를 만든 두 배열을 비교하면 다름 > 주소가 다름

  • @k_kfamily6162
    @k_kfamily6162 3 роки тому

    An explanation I will not forget for lifetime

  • @xesiusprime9360
    @xesiusprime9360 3 роки тому

    i finally understand it now!! this videos is gold thanks bro!

  • @VarshaFlimz
    @VarshaFlimz 3 роки тому

    Highly simplified and on spot explanation - the value stored is clear now

  • @MrRe-sj2iv
    @MrRe-sj2iv Рік тому

    I think you are talking about Stack memory and Heap memory.
    In the cases of primitive data types, they are located in Stack and allocated memory in stack at compile time.
    Other cases like Object, Array the Stack memory just hold the pointer link to the dynamic allocate area in heap memory (runtime)
    So your's example at 8:55 you're about to modify the object of variable d in the heap memory, but the variable c pointed to that area so the value is also reflect the new value.
    This is old but correct me if I am wrong.

  • @lukeketterer
    @lukeketterer 3 роки тому

    Couldn't get a grasp on this topic for a while and this was a great explanation!

  • @shaiebhamzadev6241
    @shaiebhamzadev6241 Рік тому

    Thank you for explaining that so I'm grateful for your expertise and your clear explanation, thank you.

  • @eddiejaoude
    @eddiejaoude 5 років тому +1

    Man, you are killing it. Great work 👍

    • @WebDevSimplified
      @WebDevSimplified  5 років тому +1

      Thanks! Loving that UA-cam grind ;P

    • @eddiejaoude
      @eddiejaoude 5 років тому

      Web Dev Simplified I can see you are enjoying it and getting lots of success. Well done 👍

  • @tan2cang93
    @tan2cang93 3 роки тому

    thank you for sharing this. now I know why we can use method array with const as array

  • @mitejmadan8672
    @mitejmadan8672 3 роки тому

    Man, your videos are so easy to understand. I can't thank you enough.

  • @eliorbuskila5794
    @eliorbuskila5794 4 роки тому +1

    That explanation is gold bro. SUBSCRIBED

  • @anonymous.youtuber
    @anonymous.youtuber 4 роки тому +2

    A really good explanation, crystal clear. You’re a great teacher Kyle ! 👍

  • @stylesg7818
    @stylesg7818 5 років тому

    Thank you. That's why I like your approach to teaching : Straight to the point.

    • @WebDevSimplified
      @WebDevSimplified  5 років тому

      Thank you. I try to keep my videos consice since I hate long winded videos that go nowhere.

  • @Divyesh_db
    @Divyesh_db 12 днів тому

    One statement clears so many Things: Anything other than premitive Values are passed By Reference.

  • @Aman-Verma
    @Aman-Verma 4 роки тому +1

    and friends that's why we used spread operator (...) to copy the elements of one array into another. now it all seems to make sense.

  • @kenluong1204
    @kenluong1204 3 роки тому

    Amazing clarity and concision on this topic but I would say that variables are passed by values in JS to simplify matters. If the value-passed is a reference to an object, then mutation of the object inside the function will carry through out our program.

  • @bulentgercek
    @bulentgercek 2 роки тому

    I would like to note an important detail about == operator. The == operator compares by converting to the primitive string, number or boolean if both sides are different. In short, one of the sides must be a primitive value. Example below.
    let c = [1, 2];
    let d = "1,2";
    console.log(`c == d ${c == d}`); // true
    Therefore, when both variables are not primitive, it does not do any converting, it directly checks whether they are the same object. The main reason for this is that Array is also considered an object. We get false return because one is c and the other is d. Even if the values in both arrays are the same.
    let c = [1, 2];
    let d = [1, 2];
    console.log(`c == d ${c == d}`); // false

  • @dandandrorivolleyball
    @dandandrorivolleyball 3 роки тому

    I may be mistaken here, but from my very short days of learning C, i think you can store and entire array in a single address in memory, rather each nunber in the array gets its own memory address, and the memory address of the array is actually the address of the first element of that array. Javascript then knows when the array ends because we defined it with a fixed amount of elements, and thats how we get an array.
    Please correct me if im wrong lol.
    *defining an array with no initial value is a bit trickier because in JS we dont have to explictly determine the length of the array at the time of initialization, and there are other mechanism at play here related to the interpreter.

  • @viniciusm.m.7822
    @viniciusm.m.7822 3 роки тому +4

    THANKS!
    Vídeo muito top, mano!
    God bless you!

  • @Jonathan_Henderson
    @Jonathan_Henderson 3 роки тому

    Excellent explanation of one the most important concepts in programming

  • @mistic.2964
    @mistic.2964 2 роки тому

    Thank you for this thorough explanation, it really helped!

  • @michaelhaag3367
    @michaelhaag3367 4 роки тому

    lucid explanation, it's a tricky concept. I have one question:
    From what you have said it seems prudent to avoid changing a datastructure (which gets passed by reference) in a function
    Example (in Python):
    list=[1,2,3]
    f(x):
    x.append(4)
    f(list)
    But how can I avoid this? Should I avoid this at all costs? How can I circumvent these problems, if I really need to pass a list as a parameter? (Well, this was not just one question, I am sorry).
    Hope someone answers!

  • @iben1195
    @iben1195 4 роки тому

    What the hell did I just learn?
    I've been so fortunate, not running into bugs and not knowing this.
    Thanks 🙏

  • @pastorfred2543
    @pastorfred2543 5 років тому +9

    Who else liked the video before watching? I learnt this way back in BSc. IT in C++ class and I've forgotten.. Thanks Sir for the refreshing..

    • @WebDevSimplified
      @WebDevSimplified  5 років тому +2

      I'm glad I could help. This is always a confusing topic no matter how long you have been programming for.

  • @ronaldbrammer1823
    @ronaldbrammer1823 Рік тому

    Awesome and easy to understand. Loved the video and I learned a lot. Thanks.

  • @AlexisDessard
    @AlexisDessard 11 місяців тому

    In summary, whether you're dealing with a copy or a reference in TypeScript depends on the type of the variable and how you've assigned or copied it. Primitive types are always copied, while reference types (like objects and arrays) are referenced unless explicitly copied using methods like the spread operator or deep copy functions.

  • @filcondrat
    @filcondrat 5 років тому +1

    great explanation for such a really sick topic in js

  • @justsaybobby
    @justsaybobby 2 роки тому

    Wow. I’m glad I found this. So helpful. Thank you!

  • @aymenboudabia5221
    @aymenboudabia5221 2 роки тому

    As always, simple and clear explanation. Thanks man!!

  • @kostiantynkarzhanov9216
    @kostiantynkarzhanov9216 Рік тому

    Thanks! Informative video, cleared up my understanding 💛

  • @Kuch_Bhi-lets_explore_it
    @Kuch_Bhi-lets_explore_it 2 роки тому +1

    Thank You Thank You Thank You So Much what an amazing explanation you nailed it 🔥🔥, I understand this tough concept so easily from your video , before that I am confused and I try to find the good explanation for that & this video clears my confusion , this concept is now crystal clear , Thank You so much again 🙌🙌

  • @harishs7384
    @harishs7384 3 роки тому +1

    the main cache here is "primitive and non-primitive" data types referring to "pass by value and pass by reference" respectively.

  • @hellothere8547
    @hellothere8547 5 років тому +2

    Thank you so much for the work you put with these videos. I was thinking of inheritance vs composition in JavaScript. Maybe that could be a new video? Which one is more beneficial.... etc

    • @WebDevSimplified
      @WebDevSimplified  5 років тому

      Thank you. That is a great idea. Generally I prefer composition when possible but it really depends.