JavaScript Basics

JavaScript is a cross-platform, object-oriented scripting language used to make webpages interactive (e.g., having complex animations, clickable buttons, popup menus, etc.). There are also more advanced server side versions of JavaScript such as Node.js, which allow you to add more functionality to a website than downloading files (such as realtime collaboration between multiple computers). Inside a host environment (for example, a web browser), JavaScript can be connected to the objects of its environment to provide programmatic control over them.

JavaScript contains a standard library of objects, such as Array, Date, and Math, and a core set of language elements such as operators, control structures, and statements. Core JavaScript can be extended for a variety of purposes by supplementing it with additional objects; for example:

  • Client-side JavaScript extends the core language by supplying objects to control a browser and its Document Object Model (DOM). For example, client-side extensions allow an application to place elements on an HTML form and respond to user events such as mouse clicks, form input, and page navigation.
  • Server-side JavaScript extends the core language by supplying objects relevant to running JavaScript on a server. For example, server-side extensions allow an application to communicate with a database, provide continuity of information from one invocation to another of the application, or perform file manipulations on a server..
You Should Know

Before diving into the bring and fantastical world of what we call, JavaScript, there are a few things you should know!

  • A general understand of the Internet and the World Wide Web (www)
  • Good working knowledge of HyperText Markup Languages (HTML)
  • Some programming experience.

Knowing the following will not only make things easier for you, but give you the ability to come up with and understand code that your write by yourself later on.

Variables

Variables are containers that store values. You start by declaring a variable with the let keyword, followed by the name you give to the variable:

myVariable "Hello World!";

A semicolon at the end of a line indicates where a statement ends. It is only required when you need to separate statements on a single line. However, some people believe it's good practice to have semicolons at the end of each statement. There are other rules for when you should and shouldn't use semicolons.

You can name a variable nearly anything, but there are some restrictions:

  1. Variable names must start with a letter (a - z / A - Z), underscore(_), or dollar($) sign.
  2. After the first letter, we can use digits (0 - 9). For example, value1

JavaScript is also case sensitive. This means myVariable is not the same as myvariable. If you have problems in your code, check the case!

Correct Javascript Variables
value 1;
_value "true";
value_2 true;

Incorrect Javascript Variables
123 0;
*value "false";
value two false;

You retrieve the value by calling the variable name:

myVariable;

After assigning a value to a variable, you can change it later in the code:

myVariable "Some Words"; 
myVariable = "Still Words";

Now you know how to declare and change variables on the fly! It is important to note that variables may hold different values that have different data-types:

  1. Strings

    Strings are sequences of text. To signify that the value is a string, enclose it in single or double quote marks.


    Example

    JS Declaration
    
    myVariable 'Bob';
    myVariable "Bob";
    

  2. Numbers

    Numbers don't have quotes around them. Adding quotes around them turn them into strings. So, it's important to remember to write them without quotation marks when you're trying to do math with them.


    Example

    JS Declaration
    
    myVariable 10;
    

  3. Booleans

    Booleans are declared with true / false. The worlds true and false are special keywords that don't need quote marks.


    Example

    JS Declaration
    
    myVariable true;
    

  4. Arrays

    Arrays are structures that allow you to store multiple values in a single reference.


    Example

    JS Declaration
    
    myVariable 10, 'Hello', 'World', false;
    
    You can refer to each member of the array like this:
    
    myVariable0; refers to: 10
    myVariable1; refers to: 'Hello'
    

  5. Objects

    Objects can be anything. Everything in JavaScript is an object and can be stored in a variable. Keep this in mind as your learn.


    Example

    JS Declaration
    
    myVariable document.querySelector('h1');
    

Comments

This far in, you must've noticed the use of comments, all highlighted in dark green, across all the Javascript examples.

If your comment contains no line breaks, it's an option to put it behind two slashes like this:

This is a comment

This type of comment
can't have a line break.

If your comment happens to have more than one line, you can write it just like your would a CSS comment:

This is
a multi-line
comment
Operators

JavaScript operators are symbols that are used to perform operations on operands. For example:

sum 20 + 10

Here, + is the arithmetic operator and = is the assignment operator.

There are 6 type of operators in JavaScript

  1. Arithmetic Operators
  2. Comparison (Relational) Operators
  3. Bitwise Operators
  4. Logical Operators
  5. Assignment Operators
  6. Special Operators

However, in this guide, we'll only go over Arithmetic & Comparison Operators.

Arithmetic Operators

Arithmetic Operators are used to perform arithmetic operations on the values. The following operators are known as JavaScript arithmetic operators.

Variables (used for the examples below)
a 20
b 10
Operator Description Example Output
+ Addition a + b 30
- Subtraction a - b 10
* Subtraction a * b 200
/ Subtraction a / b 2
% Modulus (Remainder) a % b 0
++ Increment a++ 21
-- Decrement b-- 9
Comparison Operators

The JavaScript Comparison Operator compares the two values and returns a true/false (boolean) value. The comparison operators are as follows:

Variables (used for the examples below)
a 20
b 10
Operator Description Example Output
== Is equal to a == b false
=== Strict Equality (Identical) a == b false
!= Not equal to a != b false
!== Strict Inequality (Not Identical) a !== b false
> Greater than a > b true
>= Greater than or equal to a >= b true
< Greater than a < b false
<= Greater than or equal to a <= b false
Conditionals

Conditionals are code structures used to test if an expression returns true or not. A very common form of conditionals is the if...else statement. For example:

answer "England"

answer === "England" 
   alert("That answer is Correct! 🎉")
 
   alert("That answer is Incorrect. ❌")


Let's break this down. The condition first tests the expression inside if (). This uses the Strict Equality operator to compare the variable, answer, with the string, England, to see if the two are equal. If this condition returns true, the first block of code runs:

answer === "England" 
   alert("That answer is Correct! 🎉")


If the comparison returns false, the second block of code — after the else statement — runs instead:


   alert("That answer is Incorrect. ❌")

Functions

Functions are a way of packaging functionality that you wish to reuse. It's possible to define a body of code as a function that executes when you call the function name in your code. This is a good alternative to repeatedly writing the same code. You have already seen some uses of functions. For example:

variable document.querySelector("h1");
alert("hello!");

These functions, document.querySelector and alert, are built into the browser.

If you see something which looks like a variable name, but it's followed by parentheses — () — it is likely a function. Functions often take arguments: bits of data they need to do their job. Arguments go inside the parentheses, separated by commas if there is more than one argument.

For example, the alert() function makes a pop-up box appear inside the browser window, but we need to give it a string as an argument to tell the function what message to display.

You can also define your own functions. In the next example, we create a simple function which takes two numbers as arguments and multiplies them:

a, b 
   result a * b
   return result;

Now you can run your function and input the arguments whenever you want!

multiply(5, 16); returns - 80
multiply(9, 2); returns - 18
multiply(37, 21); returns - 777

The return statement tells the browser to return the result variable out of the function so it is available to use. This is necessary because variables defined inside functions are only available inside those functions. This is called variable scoping. (Read more about variable scoping.)

Events

Real interactivity on a website requires event handlers. These are code structures that listen for activity in the browser, and run code in response. The most obvious example is handling the click event, which is fired by the browser when you click on something with your mouse.

document.querySelector"html".addEventListener"click", function  
   alert"Looks like it works!";
;

There are a number of ways to attach an event handler to an element. Here we select the htmlelement. We then call its addEventListener() function, passing in the name of the event to listen to ('click') and a function to run when the event happens.

The function we just passed to addEventListener() here is called an anonymous function, because it doesn't have a name. There's an alternative way of writing anonymous functions, which we call an arrow function. An arrow function uses () => instead of function ():

document.querySelector"html".addEventListener"click", () => 
   alert("Looks like it works!");
;