JavaScript Basics
In the previous sections we talked about how HTML
and CSS
are the basic building blocks of a webpage. The third and final building block of a webpage is JavaScript
. Like CSS, it's not required to make a webpage, but most pages use it. Unlike HTML and CSS, JavaScript is an actual programming language. You can use it to perform tasks like solving math problems, showing popups to the user, and changing the layout on a page. JavaScript has become really powerful in the last few years, but the best part is that it's very easy to learn the basics.
Basic JavaScript
If you know other programming languages like Java
, or C
, then you'll see a lot of similarities to JavaScript. Unlike those languages, JavaScript execution simply starts at the top of the files and goes to the bottom in order-- there's no main()
function that gets called. That means a "Hello World" program can be as simple as this:
JavaScript allows you use variables, but unlike some other languages, variables do not have types. You just declare variables using the var
keyword like this:
Because variables don't have types, you can reassign them after creation. For example:
JavaScript Functions
Functions in JavaScript work similarly to other languages, allowing you to write some code once and then re-use it later. Since JavaScript does not have variable types, you don't need to specify a return value on your functions.
You can pass arguments to functions just like you'd expect. Again, these arguments do not have types:
JavaScript Objects
If you're used to other object-oriented languages like Java
or C
, you might be wondering where the classes and objects are in JavaScript. JavaScript does support objects, but it's not strictly object-oriented. In JavaScript objects are just a collection of values and functions wrapped together. You can define one using curly braces. Here's an example:
More on JavaScript
JavaScript is a huge language that has changed a lot since it was created. There's a lot to learn about it, but now you know the basics. Take a look at some of the resources below if you want get a more in-depth understanding of JavaScript. In the next section we'll go over actually using some JavaScript in a webpage.
Recommended Reading
Last updated