ไม่สามารถเล่นวิดีโอนี้
ขออภัยในความไม่สะดวก
Every JavaScript Developer Has Made This Mistake With Functions
ฝัง
- เผยแพร่เมื่อ 18 ส.ค. 2024
- JavaScript Simplified Course: javascriptsimp...
Did you know a function in JavaScript is actually just an object? This simple fact can be used to explain one of the most complex JavaScript concepts which is how passing functions to other functions works. This is a crucial concept to understand since most of JavaScript is built on passing functions to other functions.
📚 Materials/References:
Arrow Functions Video: • JavaScript ES6 Arrow F...
Functions As Arguments Article: blog.webdevsim...
🌎 Find Me Here:
My Blog: blog.webdevsim...
My Courses: courses.webdev...
Patreon: / webdevsimplified
Twitter: / devsimplified
Discord: / discord
GitHub: github.com/Web...
CodePen: codepen.io/Web...
⏱️ Timestamps:
00:00 - Introduction
00:30 - Understanding What A Function Is
02:11 - Callback Example
03:35 - Functions Vs Objects
06:05 - Anonymous Functions
#Callbacks #WDS #JavaScript
One thing I absolutely love about your channel is how you ruthlessly hunt "blind spots" that are very common yet rarely get the attention they deserve. Another gem by you
Bro, your hair is getting more and more magnificent. Enable god mode and go for a full Bob Ross.
Full Johnny Bravo.
More like Guile from SF, funny enough his name is Kyle :D
Please don't, everytime his hair levels up people like me lose more hair
lol
@@maema255 Kyle wins! Perfect!
"but what _is_ print?"
_vsauce music starts playing_
Edit: also, great video! I never really thought of giving functions properties like objects, I'm not sure how it's useful but it's interesting to know!
It would be a lot more useful if all the variables defined in the function were left as properties of the function object. It would only work if they got reset each time the function gets called
@@ericskelton5191
Yeah that would've been very cool. All variables without definition become properties while those with definition work as they do now. That way you choose what to reinitialize and what to persist without stress.🤗
Was kinda expecting something more with that title. If you’re an experienced coder you’d never make that mistake since its pretty self explanatory, especially if you’ve worked with other languages that have similar rules. In a beginner’s perspective I think they learn this very early on, but maybe not to the depth you explained.
100% agree
Hmmm plz def "exp coder"?
As ... Exp web dev coder?
Desktop app coder?
CMD line coder?
Scriptor???
Yeah I’ve only been coding for about 5 months and this was nothing new to me
Yeah, object oriented 101
agree
That is why we call these first class function
First class citizens
That is why we call Javascript functions first class objects.
Interesting insight into what a JavaScript function actually is, under the hood. But regarding usage when passing functions as arguments, I'm confused that there is any confusion over this.
All you have to remember is that parenthesis "()" mean "DO THIS RIGHT NOW", and causes a function to be invoked IMMEDIATELY. So you only use them if/when you want the function to be called right at that point in your code. If you intend that the function be called LATER (as is the normal intent with a callback), do not use the parenthesis. Need it be more complicated than this?
Honestly if anyone is confused over this, that person skipped his code training. (in any language)
@UC5uBCnYHtX2VR3yJbHi5Egg There is tremendous value in many of WDS videos. I just think in this case, the waters were muddied with a lot of superfluous information, and the gist could have been conveyed much more succinctly.
@@who41683 there's no elitism in that comment
you should learn to respect others and not call them losers
@@who41683 @Darrys @Darrys
Thanks for the video!! I've always been confused about what people really meant by callback functions, you explanation was perfect and it just clicked. Cheers!
I started learning Js just like two months ago, i needed to rewatch some parts of the video to full understanding but i feel i ve learn this hard topic. Finding your channel was a realy lucky thing to me, im absorving all your content and feel im fast learning the essencial things about js and coding. Thanks for that, really
This is the first step to understanding Haskell: a function is a value which takes other values. Would be interesting to hear about making functions which make functions (allowing for staged execution and peaking at fully curried functions).
Great video Kyle! These concepts helped demystify JavaScript for me in a big way and I find it odd how little this concept is spoken about.
Almost everything in JS is an object-like at a fundamental level, even Primitive types like strings. More specifically, there's usually a __proto__ key applied to these "objects" which refers to the blueprint of key value pairs that correspond to that data type. That's where methods like "string".tolowercase() and Array.map() come from.
When declaring a function or number etc. it's similar to generating a new object from a class in the sense that the number, function, string etc. receives some default keys and values.
I'm sure that you (Kyle) know all of this and I think it would make a great video which would help demystify JS for a lot of people like it did for me.
There's a noteworthy difference between string primitives and String objects instantiated using the constructor with the `new` keyword. The latter creates an object which is of type 'object', even though strings are normally of type 'string'. The constructor can be used to convert other things to strings, but it is safer to do so without using the `new` keyword. Using objects as strings disables us from comparing strings like we're used to, since `new String('str') !== 'str'`. It also causes unexpected behaviour if you're typechecking since all of the lines below evaluate to true:
typeof String('str') === 'string'
typeof new String('str') === 'object'
'str' instanceof String === false
String('str') instanceof String === false
Primitives actually get converted into their wrapper objects (String in this case) behind the scenes if you're trying to invoke a method or a property of theirs, which means this too, is true:
'str'.prototype === new String('str').prototype
This behaviour is called auto-boxing.
@@Italiafani Sorry if I wasn't very clear, I was simply trying to say that they are object-like in the sense that they have keys and values, methods etc. just like typical objects. Besides, I mentioned making a video as Kyle would do a much better job than I could in a comment.
@@leebuckle8288 No problem, my fellow dev. I was just elaborating on your comment so people might know just a bit more than they did. I agree it's important to know that everything in JS behaves like an object, but I also think the difference I explained is something to keep in mind.
@@Italiafani so does the new keyword always generate an object with the "blueprint" that references the initial object?
As in: in the initial it is a string, but with the new keyword you reference the initial value but create a new object of that initial value? (My explanation might not be very clear, indicating to me I don't think I really get the concept)
@@Italiafani Thanks for your input. I've edited my comment to be a bit more clear as to try and not confuse or give incorrect information. I should have mentioned that I'm by no means an expert on this matter, as is probably evident 😅
I did a trickier, higher-order form of this mistake with a react interface recently
Put my buttons as onClick={setState('such&such')} causing those to just run on render and fire off alarm bells with react
Fixed it with onClick={() => setState('such&such')}
use currying it's better than creating arrow function on each render
@@karanparmar4318 wdym? what does currying have to do with it?
for me currying is
const f = x => y => x + y;
const add5 = f(5);
console.log(f(10)(20)); // 30
console.log(add5(11)); // 16
@@Kitulous instead of making stuff complex and for reusability purposes
you could create separate function for it like this that uses currying as well,
currying doesn't mean you "should" pass and call arguments individually...
I hope following snippet helps you in some way.
//callback:
const handleClick=(a,b,c,d)=>(event)=> {
//handleYourCrap...
}
//render:
@@karanparmar4318 got it! yeah, I've been doing it kinda the same, but I was defining a separate function for each element and just passing it like
Literally every video you make, make sense. Things I dont understand is understood right after I watch your videos. Thank you so much for the value you bring to the Web Dev wold.
The hype is deserved, kyle. Great job and thank you.
Hate to say this, but this video is much easier to digest than the one on your JavaScript Simplified for beginners.
I'm liking your React course Kyle! Way better then another one I bought that was a lot more expensive. Very easy to follow and you explain the concepts well!
so clear! I kinda learned it myself, but really appreciate how concise and clear your explanation is!
가장 명쾌한 설명입니다.
JS 의 function 은 Object 이기 때문에,
callFunc( calledFunc ) 또는
callFunc( () => { doSomething } )
이렇게 쓰는 게 맞다.
() => { doSomething } 는 자체가 object 이기 때문이다.
callFunction( calledFunc() ) 가 혼란과 에러를 발생시키는 이유에 대해 정확하게 이해했습니다.
It just so happens that I'm learning JS today! lol
Thanks appreciate the explanation!
I really like that you cover more web theorie related content lately. I felt that more and more content related to your personal opinion (e.g. VSC extensions) took over. I subcribed because of the foundation principles and re-subed because you got back to those again.
I thought that this is knowledge that is supposed to be common knowledge, but then again I have been in this world of software engineering for decades now. But if it is true that many are not aware, then this is a great video that is excellent in getting those many developers out there that are missing a great idea, informed. Thanks for the video, and no thanks to the 33 dislikes who do not get the point with training videos.
recommended channel if you are interested th-cam.com/channels/vu6J9q1AM6q4xysGqAvVyw.html
Assigning a key:value to the function killed me :D :D :D Amazing explanations!
I love your videos so much Kyle, thank you for being so concise and helpful! You make every one of us better devs.
recommended channel if you are interested th-cam.com/channels/vu6J9q1AM6q4xysGqAvVyw.html
Hey Kyle! You're the BEST when I comes to break down the fundamentals in a comprehensive and elegant way 🙏 In 03:50 When you say: Functions are just like normal objects, the only difference is that you can call a function using parentheses passing different PARAMETERS to it. Wouldn't be more correct to say ARGUMENTS since you here is referring to values passed to the function and not names defined in the function declaration? Or am I missing something in regards of parameter/argument naming in function callbacks?
I'm new to developing, and OMG this video helped me A LOOOT to finally understand functions. Thaaank you
If you are a beginner see his videos 2 times and make notes of it you will never again have to struggle about that topic
Thanks Kyle. You really helped me to understand React and JavaScript. Love u man ❤❤
closures: allow us to introduce ourselves.
I been trying to understand callback function for a very long time and it just took less than a minute for you to explain what it is and i finally understooddddddddd...finallllyyyyyyyyyyyy
Thanks 😭😭😭
Wow this video is probably one of the best i haves seen as fresh JS and React coder. Always know how to use call back but never knew why am i doing it this way:D THX
One thing about functions few understand is that with IIFE syntax : (function x(){})(), from inside the function 'this' is always the CREATOR or OWNER of the function (usually Window at the top level), and that is because ALL vars in js (of which functions are just lists of instructions referenced by a var) are owned by whatever they are created inside of.
If all you want is a singleton that runs once and returns a handle to an interface you created, then no biggie...but...
If you use the syntax var x = new function(){} instead, the function is also immediately invoked - but from within the new function 'this' will be Object which is *often* what was intended because your whole point was to create a new execution context.
I call this DIFO (dynamically instantiated function object). Crockford got this wrong IMHO. If you use DIFO syntax instead of IIFE, all the this=that b.s. is not needed because you are not having to compensate for 'this' not being what you expect it to be. Crockford says this was an error in js but if you do a LOT of console logging tests the elegant design of js makes sense.
In js ALL vars are static, retaining their value between invocations of their enclosing function b/c they actually are data members ATTACHED to something, effectively a member of whatever it is created inside of - it's just confusing because much code is top level meaning it is owned by the Window object.
Because of all this, IMHO all the new ECMA 6 syntax like the class keyword, construction, even object.create is just syntactic sugar for C type programmers who are having a hard time grokking how js works.
Lovely comment
I made this comment almost a year ago but stand by it ;)
@@NicholasShanks
arrow functions are likewise dumb b/c in practice not only do you hardly save any keystrokes, but to understand at a glance what the code is doing - it just makes it harder with virtually no upside imho b/c you have to mentally sort the various flavors of arrow functions
Thanks because I just learned that callback in callback("hello") can be treated as a key
What i learned from this video
function TM( r ) {
if(!( 'tracker' in TM )){
TM.tracker = 0;
TM.maxR = r;
}
console.log('relevant execution completed');
TM.tracker++;
console.log('you can only replay this message '+ (TM.maxR - TM.tracker) +' times');
if(TM.tracker === TM.maxR){
console.log('TM is self-destructing...');
}
}
Thanks, Kyle for sharing and continuous effort for sharing all the stuff its really help
So true, great video Kyle
Yes bro sometimes I messed up with this and ultimately left that code, thank you for this... :)
thanks so much Kyle, it help so much how explained it
Very Helpful Video
Very useful tips, dude. Thanks!!!
Thanks mate!
Thanks a lot for this useful video. I came across this kind of problem recently, while I was trying to make a function, which was using a callback as an input parameter and use it across multiple components in Vue JS, but I got stuck and temporarely left the problem undone. Now I will definetly try again :). Thanks again and thumbs up
Anonymous / Arrow / Lambda functions. When I started playing with them, the idea that "functions are also variables" finally clicked. And those are littered throughout JavaScript lmao
This is amazing to know, thanks man!
Well thanks for teaching some fundamental principles of functional programming. But please don‘t use such clickbait titles, and someone that is programming for years certainly figured this out already (in the beginning you said that even these people still don’t get this).
Just make a course about functional programming and name it that, not some clickbait shit
Agree, I got clickbaited.
no he did it right, I met someone who is coding in node js for many years but still don't know about it
I also worked with one guy who is coding in laravel more than year and still don't know accessor and mutators while I was a newbie and already knew about it, so it happens in real life
This isn't clickbait. I have met far too many people that consider themselves strong JS developers that do not understand these concepts. This is something often overlooked by people following the self-taught route and the confusion between functions being special things vs just being an object is something I see all the time.
@@WebDevSimplified well i think it is. You bait someone to click on your video with the statement that EVERYBODY is making these mistakes, even experienced js developers. I agree that many people don‘t know functional programming. And as I already said, i think it is a nice and informative video, but I think you should declare upfront what you will explain in this video
@@WebDevSimplified Just because there are so many people who overlook this concept, doesn't mean *everybody* does. The fact that you put "Every" in your title while it's actually not, is clickbait.
TH-cam literally recommends me this right after I used it in my code
Awesome stuff as always Kyle, keep it up!
recommended channel if you are interested th-cam.com/channels/vu6J9q1AM6q4xysGqAvVyw.html
Wow kyle am always great full with your content and tutorials I have leant alot from your working, Javascript it's awesome
hello please, i have an input, i created a function to get the input value and put it inside a text, the problem is that i need the function to put the value inside the text multiple times and the function take the value and put it in the one only! so how can tell the function to whenever it finds the div to put the value it put it there (multiple times)
This makes so much more sense now! 😮
Hey Kyle! Could you make a video of deployment ? Web hosting, DNS and so on ...
The function you defined, "print" actually overrides a JavaScript default function. Be ware!
It would only override it in that specific instance, though, right?
Well, it's just for educational purposes. And the _print_ function isn't even native to JavaScript, it's from the browser.
@@farhanaditya2647 ...which is where JS originated.
Yo this was so informative! Thanks for helping us fill in the gaps 🙂
Man this is so good. Thanks for this
Thanks Kyle and do you mind to make a video for JavaScript prototype? Wish to know a bit more from your video ~~
Hmm, I think you need to change the name of the video (make too made rather?). I may have made this mistake loooong ago (couldn't even tell you if I did), but I worked with prototyping back in 2008 already which is the basis of what you're eluding to... I actually thought you were gonna talk about prototyping.
And, my prototyping knowledge came from my Flash ActionScript 1 days which was based on ECMA.
Good point. I just updated the title.
Really neat introduce to OOP :)
It's just fundamental in JS, very simple to think, we use .call .apply .bind , so function is an object itself.... We can add more properties.
hi can you explain the difference between a factory function and a constructor function and it's applications?
Really helpful
That's why JavaScript is my favourite language.
Hi Kyle! First of all thanks for your content man ,it's really helpful...
I started noticing your guitar on your videos, what type of music do you like to play? Any videos of that soon ;) Cheers!
so cool 👍🏻 thanks
stupid question: why no ";" at end of statments ? I didn't know we could skip them... is it new ?
Thanks !!
Hey Kyle, thanks for the informative video. I'm sure a lot of people will benefit from this.
I just wanted to point out that the whole idea of functions (which are essentially objects) to be used as a variable (like passed in as an argument or returned from a function etc) is known to us as "Functions are First-Class Objects or First-Class Citizens in JavaScript". Just a little terminology that can help people in interviews or elsewhere.
Thanks!
like Jeff (Fireship) said, "welcome to javaScript world"
Your videos ALWAYS blow my mind ; )
Web Dev Challenge-Ethiopia
If this makes sense, I just think of functions as a way to create a temporary scope like one of the worlds in our solar system. A world / planet has access to meteorites and other universal things from the universe but to return it back out to the universe we must explicitly return it (punch it back out like ultraman fist!).. hence return lol
Lol nice metaphor
Johnny Bravo knows JavaScript!
Reminds me of the "*Everything* in JS is an object" argument. (Which is not true). But still, good catch, Kyle, thank you for the info
I'm confused. Isn't a function different in that it defines a bunch of code to execute? A plain object only contains properties, whereas a function executes a block of code (conditional logic, loops, etc)
Awesome man 😎😎😎
Function is just a variable, essentially like an object… makes sense! 🤯😂
Hi, could you make a video about importing something from string variable?
Something like:
const dir = './img.png'
import(dir)
coming from java, sometimes its difficult to wrap head around weirdness of javascript
Thanks
This is good and all, but when are you picking up that guitar?
It's bit confusing to say that you pass a function print to another function as an input parameter. You pass a pointer which points to a print function or to be more explicit to the memory space on the heap where the memory for print function was allocated. Correct me if I'm wrong. Good vid btw.
Its abstraction. What you said is more confusing especially considering Javascript is a language where you don’t directly manage the stack, heap, etcetera. Maybe in languages like C that would make more sense.
Despite being a beginner, their comment was ironically more understandable. It my head, that's exactly what I see, 'passing pointers' that point to the 'print' function, as opposed to 'passing the function'.
i get it thanks
I love it. You're awesome 👌👌👌
this just made more confused bro. I think I need to watch it a couple of times.
Useful.
I've never made this mistake (maybe typos, but never because of a lack of understanding), so I feel oddly left out now 😂😂. The setting properties on functions thing was very cool though, never knew about that! ☮️🙌🏽🎊🏆
this video saved me
Awesome video
Hello Kyle and thank you for all of your content!
(btw I really like how you styled the battleship game, amazing job!)
Another example for the concept you delivered in this video is actually in REDUX actions creators...
naturally we destruct action creators functions when we use bindActionCreators function.
like this for example:
const { actionCreator1, actionCreator2, actionCreator3 } = bindActionCreators(actionCreators, dispatch)
we can see that we destruct those functions like regular objects.
Love you, Kyle
It's surprising how many people get confused by this.. I don't really understand why
Types in typescript can also be functions if you're crazy enough
Nice one
Amazing!
What I find confusing is when a function is set to a const. The following will print "hello world" even though there is no explicit statement myWorld() to execute the function assigned to it. Makes no sense to me. If I set a const to a function it should mean that I don't want the function to execute until the const is called.
const myWorld= setTimeout(() => { //setTimeout executes
console.log("hello world")
}, 500);
you assign setTimeout() call result to a constant, not a function
when you call setTimeout, it already creates a timer that calls the specified function in a specified timeout
idk if it returns anything even
setInterval returns a number that you can use later to clear that interval:
const interval = setInterval(() => console.log("I will log this every second"), 1000);
function stopLogging() {
clearInterval(interval);
}
"Whether you're a novice or have been programming for years, I'm gonna blow your mind!" *proceeds to explain the most basic concept of JavaScript, that functions are first-class objects* No offense but I'm glad I had my adblocker on for this, you do not deserve any revenue for 7 minutes of content that should have been in your "Intro To" series back in 2018.
I actually learned the difference between passing a function With and Without parenthesis, thanks! even so, I downvoted the video because of the confusing accelerated explanation that as usual lookes more like thinking in a loud voice rather than TEACHING.
recommended channel if you are interested th-cam.com/channels/vu6J9q1AM6q4xysGqAvVyw.html
Awesome...
Very insightful tutorial. Thanks, Kyle
{2021-08-15}
This is what functions being fist class citizens in javascript means.
I was not a big fan of Javascript some time ago, but it has grown on me and there are things I do think are cool in it.
But one thing I think I will never like, or use if I can avoid it, is Callbacks.
I hate them. I can't see the reason or the logic behind using them.
*Here, let me write a function that takes in a callback, write another function that prints out some input and bla bla bla...*
Why?! Just write console.log("something") and there you go. And there is probably also another, easier, solution if the scenario is different. I don't see how or why using callbacks would be smarter. I just don't. And I haven't heard anyone explain it in a way that made me go "aaaah, now I see".
This is because they're not showing real callbacks, they're showing a spaghetti version.
How I would use a callback. I'd have another object that is a controller. Other objects can store their launch, pause, destroy methods (functions). I would call this registering with the controller.
Now a user can make a choice from a the ui, and it calls the proper objects (call me back when you need me bro) methods.
This way that code never needs to run unless necessary.
I can make each object have the same name for their functions that control them. Now the API to control my objects are the same. So the controller can get the object from a map, and call it's launch, or whatever. So my launcher function in my controller is a function that takes a search term.
dummy code to express idea.
launcher(searchterm){ launcherMap.get(searchterm).launch()}
pauser(searchterm){ launcherMap.get(searchterm).pause()}
Still confused about these callback functions
Function you call when you need to do something in another function. Before you print data, you want to read them first. Getting data will be a callback you cannot print without cause there is nothing to print.
nice tnx