7.1 Function Declarations VS Expressions
So you've learned a bit about functions in JavaScript, in this new and final section, we'll look at functions in more detail. So I'm going to start by defining a function called walk and here we're going to do a console. Log of walk. What we have here is what we call a function declaration. But in JavaScript, there's another way to define a function, and is to use a function expression. So we start by declare a variable or a constant, give it a name like run, and then a name like run, and then we define it on a function. So, just like we can define a variable on a number, a string or an object, we can also define it on a define it on a function as well. And you know that in JavaScript, functions are objects. So, setting the variable to a function is similar to setting it on an object, And here at the end, we have to add a semicolon, because every we declare a variable or a constant, we end this statement with a semi-colon. statement with a semicolon. So here is another example. We set x to 1 and end it with a semicolon. On the other hand, we don't put a semicolon when we the semicolon when we define a function using the function declaration syntax declaration syntax, it doesn't really matter, so if you run this code, you'll you run this code, you won't get any errors, but by convention, we don't put that in here. So that's one difference between and function expressions. Now let's do a console. log, from run here. So basically, here we have defined a function, and this function has no name. Its syntax is very similar to what we have in a function declaration, except that here we don't have a name, we can give it a name, we can give it a name and then we would refer to that as a as a named function expression. Or we can exclude the name and with that we have an anonymous anonymous function expression. So we have defined an anonymous function that has no name and defined run to reference that function. So now we can call this anonymous function using this reference. Just like we call a function in JavaScript. So, save the changes and we get the runtime message on the console. Now we can declare another variable, which we'll call move and set it up so that it runs. So now move and run refer to the same anonymous function, which is an object in memory. So we can call this function using this other reference. So if we call move, we get the same result. So, to recap, in JavaScript, there are two ways to define a function, we can use the function declaration syntax, or the function expression which essentially involves declaring a variable or a constant, and then defining it on a function. define it on a function. That's it for this video on function declarations and expressions, we'll meet again for a very next video.