Stephen Grider

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.

The Modern Javascript Bootcamp Course (2020)

Last Updated February 2021

  • 483 lectures
  • All Levels
4.7 (6,391)

The most up-to-date JS resource online! Master Javascript by building a beautiful portfolio of projects! | By Colt Steele, Stephen Grider

Explore Course

Writing 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:

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:

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:

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:

const car ="Toyota";
const car = "Toyota"; // Easier to read
Document.getElementById(“example”).innerHTML = “Insert New Text Here”;
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:

abstractargumentsawaitboolean
breakbytecasecatch
charclassconstcontinue
debuggerdefaultdeletedo
doubleelseenumeval
exportextendsfalsefinal
finallyfloatforfunction
gotoifimplementsimport
ininstanceofintinterface
letlongnativenew
nullpackageprivateprotected
publicreturnshortstatic
superswitchsynchronizedthis
throwthrowstransienttrue
trytypeofvarvoid
volatilewhilewithyield

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:

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:

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.

OperatorDescriptionExampleResult
+Additionx + ySum of x and y
Subtractionx – yDifference of x and y.
*Multiplicationx * yProduct of x and y.
/Divisionx / yQuotient of x and y
%Modulusx % yRemainder of x divided by y

Comparison

Comparison operators compare two values and return a boolean value of true or false.

OperatorNameExampleResult
==Equalx == yTrue if x is equal to y
===Identicalx === yTrue if x is equal to y, and they are of the same type
!=Not equalx != yTrue if x is not equal to y
!==Not identicalx !== yTrue if x is not equal to y, or they are not of the same type
<Less thanx < yTrue if x is less than y
>Greater thanx > yTrue if x is greater than y
>=Greater than or equal tox >= yTrue if x is greater than or equal to y
<=Less than or equal tox <= yTrue if x is less than or equal to y

Logical (or Relational)

Logical operators are used to combine conditional statements.

OperatorNameExampleResult
&&Andx && yTrue if both x and y are true
||Orx || yTrue if either x or y is true
!Not!xTrue if x is not true

Assignment

The JavaScript assignment operators are used to assign values to variables.

OperatorDescriptionExampleIs The Same As
=Assignx = yx = y
+=Add and assignx += $x = x + y
-=Subtract and assignx -= yx = x – y
*=Multiply and assignx *= yx = x * y
/=Divide and assign quotientx /= yx = x / y
%=Divide and assign modulusx %= yx = x % y

String Operators

String operators operate on strings. There are only two.

OperatorDescriptionExampleResult
+Concatenationstr1 + str2Concatenation of str1 and str2
+=Concatenation assignmentstr1 += str2Appends 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.

Page Last Updated: February 2021

Top courses in JavaScript

50 Projects In 50 Days - HTML, CSS & JavaScript
Brad Traversy, Florin Pop
4.8 (2,527)
Bestseller
JavaScript Web Projects: 20 Projects to Build Your Portfolio
Andrei Neagoie, Jacinto Wong
4.7 (1,469)
The Complete JavaScript Course 2021: From Zero to Expert!
Jonas Schmedtmann
4.7 (98,823)
Bestseller
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
Academind by Maximilian Schwarzmüller, Maximilian Schwarzmüller
4.6 (13,116)
The Modern Javascript Bootcamp Course (2020)
Colt Steele, Stephen Grider
4.7 (6,391)
JavaScript Basics for Beginners
Mosh Hamedani
4.6 (8,115)
Bestseller
Modern JavaScript From The Beginning
Brad Traversy
4.7 (23,992)
Modern JavaScript (Complete guide, from Novice to Ninja)
The Net Ninja (Shaun Pelling)
4.8 (6,027)
Learn JavaScript: Full-Stack from Scratch
Brad Schiff
4.8 (3,320)
Highest Rated

More JavaScript Courses

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 for Business.

Request a demo

Courses by Stephen Grider

Modern React with Redux [2020 Update]
Stephen Grider
4.7 (66,305)
Bestseller
Advanced React and Redux
Stephen Grider
4.6 (9,742)
Meteor and React for Realtime Apps
Stephen Grider
4.8 (1,927)
Bestseller
The Complete Elixir and Phoenix Bootcamp
Stephen Grider
4.5 (5,547)
Bestseller
The Complete React Native + Hooks Course [2020 Edition]
Stephen Grider
4.6 (36,790)
Bestseller
GraphQL with React: The Complete Developers Guide
Stephen Grider
4.5 (7,578)
Bestseller
React Native: Advanced Concepts
Stephen Grider
4.2 (4,689)

Courses by Stephen Grider