What is JavaScript ?

JavaScript was initially created to “make web pages alive”.

The programs in this language are called scripts. They can be written right in a web page’s HTML and run automatically as the page loads.

Scripts are provided and executed as plain text. They don’t need special preparation or compilation to run.

Internal JavaScript

Add the following at the bottom of your body — just before your closing </body> tag, this way it will be executed when the page loads:

<script>
  // JavaScript goes here
</script>

External scripts

If we have a lot of JavaScript code, we can put it into a separate file. Script files are attached to HTML with the src attribute:

<script src="script.js"></script>

Script loading strategies

All the HTML on a page is loaded in the order in which it appears. If you are using JavaScript to manipulate elements on the page (or more accurately, the Document Object Model), your code won't work if the JavaScript is loaded and parsed before the HTML you are trying to do something to.

There are a few different strategies to make sure your JavaScript only runs after the HTML is parsed:

  • In the internal JavaScript example above, the script element is placed at the bottom of the body of the document, and therefore only run after the rest of the HTML body is parsed.
  • In the external JavaScript example above, the script element is placed in the head of the document, before the HTML body is parsed. But because we're using <script type="module">, the code is treated as a module and the browser waits for all HTML to be processed before executing JavaScript modules.
  • If you still want to use non-module scripts in the document head, which could block the whole page from displaying, and could cause errors because it executes before the HTML is parsed:
    • For external scripts, you should add the defer (or if you don't need the HTML to be ready, the async) attribute on the <script> element.
    • For internal scripts, you should wrap the code in a DOMContentLoaded event listener.

See some examples and get more information in the MDN Documenation

Comments

A single line comment is written after a double forward slash (//), e.g.

// I am a comment

A multi-line comment is written between the strings /_ and _/, e.g.

/*
  I am also
  a comment
*/

Variables

To create a variable in JavaScript, use the let keyword.

let myVariable;

In older scripts, you may also find another keyword: var instead of let:

var myVariable;

Constants

To declare a constant (unchangeable) variable, use the const keyword.

const PI = 3.14;

Variables declared using const are called “constants”. They cannot be reassigned. An attempt to do so would cause an error

Variable Types

Number

let n = 123;
n = 12.345;

The number type represents both integer and floating point numbers.

String

A string in JavaScript must be surrounded by quotes.

let str = "Hello";
let str2 = "Single quotes are ok too";
let phrase = `can embed another ${str}`;

In JavaScript, there are 3 types of quotes.

  • Double quotes: "Hello".
  • Single quotes: 'Hello'.
  • Backticks: Hello. Double and single quotes are “simple” quotes. There’s practically no difference between them in JavaScript.

Backticks are “extended functionality” quotes. They allow us to embed variables and expressions into a string by wrapping them in ${…}, for example:

let name = "John";
 
// embed a variable
alert(`Hello, ${name}!`); // Hello, John!
 
// embed an expression
alert(`the result is ${1 + 2}`); // the result is 3

The expression inside ${…} is evaluated and the result becomes a part of the string. We can put anything in there: a variable like name or an arithmetical expression like 1 + 2 or something more complex.

Boolean

Booleans are true/false values — they can have two values, true or false. These are generally used to test a condition, after which code is run as appropriate. So for example, a simple case would be:

let iAmAlive = true;
let test = 6 < 3;

Arrays

An array is a single object that contains multiple values enclosed in square brackets and separated by commas.

let myNameArray = ["Chris", "Bob", "Jim"];
let myNumberArray = [10, 15, 40];

Once these arrays are defined, you can access each value by their location within the array. Try these lines:

myNameArray[0]; // should return 'Chris'
myNumberArray[2]; // should return 40

The square brackets specify an index value corresponding to the position of the value you want returned. You might have noticed that arrays in JavaScript are zero-indexed: the first element is at index 0.

Objects

In programming, an object is a structure of code that models a real-life object. You can have an object that represents a box and contains information about its width, length, and height, or you could have an object that represents a person, and contains data about their name, height, weight, what language they speak, how to say hello to them, and more.

let dog = { name: "Spot", breed: "Dalmatian" };

To retrieve the information stored in the object, you can use the following syntax:

dog.name;

Dynamic typing

JavaScript is a "dynamically typed language", which means that, unlike some other languages, you don't need to specify what data type a variable will contain (numbers, strings, arrays, etc.).

For example, if you declare a variable and give it a value enclosed in quotes, the browser treats the variable as a string:

The typeof operator

The typeof operator returns the type of the operand. It’s useful when we want to process values of different types differently or just want to do a quick check.

A call to typeof x returns a string with the type name:

typeof undefined; // "undefined"
 
typeof 0; // "number"
 
typeof 10n; // "bigint"
 
typeof true; // "boolean"
 
typeof "foo"; // "string"

The “null” value

The special null value does not belong to any of the types described above.

It forms a separate type of its own which contains only the null value:

let age = null;

In JavaScript, null is not a “reference to a non-existing object” or a “null pointer” like in some other languages.

It’s just a special value which represents “nothing”, “empty” or “value unknown”.

The code above states that age is unknown.

The “undefined” value

The special value undefined also stands apart. It makes a type of its own, just like null.

The meaning of undefined is “value is not assigned”.

If a variable is declared, but not assigned, then its value is undefined:

let age;
 
alert(age); // shows "undefined"

Technically, it is possible to explicitly assign undefined to a variable but we don’t recommend doing that. Normally, one uses null to assign an “empty” or “unknown” value to a variable, while undefined is reserved as a default initial value for unassigned things.

Math operations

5 % 2; // 1 is the remainder of 5 divided by 2
5 ** 2; // 25 is 5 raised to the second power
5 + 2; // 7
5 - 2; // 3
5 * 2; // 10
5 / 2; // 2.5