2.3 Printing - Video Tutorials & Practice Problems
Video duration:
3m
Play a video:
<v ->In this section, we'll quickly review printing strings,</v> which is something we already talked about in the first chapter. Recall that we did something like this. Well, something exactly like this. (computer keyboard clacking) So the way to print strings in JavaScript is using console.log, and as mentioned briefly in the last chapter, this rather cumbersome and long name is an indication that JavaScript was not designed as a general purpose programming language. Most languages have something like print or printf which stands for print format, or "put s" which stands for put string. Usually it's something short and relatively easy to understand. Console.log is kind of weird and the reason is because JavaScript was designed for use in a browser where the main use of this sort of printing is to log things that are happening in the program. So let's take a look at the browser. I wanna open up the index.html file. (computer keyboard clacking) So in addition to this alert, I'm gonna add a console.log. (computer keyboard clacking) I'm gonna take a look at it. (computer mouse clicking) So here's the alert, and then if we look at the inspect element here, (computer mouse clicking) there it is, here's the result of the log. So this is the kind of thing you might use to debug something. If you wanted to put variable names, do a console.log to output variable names. You can also print things here, as we saw before. (computer keyboard clacking) A little small, but you get the idea. So this is the kind of thing that, for example, if I were to define a variable here, (computer keyboard clacking) I could then log it right here. (computer keyboard clacking) There it is. Finally, I'd like to note that the default behavior of console.log if you give it multiple arguments is to print them out with space separators. (computer keyboard clacking) So for example, before we saw this, (computer keyboard clacking) this is concatenation, (computer keyboard clacking) I could also do this. (computer keyboard clacking) This isn't quite the same thing because this here is a return value, you can see that it's in quotes. Whereas down here, this is being printed out as a side effect. We mentioned this briefly in the last chapter, but this is something that's happening as the result of evaluating console.log, but then the actual return value is undefined, right here. So strictly speaking, to make these equivalent I can do this, (computer keyboard clacking) so console.log of Michael plus space plus Hartl is the same as doing this.