JavaScript Tutorial: Learn the Basics
JavaScript is easy to learn, one of the most popular programming languages, and the language of the web. If you have a web browser, you have an environment where you can write JavaScript. So why not get started today with this basic JavaScript tutorial?
Prerequisites
It will help if those starting this tutorial have a basic understanding of HTTP Protocol and possess some knowledge of HTML and CSS. You can find introductory resources for these topics on Udemy’s website. However, it is not necessary to know any of this to write JavaScript code. So let’s do that now to show you.
Last Updated February 2023
The most up-to-date JS resource online! Master Javascript by building a beautiful portfolio of projects! | By Colt Steele, Stephen Grider
Explore CourseWriting your first JavaScript code
Getting started with Javascript is easier than any other programming language. All you need is a browser to write JavaScript code. All popular browsers, including Chrome, Edge and Safari, have a set of developer tools that allow users to view information about the current web page, execute JavaScript, modify the live HTML, among other things.
Let’s try writing some Javascript inside the Chrome browser. If you choose another browser to use, the only difference will be how you access the developer tools and the console. In Chrome, you can get to the console in the developer tools in two ways:
- Use the keyboard shortcut Command + Option + J (Mac) or Control + Shift + J (Windows/Linux).
- Use the Chrome menu: Select > More Tools > JavaScript Console.
Once you have accessed your browser’s console, type this code in and hit enter:
alert('Hello, World!')
You couldn’t exactly call yourself a hacker now, but that was pretty simple. After this action, you should see an alert pop up that says, “Hello, World.” Now let’s learn more about JavaScript so we can start writing code that does more. First, let’s look at what exactly JavaScript is.
What is JavaScript?
Brendan Eich created JavaScript in 1995 while working as an engineer at Netscape. It is an object-oriented programming language that facilitates interactivity within browsers without reloading pages for each action. JavaScript is a scripting language. Eich wrote the first version of the language in only 10 days.
JavaScript features
JavaScript is a scripting language. Scripting languages do not need to undergo compilation. They rely on special run-time environments and related interpreters—computer programs that execute code without compilation through various methods. Modern web browsers include interpreters that can interpret Javascript code.
JavaScript outside of the browser
The most popular environment you will find JavaScript outside of the browser is for NodeJS. NodeJS is a JavaScript engine that runs without a browser in a server environment. This means you can use JavaScript to build a complete web application from the backend to the frontend.
In addition, various mobile frameworks like Cordova, Ionic, and React Native allow developers to build mobile apps using web technology, including JavaScript for any scripting.
Alternatives to JavaScript
There are few real alternatives to JavaScript for executing code in a browser. These options offer an alternative syntax to JavaScript but are compiled to pure JavaScript before we can use them in a browser. Some popular alternatives to JavaScript include CoffeeScript, TypeScript, and Dart.
When using these alternative languages, your code is translated to Javascript then executed in the browser.
Adding JavaScript to HTML
In the experiment above, you used the console of your web browser to execute JavaScript code. The standard use of JavaScript is to add scripting to HTML pages. To do that, you need to include JavaScript in the HTML itself. When a browser detects a <script> tag in an HTML file, it knows to execute JavaScript code. Using this tag, you can either embed your JavaScript code directly in an HTML file or include a separate JavaScript source file.
Internal JavaScript
You can place JavaScript directly in the HTML file, between the <script> and </script> tags.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example web page</title>
<link rel="stylesheet" type="text/css" href="css/example.css">
</head>
<body>
<h1>Example Page</h1>
<script>document.write("<h3>Hello!</h3>")</script>
<p>Glad you're here.</p>
</body>
</html>
You can place internal JavaScript in either the head or body section of an HTML document.
In this case, our Javascript code is embedded directly into the HTML file.
External JavaScript
You can also link an external JavaScript file to an HTML file.
For example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example web page</title>
<link rel="stylesheet" type="text/css" href="css/example.css">
</head>
<body>
<h1>Example Page</h1>
<p>Glad you're here.</p>
<script src = "js/example.js"></script>
</body>
</html>
In this case, the script tag forces the browser to fetch our Javascript code from an external location.
The path to the external JavaScript file is the value of the src attribute in the <script> tag. It is recommended that scripts be placed at the bottom of the <body> element to prevent delayed page loading due to blockage of HTML display by script loading. JavaScript files traditionally use the extension js.
Unless you are just adding a small snippet of code to a web page, the recommended way to add JavaScript to HTML is by including the external JavaScript file. There are a few reasons for this:
- Separation of JavaScript and HTML makes both easier to read and maintain.
- Pages can load faster because of the caching of JavaScript files by browsers, which decreases the size of HTML documents. Internal JavaScript increases the size of HTML documents because it gets downloaded upon each HTML document request.
- You can link multiple HTML documents to the same JavaScript file, which can decrease page loading time because of browser caching.
JavaScript basics
Before you write more JavaScript code, it pays to know the basics. Every programming language has rules, and JavaScript is no different. The rules of a programming language are like those of a spoken language, except when you break the rules in code, the most likely result is that your code will not work.
The following features of the JavaScript language are common to most programming languages, but how they handle them are different.
JavaScript syntax
Syntax are the rules of writing the language, similar to grammar in a spoken language.
Case sensitive
One rule of JavaScript is that it is case-sensitive, meaning that if you create a variable of a specific case, like Car, then you must use the same case to access that variable again, and not car.
Identifiers
An identifier in JavaScript is the name of a variable, function, parameter, or class. These names must follow these rules:
- The first character must be a letter (a-z or A-Z), an underscore(_), or a dollar sign ($).
- The other characters can be letters (a-z or A-Z), numbers (0-9), underscores (_), and dollar signs ($).
While not a rule of the JavaScript language, a convention followed by most developers is that these names should be in CamelCase. CamelCase capitalizes every word in a name except the first.
Example:
const thisIsCamelCase = '';
Comments
Comments are sections of your code that don’t execute. The name defines itself. They are used to add notes to code and sometimes are written in a structured format so they can be parsed to create documentation pages for code. JavaScript supports two types of comments, single line and block.
// This is a single line comment. It must stay on one line.
/* This is a
block comment. It can
span as many lines as you'd like.*/\### JavaScript variables
Statements
A statement is an instruction given to the computer. A script comprises a series of statements specifically ordered to achieve a goal (like a recipe). Here are a few things to keep in mind regarding statements:
- New Lines – Every statement should start on a new line.
- Semicolons – Each statement should end with a semicolon; this tells the interpreter to complete this step and begin with the following statement.
- White space – White space comprises tabs, spaces, and newline characters. White space between words and tabs are ignored. Use white space to make your code easier to read.
Example:
const car ="Toyota";
const car = "Toyota"; // Easier to read
- Line Length – Keep code length to 80 characters or shorter to maximize readability.
- Line breaks – Ignored unless found in a statement. For multi-line statements, breaks should be used after operators (e.g., =, +, -).
Example:
Document.getElementById(“example”).innerHTML = “Insert New Text Here”;
- Code Blocks – Code blocks organize related statements within curly braces { } and make them easier to read. Closing curly bracket is not followed by a semicolon. JavaScript functions are often in code blocks.
Example:
function myBirthday {
alert(%u201CHappy Birthday!%u201D);
Document.getElementById(%u201Cmessage%u201D).innerHTML =
%u201CYou%u2019re one year wiser!%u201D;
}
Expressions
An expression is a snippet of code that evaluates to a value.
For example:
10 + 20
The expression above evaluates to 30.
You can use variables in expressions as well:
const a = 10;
const b = 20;
a + b
The third line is an expression that also evaluates to 30.
Keywords and reserved words
JavaScript uses specific names for some of its own method. Because of this, you can’t use the same names for your own variables, functions, and classes. These are called keywords or reserved words. Here is a list of them:
abstract | arguments | await | boolean |
break | byte | case | catch |
char | class | const | continue |
debugger | default | delete | do |
double | else | enum | eval |
export | extends | false | final |
finally | float | for | function |
goto | if | implements | import |
in | instanceof | int | interface |
let | long | native | new |
null | package | private | protected |
public | return | short | static |
super | switch | synchronized | this |
throw | throws | transient | true |
try | typeof | var | void |
volatile | while | with | yield |
JavaScript variables
JavaScript and other programming languages use variables to store values. Above, in the syntax section, we reviewed the rules of creating names for variables.
Datatypes
JavaScript variables must have a type. JavaScript determines the type of a variable dynamically when it is assigned. Here are the data types that JavaScript supports:
- Undefined – A variable is assigned this type when it doesn’t have a value.
- Null – A variable of this type does not exist. It is not the same as undefined.
- Boolean – A variable of this type can either be true or false.
- String – A variable of this type can contain letters and other characters. It must be surrounded by single or double quotes.
- Symbol – A variable of this type is unique and immutable and was added in the ES6 version of JavaScript.
- Number – A variable of this type can be a whole number, decimal, negative number, or scientific notation.
- Object – A variable of this type is a composite type. It has properties and methods. It is represented with key-value pairs separated by commas and wrapped with brackets. The properties and methods are accessed by keys.
- Array – A variable of this type is a list of values enclosed in braces and separated by commas. Values are accessed by the index of the value. Arrays in JavaScript are zero-based, meaning this index starts at 0.
Examples of these are:
// Undefined
const a;
// Null
const b = null;
// Boolean
const c = true;
// String
const d = "string one";
const e = 'string two';
// Symbol
const f = Symbol( );
// Number
const g = 10;
const h = 5.5;
const i = -7;
const j = 123e-5;
// Object
const k = {carMake: "Toyota", carModel: "Prius", year: 2012, extColor: "black"};
// Array
const l = ["White", "Blue", "Green"];
JavaScript data types are dynamic, which means that a variable can be reassigned to a new type when they are defined with var or let.
let x = 12; // Type is number
let x = "Car"; // Type is string
let x; //Type is undefined
Assignment
You can assign a value to a variable with the assignment operator, which is the equals sign (=). These are the three ways to define variables in JavaScript:
- var – Variables defined with this keyword are processed before the execution of the JavaScript.
- let – Variables defined with this keyword can be reassigned. They also can only be used in the block they are defined in.
- const – Variables defined with this keyword cannot be reassigned. The keyword stands for constant.
Examples are:
const a = 'I cannot be reassigned';
let b = 'I only work in my code block';
var c = 'I am not used as often any more';
For most development needs, const and let are preferred.
JavaScript operators
An operator in a JavaScript is a symbol that tells the compiler or interpreter to perform one of the following operations:
Arithmetic
Some of these should be familiar. They perform arithmetic operations.
Operator | Description | Example | Result |
+ | Addition | x + y | Sum of x and y |
– | Subtraction | x – y | Difference of x and y. |
* | Multiplication | x * y | Product of x and y. |
/ | Division | x / y | Quotient of x and y |
% | Modulus | x % y | Remainder of x divided by y |
Comparison
Comparison operators compare two values and return a boolean value of true or false.
Operator | Name | Example | Result |
== | Equal | x == y | True if x is equal to y |
=== | Identical | x === y | True if x is equal to y, and they are of the same type |
!= | Not equal | x != y | True if x is not equal to y |
!== | Not identical | x !== y | True if x is not equal to y, or they are not of the same type |
< | Less than | x < y | True if x is less than y |
> | Greater than | x > y | True if x is greater than y |
>= | Greater than or equal to | x >= y | True if x is greater than or equal to y |
<= | Less than or equal to | x <= y | True if x is less than or equal to y |
Logical (or Relational)
Logical operators are used to combine conditional statements.
Operator | Name | Example | Result |
&& | And | x && y | True if both x and y are true |
|| | Or | x || y | True if either x or y is true |
! | Not | !x | True if x is not true |
Assignment
The JavaScript assignment operators are used to assign values to variables.
Operator | Description | Example | Is The Same As |
= | Assign | x = y | x = y |
+= | Add and assign | x += $ | x = x + y |
-= | Subtract and assign | x -= y | x = x – y |
*= | Multiply and assign | x *= y | x = x * y |
/= | Divide and assign quotient | x /= y | x = x / y |
%= | Divide and assign modulus | x %= y | x = x % y |
String Operators
String operators operate on strings. There are only two.
Operator | Description | Example | Result |
+ | Concatenation | str1 + str2 | Concatenation of str1 and str2 |
+= | Concatenation assignment | str1 += str2 | Appends the str2 to the str1 |
JavaScript conditionals
JavaScript and other programming languages use conditionals to control the flow of a program.
if, else if, and else
If a if condition is met, a particular code block should run. An else if statement only executes if the previous condition is not met. If the else if statement condition is not met, the else statement following it will execute.
Example:
if (x < y) {
console.log('y is bigger');
} else if (x > y) {
console.log('x is bigger');
} else {
console.log('This will never run.');
}
switch
The variable, the switch value, determines which case to execute. The switch statement lives in a single code block, with semicolons separating the cases from each other. A default option runs if the switch value does not match any of the cases. A break statement must be used after each switch statement to exit the switch statement once a condition has been met or it will keep testing conditionals. The code in the default case runs when none of the other conditions are met.
For example:
const greeting;
const day = ‘Monday’;
switch(day) {
case ‘Monday’:
greeting = ‘Happy Monday!’;
break;
case ‘Friday’:
greeting = ‘TGIF!’;
break;
default:
greeting = ‘Good Morning!’;
break;
}
JavaScript loops
Loops allow you to repeat a code block until it returns false. JavaScript supports three types of loops.
for
The for loop, the most common type of loop, allows you to run the code a specific number of times and keeps track of the number of loops through the code block.
For example:
for (let i = 1; i < 10; i++) {
console.log(i);
}
In the loop above, the loop counter is the variable i and is set to 1. The second expression tells us that the loop will run while i is less than 10. The final expression increments the variable by 1 for each loop.
while
A while loop repeats a code block until a condition returns false. You would apply this when you do not have a specific number of desired loops or when you want to loop while a certain condition proves true.
For example:
let x = 0;
let y = 1;
while(x < 10) {
x++;
y--;
}
The loop above will execute while x is less than 10. x starts at 0 and increments 1 for each loop, so the loop will execute 10 times.
do while
This type of loop is like a while loop, but will run a code block at least once, whether or not the specified condition is met.
For example:
let count = 20;
do {
alert('Loop de loop!');
count++;
} while (count < 20);
The loop above will run 20 times.
JavaScript functions
A JavaScript function comprises a reusable code block containing statements aimed at completing a particular task. You create functions in JavaScript using the function keyword.
For example:
function areaRectangle(width, height) {
alert (“The area is " + (width * height) + " feet.");
}
areaRectangle(10, 20); // the result is "The area is 200 feet."
In the example above, we have a function that will create an alert telling us the area of a rectangle named areaRectangle. In this function, width and height are called parameters. In the last line of the example, we execute the function.
Conclusion
This tutorial should get you started with the basics of JavaScript. There is much more to learn about this powerful programming language, but with this knowledge, you should be able to understand the terminology of the language and follow more advanced tutorials to start building applications in JavaScript.
Recommended Articles
Top courses in JavaScript
JavaScript students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.