How to Program Hello, World in JavaScript
Hello, world! This is my first blog post so I would like to give myself a proper introduction. The only way to do that, of course, is with a Hello, World program. I will be using JavaScript to demonstrate this. If you are new to the coding verse, just consider it an initiation ritual, and don't feel too stressed about understanding everything in this post. Now, let's get straight to the code.
Before we run this program, I'd like to talk a bit about what we are doing here. First, forget about everything inside and after the brackets, and focus on the following:
On the left-hand side of the equals sign, we've created a variable, a place where we can store something for later. The const declares a variable into existence named helloWorld. There are different ways to declare a variable, like let and var, but const just means we can't change it once assigned to something.
On the right-hand side of the equals sign, we've created what's called an arrow function. Think of a function as an action. Anything inside of the brackets is what we want to execute. We also give helpful data to a function to do its job, called name
. Formally, this is called a parameter. So to summarize, what we have done here is assigned a function (an action) to a variable (to store) so we can execute it later. Now, let's move on to what's inside the function:
Console.log()
is a special method that comes packaged with JavaScript which allows us to print something to the console. Inside the parentheses, we've given it what we want to print. The ` denotes that we are creating a template string. A template string is special syntax that allows us to use string interpolation. This means we can use a variable directly in a string using the ${variable}
syntax. This is the equivalent of using "Hello, world. I'm " + name
.
Finally, let's move on to the final line of code:
Remember that function we saved in helloWorld earlier? We're now calling it with an argument of 'Charmy'. That is, we're executing the action. Do you remember how we added a parameter to the function in order to receive data? When calling a function, what you give it is called an argument. You could give it anything! Try it with your name, or "apple" or "a wild giraffe."
Alright, now that we've finished discussing the code, let's execute this program! To run the script we can use Node.js. If you do not have that installed, you can download it here. Open a terminal in the same directory as the script and run node .hello-world.js
And that's it! That's the hello, world program. I'm sure that was a lot to digest. If you are overwhelmed by all this information, trust me that's okay! Especially if you are early in your JavaScript career, it's a lot to put into one lesson. In the future, I'll be breaking topics down more for you.