JavaScript image hero banner.

Hi, I'm Elmar Chavez

Let's Learn JavaScript

Learning JavaScript opens the door to creating dynamic, interactive websites and is a fundamental skill for anyone interested in web development.

My name is Elmar Chavez, and I invite you to join me on this journey as we explore and learn JavaScript together.

Start Learning

Introduction

JavaScript is the programming language of the web. It can update and change both HTML and CSS. It can calculate, manipulate and validate data.

JavaScript is one of the 3 languages all web developers must learn:

  • HTML to define the content of web pages
  • CSS to specify the layout of web pages
  • JavaScript to program the behavior of web pages

JavaScript Can Change HTML Content

One of many JavaScript HTML methods is

getElementById()

The example below "finds" an HTML element (with id="introduction__demo1"), and changes the element content (innerHTML) whilst uncovering a secret:

Demo 1: What Can JavaScript Do?

I will tell you a secret.

Explanation:

JavaScript Can Change HTML Attribute Values

In this example JavaScript changes the value of the src (source) attribute of an img tag:

Demo 2: Turn The Bulb On and Off

JavaScript can change HTML attribute values.

In this case JavaScript changes the value of the src (source) attribute of an image.

Light bulb turned off.

Explanation:

JavaScript Can Change HTML Styles (CSS)

Changing the style of an HTML element, is a variant of changing an HTML attribute:

Demo 3: Change the Style of the p Element Below

Cogito ergo sum.

Explanation:

JavaScript Can Show/Hide HTML Elements

Showing and hiding HTML elements can be done by changing the display style:

Demo 4: Make the ghost disappear

Cartoon ghost image.

Explanation:

Where To

JavaScript can be placed and executed in various parts of a web project, depending on the desired functionality and structure.

It can be embedded directly within HTML using <script> tags, placed in the <head> or at the end of the <body> for different loading behaviors, or kept in separate external .js files for better organization and reusability.

Understanding where to put JavaScript in a web page is key to optimizing performance, maintaining code clarity, and ensuring correct execution timing.

The <script> Tag

In HTML, JavaScript code is inserted between the script tags:

<script> document.getElementById("demo").innerHTML = "My First JavaScript"; </script>

JavaScript Functions and Events

A JavaScript function is a block of JavaScript code, that can be executed when "called" for.

For example, a function can be called when an event occurs, like when the user clicks a button.

JavaScript in <head> or <body>

You can place any number of scripts in an HTML document.

Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.

External JavaScript

Scripts can also be placed in external files:

function myFunction() { document.getElementById("demo").innerHTML = "Paragraph changed."; }

External scripts are practical when the same code is used in many different web pages.

JavaScript files have the file extension .js.

To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:

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

You can place an external script reference in <head> or <body> as you like.

The script will behave as if it was located exactly where the <script> tag is located.

External JavaScript Advantages

Placing scripts in external files has some advantages:

  • It separates HTML and code
  • It makes HTML and JavaScript easier to read and maintain
  • Cached JavaScript files can speed up page loads

To add several script files to one page - use several script tags:

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

External References

An external script can be referenced in 3 different ways:

  • With a full URL (a full web address)
  • With a file path (like /js/)
  • Without any path

This example uses a full URL to link to myScript.js:

<script src="https://www.w3schools.com/js/myScript.js"></script>

This example uses a file path to link to myScript.js:

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

This example uses no path to link to myScript.js:

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

Output

JavaScript output refers to the various ways in which a JavaScript program communicates information to the user or to another system.

Understanding JavaScript output is essential for effective debugging, user interaction, and dynamic content rendering on web pages.

JavaScript Display Possibilities

JavaScript can "display" data in different ways:

  • Writing into an HTML element, using innerHTML or innerText.
  • Writing into the HTML output using document.write().
  • Writing into an alert box, using window.alert().
  • Writing into the browser console, using console.log().

Using innerHTML

To access an HTML element, you can use the document.getElementById(id) method.

Use the id attribute to identify the HTML element.

Then use the innerHTML property to change the HTML content of the HTML element:

Demo 1: Transform the p element to a button element

I want to be a button element!

Explanation:

Note:

Changing the innerHTML property of an HTML element is the most common way to display data in HTML.

Using innerText

To access an HTML element, use the document.getElementById(id) method.

Then use the innerText property to change the inner text of the HTML element:

Demo 2: Change the text message

Arrivederci

Explanation:

Note:

Use innerHTML when you want to change an HTML element.

Use innerText when you only want to change the plain text.

Using document.write()

For testing purposes, it is convenient to use document.write():

Demo 3: What is 23 + 46?

Explanation:

Note:

Using document.write() after an HTML document is loaded, will delete all existing HTML:

Demo 4: Don't click the button

Explanation:

Using window.alert()

You can use an alert box to display data:

Demo 5: Alert Box Quote

Click the button below to receive a quote:

Explanation:

You can skip the window keyword.

In JavaScript, the window object is the global scope object.

This means that variables, properties, and methods by default belong to the window object.

This also means that specifying the window keyword is optional.

Using console.log()

For debugging purposes, you can call the console.log() method in the browser to display data.

Press F12 to activate debugging.

Then select "Console" in the debugger menu.

Then click Run again.

JavaScript Print

JavaScript does not have any print object or print methods.

You cannot access output devices from JavaScript.

The only exception is that you can call the window.print() method in the browser to print the content of the current window:

Demo 6: Print this site

Explanation:

JavaScript Statements

A JavaScript program is a list of statements to be executed by a computer.

JavaScript statements are the building blocks of a script.

Statements

Each statement performs a specific action, such as declaring a variable, making a decision with if, looping through data, or calling a function:

Demo 1: What's the value of "z"?

If x is 23 and y is 46 and z = x + y, what is the value of z?

The value of z is ___.

Explanation:

JavaScript statements are composed of:

  • Values
  • Operators
  • Expressions
  • Keywords
  • Comments

Most JavaScript programs contain many JavaScript statements.

The statements are executed, one by one, in the same order as they are written.

JavaScript programs and JavaScript statements are often called JavaScript code.

Semicolons ;

Semicolons separate JavaScript statements.

Add a semicolon at the end of each executable statement:

let a, b, c; a = 5; b = 6; c = a + b;

When separated by semicolons, multiple statements on one line are allowed:

a = 5; b = 6; c = a + b;

JavaScript White Space

JavaScript ignores multiple spaces. You can add white space to your script to make it more readable.

The following lines are equivalent:

let person = "Hege"; let person="Hege";

A good practice is to put spaces around operators ( = + - * / ):

let x = y + z;

JavaScript Line Length and Line Breaks

For best readability, programmers often like to avoid code lines longer than 80 characters.

If a JavaScript statement does not fit on one line, the best place to break it is after an operator:

document.getElementById("demo").innerHTML = "Hello Dolly!";

JavaScript Code Blocks

JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.

The purpose of code blocks is to define statements to be executed together.

One place you will find statements grouped together in blocks, is in JavaScript functions:

Demo 2: Change my background color

Change the background color of this demo box by clicking the button.

Explanation:

JavaScript Keywords

JavaScript statements often start with a keyword to identify the JavaScript action to be performed.

Here is a list of some of the keywords you will learn about in this tutorial:

JavaScript Keywords
Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant
if Marks a block of statements to be executed on a condition
switch Marks a block of statements to be executed in different cases
for Marks a block of statements to be executed in a loop
function Declares a function
return Exits a function
try Implements error handling to a block of statements

JavaScript keywords are reserved words.

Reserved words cannot be used as names for variables.

JavaScript Syntax

JavaScript syntax is the set of rules, how JavaScript programs are constructed:

// How to create variables: var x; let y; // How to use variables: x = 5; y = 6; let z = x + y;

It includes the proper use of keywords, variables, operators, punctuation, and structure for statements and functions.

Understanding JavaScript syntax is essential for writing clean, error-free, and functional code that the JavaScript engine can execute correctly.

JavaScript Values

The JavaScript syntax defines two types of values:

  • Fixed values
  • Variable values

Fixed values are called literals.

Variable values are called variables.

JavaScript Literals

The two most important syntax rules for fixed values are:

  • Numbers are written with or without decimals:
  • Strings are text, written within double or single quotes:

Demo 1: Numbers and Strings

Make me a number!

Explanation:

JavaScript Variables

In a programming language, variables are used to store data values.

JavaScript uses the keywords var, let and const to declare variables.

An equal sign is used to assign values to variables.

In the code below, x is defined as a variable. Then, x is assigned (given) the value 69:

let x; x = 69;

JavaScript Operators

JavaScript uses arithmetic operators ( + - * / ) to compute values.

JavaScript uses an assignment operator ( = ) to assign values to variables:

Demo 2: Math 101

What is 69 + 32?

Answer: ___

Explanation:

JavaScript Expressions

An expression is a combination of values, variables, and operators, which computes to a value.

The computation is called an evaluation.

The following are examples of expressions and their evaluations:

Demo 3: Expressions, Evaluations, and

Compute: 5269 + 3731

Evaluation: ____

If x is 17,892,288.260869565217391304347826, what is x multiplied by 69?

Evaluation: ____

Complete this meme sentence:

Nappa: Vegeta, what does the scouter say about his power level?

Vegeta: __________________

Explanation:

JavaScript Keywords

JavaScript keywords are used to identify actions to be performed.

The let keyword tells the browser to create variables:

let x, y; x = 6 + 9; y = x * 777;

The var keyword also tells the browser to create variables:

var x, y; x = 6 + 9; y = x * 9000;

In these examples, using var or let will produce the same result.

We will learn more about these two later in this tutorial.

JavaScript Comments

Not all JavaScript statements are "executed".

Code after double slashes // or between /* and */ is treated as a comment.

Comments are ignored, and will not be executed:

Demo 4: A Quote A Day makes Bad Comments Go Away

Quote:

Explanation:

JavaScript Identifiers / Names

Identifiers are JavaScript names.

Identifiers are used to name variables and keywords, and functions.

The rules for legal names are the same in most programming languages.

A JavaScript name must begin with:

  • A letter (A-Z or a-z)
  • A dollar sign ($)
  • Or an underscore (_)

Subsequent characters may be letters, digits, underscores, or dollar signs.

Note:

Numbers are not allowed as the first character in names.

This way JavaScript can easily distinguish identifiers from numbers.

JavaScript is Case Sensitive

All JavaScript identifiers are case sensitive.

The variables JoeMama and joeMama, are two different variables:

let JoeMama, joeMama; JoeMama = "Joe mama so big..."; joeMama = "...NASA thought she was a new planet.";

We can assign different values to each since they are not the same.

Note:

JavaScript does not interpret LET or Let as the keyword let.

JavaScript and Camel Case

Hyphens:

first-name, last-name, master-card, inter-city.

Underscore:

first_name, last_name, master_card, inter_city.

Upper Camel Case (Pascal Case):

FirstName, LastName, MasterCard, InterCity.

Lower Camel Case:

firstName, lastName, masterCard, interCity.

This last one is what programmers tend to use which is the camel case that starts with a lowercase letter.

JavaScript Character Set

JavaScript uses the Unicode character set.

Unicode covers almost all the characters, punctuations, and symbols in the world.

For a closer look, please study the Complete Unicode Reference from W3Schools.com.

JavaScript Comments

JavaScript comments can be used to explain JavaScript code, and to make it more readable.

JavaScript comments can also be used to prevent execution, when testing alternative code.

Single Line Comments

Single line comments start with //.

Any text between // and the end of the line will be ignored by JavaScript (will not be executed).

This example uses a single-line comment before each code line:

// Change heading: document.getElementById("myH").innerHTML = "My First Page"; // Change paragraph: document.getElementById("myP").innerHTML = "My first paragraph.";

This example uses a single line comment at the end of each line to explain the code:

let x = 5; // Declare x, give it the value of 5 let y = x + 2; // Declare y, give it the value of x + 2

Multi-line Comments

Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored by JavaScript.

This example uses a multi-line comment (a comment block) to explain the code:

/* The code below will change the heading with id = "myH" and the paragraph with id = "myP" in my web page: */ document.getElementById("myH").innerHTML = "My First Page"; document.getElementById("myP").innerHTML = "My first paragraph.";

Note:

It is most common to use single line comments.

Block comments are often used for formal documentation.

Using Comments to Prevent Execution

Using comments to prevent execution of code is suitable for code testing.

Adding // in front of a code line changes the code lines from an executable line to a comment.

This example uses // to prevent execution of one of the code lines:

//document.getElementById("myH").innerHTML = "My First Page"; document.getElementById("myP").innerHTML = "My first paragraph.";

This example uses a comment block to prevent execution of multiple lines:

/* document.getElementById("myH").innerHTML = "My First Page"; document.getElementById("myP").innerHTML = "My first paragraph."; */

JavaScript Variables

JavaScript variables are used to store data values that can be referenced and manipulated throughout a program.

They act as named containers for data, and can hold different types of values such as numbers, strings, objects, or functions.

Variables are Containers for Storing Data

JavaScript variables can be declared in 4 ways:

  • Automatically
  • Using var
  • Using let
  • Using const

In this first example, x, y, and z are undeclared variables.

They are automatically declared when first used:

x = 5; y = 6; z = x + y;

Note:

It is considered good programming practice to always declare variables before use.

From the examples you can guess:

  • x stores the value 5
  • y stores the value 6
  • z stores the value 11

Example using var:

var x = 5; var y = 6; var z = x + y;

Note:

The var keyword was used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

The var keyword should only be used in code written for older browsers.

Example using let:

let x = 5; let y = 6; let z = x + y;

Example using const:

const x = 5; const y = 6; const z = x + y;

Mixed example:

const price1 = 5; const price2 = 6; let total = price1 + price2;

The two variables price1 and price2 are declared with the const keyword.

These are constant values and cannot be changed.

The variable total is declared with the let keyword.

The value total can be changed.

When to Use var, let, or const?

  • Always declare variables
  • Always use const if the value should not be changed
  • Always use const if the type should not be changed (Arrays and Objects)
  • Only use let if you can't use const
  • Only use var if you MUST support old browsers.

Just Like Algebra

Just like in algebra, variables hold values:

let x = 5; let y = 6;

Just like in algebra, variables are used in expressions:

let z = x + y;

From the example above, you can guess that the total is calculated to be 11.

JavaScript Identifiers

All JavaScript variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter.
  • Names can also begin with $ and _ (but we will not use it in this tutorial).
  • Names are case sensitive (y and Y are different variables).
  • Reserved words (like JavaScript keywords) cannot be used as names.

The Assignment Operator

In JavaScript, the equal sign = is an "assignment" operator, not an "equal to" operator.

This is different from algebra. The following does not make sense in algebra:

x = x + 5;

In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.

It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.

Demo 1: Make it make sense

Assign x with (x + 5) * (x + 5).

What's x if its initial value is 5?

x =

Explanation:

Note:

The "equal to" operator is written like == in JavaScript.

JavaScript Data Types

JavaScript variables can hold numbers like 100 and text values like "John Doe".

In programming, text values are called text strings.

JavaScript can handle many types of data, but for now, just think of numbers and strings.

Strings are written inside double or single quotes. Numbers are written without quotes.

If you put a number in quotes, it will be treated as a text string.

Declaring a JavaScript Variable

Creating a variable in JavaScript is called "declaring" a variable.

You declare a JavaScript variable with the var or the let keyword:

var carName; let carName;

After the declaration, the variable has no value (technically it is undefined).

To assign a value to the variable, use the equal sign:

carName = "Volvo";

You can also assign a value to the variable when you declare it:

let carName = "Volvo";

In the example below, we create a variable called carName and assign the value "Volvo" to it.

Then we "output" the value inside an HTML paragraph with id="demo":

let carName = "Volvo"; document.getElementById("demo").innerHTML = carName;

Note:

It's a good programming practice to declare all variables at the beginning of a script.

One Statement, Many Variables

You can declare many variables in one statement.

Start the statement with let and separate the variables by comma:

let person = "John Doe", carName = "Volvo", price = 200;

A declaration can span multiple lines:

let person = "John Doe", carName = "Volvo", price = 200;

Value = undefined

In computer programs, variables are often declared without a value.

The value can be something that has to be calculated, or something that will be provided later, like user input.

A variable declared without a value will have the value undefined.

The demo below showcases the value undefined:

Demo 2: What's my value?

What is x + y?

x =

y =

x + y =

Explanation:

Re-Declaring JavaScript Variables

If you re-declare a JavaScript variable declared with var, it will not lose its value.

The variable carName will still have the value "Volvo" after the execution of these statements:

var carName = "Volvo"; var carName;

Note:

You cannot re-declare a variable declared with let or const.

This will not work:

let carName = "Volvo"; let carName;

This is because var is function-scoped while let and const are block-scoped.

This means that function-scoped are tied to the entire function or global scope where its defined.

In the old JavaScript days, var was always allowed to be redeclared

Block-scoped are designed to prevent accidental redeclarations and improve clarity.

Also, variables declared by let and const are not accessible before declaration which minimizes bugs caused by premature access or redeclarations.

JavaScript Arithmetic

As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:

let x = 5 + 2 + 3;

You can also add strings, but strings will be concatenated.

The x variable from the code below will return a string value of "John Cena":

let x = "John" + " " + "Cena";

We can also add strings and number values together. Let's try the demo below and see if you can guess the values of the given expressions:

Demo 3: Guess my value

1. What's the return value of x if it is coded like so:

x = "1" + 2 + 3;

Value: ?

2. What's the return value of x if it is coded like so:

x = 1 + 2 + "3";

Value: ?

3. What's the return value of x if it is coded like so:

x = 1 + "2" + 3;

Value: ?

Explanation:

JavaScript Dollar Sign $

Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names:

let $ = "Hello World"; let $$$ = 2; let $myMoney = 5;

Using the dollar sign is not very common in JavaScript, but professional programmers often use it as an alias for the main function in a JavaScript library.

In the JavaScript library jQuery, for instance, the main function $ is used to select HTML elements.

In jQuery, the code below means "select all p elements":

$("p");

JavaScript Underscore (_)

Since JavaScript treats underscore as a letter, identifiers containing _ are valid variable names:

let _lastName = "Johnson"; let _x = 2; let _100 = 5;

Using the underscore is not very common in JavaScript, but a convention among professional programmers is to use it as an alias for "private (hidden)" variables.

JavaScript Let

The let keyword was introduced in ES6 (2015)

Variables declared with let have Block Scope

Variables declared with let must be Declared before use

Variables declared with let cannot be Redeclared in the same scope

Block Scope

Before ES6 (2015), JavaScript did not have Block Scope.

JavaScript had Global Scope and Function Scope.

ES6 introduced the two new JavaScript keywords: let and const.

These two keywords provided Block Scope in JavaScript.

Variables declared inside a { } block cannot be accessed from outside the block:

{ let x = 2; } // x can NOT be used here

Global Scope

Variables declared with the var always have Global Scope.

Variables declared with the var keyword can NOT have block scope:

Variables declared with varinside a { } block can be accessed from outside the block:

{ var x = 2; } // x CAN be used here

Cannot be Redeclared

Variables defined with let can not be redeclared.

You can not accidentally redeclare a variable declared with let.

With let you can not do this:

let x = "John Doe"; let x = 0;

Variables defined with var can be redeclared.

var x = "John Doe"; var x = 0;

Redeclaring Variables

Redeclaring a variable using the var keyword can impose problems.

Redeclaring a variable inside a block will also redeclare the variable outside the block:

var x = 10; // Here x is 10 { var x = 2; // Here x is 2 } // Here x is 2

Redeclaring a variable using the let keyword can solve this problem.

Redeclaring a variable inside a block will not redeclare the variable outside the block:

let x = 10; // Here x is 10 { let x = 2; // Here x is 2 } // Here x is 10

Difference Between var, let and const

Table for the difference between var, let, and const
Keyword Scope Redeclare Reassign Hoisted Binds this
var No Yes Yes Yes Yes
let Yes No Yes No No
const Yes No No No No

What is good?

  • let and const have block scope.
  • let and const can not be redeclared.
  • let and const must be declared before use.
  • let and const does not bind to this.
  • let and const are not hoisted.

What is not good?

  • var does not have to be declared.
  • var is hoisted.
  • var binds to this.

Redeclaring

Redeclaring a JavaScript variable with var is allowed anywhere in a program:

var x = 2; // Now x is 2 var x = 3; // Now x is 3

With let, redeclaring a variable in the same block is NOT allowed:

var x = 2; // Allowed let x = 3; // Not allowed { let x = 2; // Allowed let x = 3; // Not allowed } { let x = 2; // Allowed var x = 3; // Not allowed }

Redeclaring a variable with let, in another block, IS allowed:

let x = 2; // Allowed { let x = 3; // Allowed } { let x = 4; // Allowed }

Let Hoisting

Variables defined with var are hoisted to the top and can be initialized at any time.

Meaning: You can use the variable before it is declared:

carName = "Volvo"; //the variable is assigned a value before being declared var carName; //the variable is just being declared here

If you want to learn more about hoisting, study the chapter JavaScript Hoisting.

Variables defined with let are also hoisted to the top of the block, but not initialized.

Meaning: Using a let variable before it is declared will result in a ReferenceError:

carName = "Saab"; let carName = "Volvo";

Javascript will throw this error to you:

ReferenceError: Cannot access 'carName' before initialization

JavaScript Const

The const keyword was introduced in ES6 (2015)

Variables defined with const cannot be Redeclared

Variables defined with const cannot be Reassigned

Variables defined with const have Block Scope

Cannot be Reassigned

A variable defined with the const keyword cannot be reassigned:

Demo 1: One assignment is enough

The variable pi is declared using const is assigned with 3.14

What is the new value of pi if:

pi = 7 + 8 + pi;

pi = ?

Explanation:

Must be Assigned

JavaScript const variables must be assigned a value when they are declared.

This is CORRECT:

const PI = 3.14159265359;

This is INCORRECT:

const PI; PI = 3.14159265359;

When to use JavaScript const?

Always declare a variable with const when you know that the value should not be changed.

Use const when you declare:

  • A new Array
  • A new Object
  • A new Function
  • A new RegExp

Constant Objects and Arrays

The keyword const is a little misleading.

It does not define a constant value. It defines a constant reference to a value.

Because of this you can NOT:

  • Reassign a constant value
  • Reassign a constant array
  • Reassign a constant object

But you CAN:

  • Change the elements of constant array
  • Change the properties of constant object

Constant Arrays

You can change the elements of a constant array:

Demo 2: Gear up with Arrays

You are a manager for a store that sells high-quality gaming PC's.

The store contains the following brands:

  • Alienware
  • ROG
  • MSI
  • Corsair
  • NZXT
  • HP OMEN
  • Lenovo Legion
  • CyberPowerPC
  • iBUYPOWER

The store owner wants you to rearrange the shelf items so that the first shelf contains the brand "ROG" instead and not "Alienware".

He also wants you to add another brand to sell in the store named Maingear.

You're not allowed to replace the store itself — just rearrange the products inside.

New Order:

Explanation:

Again, you cannot reassign the const array.

const cars = ["Saab", "Volvo", "BMW"]; cars = ["Toyota", "Volvo", "Audi"]; // ERROR

Constant Objects

You can change the properties of a constant object:

Demo 3: Hook up your gaming PC

Your gaming PC is running slow and you want to upgrade its parts.

These are its current specifications:

  • CPU: Intel Core i5-4690K
  • RAM: 16 GB
  • Storage: SSD 512 GB
  • GPU: RTX 4060 Ti

You've earned enough money to upgrade your setup so you finally hit the store. (You deserve it!)

Explanation:

Again, you cannot reassign constant objects.

const car = {type:"Fiat", model:"500", color:"white"}; car = {type:"Volvo", model:"EX60", color:"red"}; // ERROR

JavaScript Operators

JavaScript operators are used to perform different types of mathematical and logical computations.

The following are some examples:

  • The Assignment Operator = assigns values
  • The Addition Operator + adds values
  • The Multiplication Operator * multiplies values
  • The Comparison Operator > compares values

JavaScript Assignment

The Assignment Operator (=) assigns a value to a variable:

// Assign the value 5 to x let x = 5; // Assign the value 2 to y let y = 2; // Assign the value x + y to z: let z = x + y;

JavaScript Addition & Multiplication

The Addition Operator (+) adds numbers:

let x = 5; let y = 2; let z = x + y;

The value of z would become 7.

The Multiplication Operator (*) multiplies numbers:

let x = 5; let y = 2; let z = x * y;

The value of z would become 10.

Types of JavaScript Operators

There are different types of JavaScript operators:

  • Arithmetic Operators
  • Assignment Operators
  • Comparison Operators
  • String Operators
  • Logical Operators
  • Bitwise Operators
  • Ternary Operators
  • Type Operators

JavaScript Arithmetic Operators

Arithmetic Operators are used to perform arithmetic on numbers:

let a = 3; let x = (100 + 50) * a;

A typical arithmetic operation takes two numbers (or expressions) and produces a new number.

The final value of x would become 450.

Arithmetic Operators
Operator Descriptor
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement

Note:

Arithmetic operators are fully described in the later topics.

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables.

The Addition Assignment Operator (+=) adds a value to a variable.

let x = 10; x += 5;

Now the final value of x would become 15.

The following is a table of assignment operators:

Assignment Operators
Operator Example Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
**= x **= y x = x ** y

Note:

Assignment operators will be fully discussed in later topics.

JavaScript Comparison Operators

The following is a table for comparison operators:

Comparison Operators
Operator Description
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator

Note:

Comparison operators will be fully discussed in later topics.

JavaScript String Comparison

All the comparison operators above can also be used on strings:

let text1 = "A"; let text2 = "B"; let result = text1 < text2;

The result variable returns a boolean value and checks if text1 is less than text2.

This happens because JavaScript compares string values alphabetically.

So in the code example above, the result variable will have a value of true since "A" comes before "B" like when the number 1 comes before 2.

Let's look at another example:

let text1 = "20"; let text2 = "5"; let result = text1 < text2;

Remember, we are comparing strings since both "20" and "5" are enclosed in quotes.

Alphabetically "20" comes before "5" just like when "apple" comes before "b".

Therefore, the result variable will also return a value of true.

JavaScript String Addition

The + can also be used to add (concatenate) strings:

let text1 = "John"; let text2 = "Cena"; let text3 = text1 + " " + text2;

In this code, we concatenated or joined the string value of text1, a string of value " " (a space), and lastly the string value of text2.

The resulting string value for text3 will become "John Cena".

The += assignment operator can also be used to add (concatenate) strings:

let text1 = "What a very "; text1 += "nice day";

In this example, we initially assigned a value for text1 with a string of "What a very".

Then we used += to add a string value of "nice day" to its initial value.

Finally, the resulting value for text1 will become "What a very nice day"

Note:

When used on strings, the + operator is called the concatenation operator.

Adding Strings and Numbers

Adding two numbers, will return the sum as a number like 5 + 5 = 10.

Adding a number and a string, will return the sum as a concatenated string like 5 + "5" = "55".

The following is an example code:

let x = 5 + 5; let y = "5" + 5; let z = 5 + "Hello";

First, the value of x will become 10 since it has no strings as one of its operands.

Second, the value of y will become "55" since one of the operands is a string.

Lastly, the value of z will become "5Hello" since one of the operands is a string even if it comes last.

Note:

If you add a number and a string, the result will be a string!

JavaScript Logical, Type, & Bitwise Operators

Below is a table for logical operators:

Logical Operators
Operator Description
&& logical and
|| logical or
! logical not

Note:

Logical operators will be full discussed in later topics.

Next, we have the table for type operators:

Type Operators
Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an instance of an object type

Note:

Type operators will be fully discussed in later topics.

Lastly we have the table for bitwise operators:

Bitwise Operators
Operator Description Example
& AND 6 & 9
| OR 6 | 9
~ NOT ~ 69
^ XOR 6 ^ 9
<< left shift 6 << 9
>> right shift 6 >> 9
>>> unsigned right shift 6 >>> 9

Note:

Bitwise operators will be fully discussed in later topics.

JavaScript Arithmetic

JavaScript arithmetic refers to the use of mathematical operations—like addition, subtraction, multiplication, and division to perform calculations.

Whether you're updating a score in a game, calculating a total price, or adjusting values in a script, arithmetic is a fundamental part of writing dynamic and interactive JavaScript code.

JavaScript Arithmetic Operators

Arithmetic operators perform arithmetic on numbers (literals or variables):

Arithmetic Operators
Operator Descriptor
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement

Arithmetic Operations

A typical arithmetic operation operates on two numbers.

The two numbers can be literals:

let x = 100 + 50;

The two numbers can also be variables:

let x = a + b;

They can also be both expressions:

let x = (100 + 50) * a;

Operators and Operands

The numbers (in an arithmetic operation) are called operands.

The operation (to be performed between the two operands) is defined by an operator.

let x = 6 + 9;

The operands in the expression above are 6 and 9 while + is the operator.

Operator Types

From the table presented under this topic, we can see multiple types of operations.

Let's discuss each of the operations with the demo below:

Demo 1: Emergency Operation! Call the Doctor!

You are a doctor and your hospital currently has 206 patients.

After three hours, your hospital admitted an influx of 18 patients due to an unfortunate fire accident.

Quick, what's the total number of patients your hospital currently accomodates now?

Total: ?

Your hospital has a maximum patient capacity of 248 patients.

What's the number of available patient slots left?

Available Slots: ?

Since the hospital is packed, you are immediately needed in the emergency room.

You need to give the right medicine dosage for a patient.

The medicine prescriptions reads 5 mg per kg of the patient's body weight.

Your nurses weighed the patient beforehand and gave you a stat of 75kg.

What's the right prescription to give?

Amount of medicine: ?

After that, you were tasked to find the ratio of the systolic pressure to the diastolic pressure of a patient next room.

The patient's data tells you that he has 135/85 mmHg which is rated as high blood pressure.

What's his ratio: ?

Now, your nurse tells you to go to the next room where you will be prescribing pill dosages.

The patient needs 3 pills a day and your hospital pharmacy only has 50 pills left.

Compute the number of pills you will take away to make sure your patient takes in exactly what's prescribed.

Take away: ?

We have been informed that the next room have a total of 5 patients and we are tasked to carry out the number of patients left if for the next 3 days, a new patient is admitted and then for the next 2 days, a patient will be discharged.

Total: ?

There's a bacteria outbreak in your hospital lab and you need to compute the bacteria population for the upcoming hours for a planned bacteria containment.

If the initial number of bacteria is 10 and it doubles every hour, what is the final bacteria population after 5 hours.

Bacteria Population: ?

Explanation:

Operator Precedence

Operator precedence describes the order in which operations are performed in an arithmetic expression:

let x = 100 + 50 * 3;

Is the result of example above the same as 150 * 3, or is it the same as 100 + 150?

Is the addition or the multiplication done first?

As in traditional school mathematics, the multiplication is done first.

Multiplication (*) and division (/) have higher precedence than addition (+) and subtraction (-).

And (as in school mathematics) the precedence can be changed by using parentheses.

When using parentheses, the operations inside the parentheses are computed first:

let x = (100 + 50) * 3;

This code will do addition first then multiplication.

When many operations have the same precedence (like addition and subtraction or multiplication and division), they are computed from left to right:

let x = 100 + 50 - 3; let x = 100 / 50 * 3;

Note:

Operator precedence will be discussed more in later topics.

JavaScript Assignment

In JavaScript, assignment is the process of storing a value in a variable.

It's one of the most fundamental operations in programming.

Without it, a program can't remember or manipulate data.

JavaScript Assignment Operators

Assignment operators assign values to JavaScript variables:

Assingnment Operators Table
Operator Example Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
**= x **= y x = x ** y

Shift Assignment Operators

Shift assignment operators converts values to 32-bit format and shifts it and then converts it back to its decimal form.

Shift Assignment Operators
Operator Example Same As
<<= x <<= y x = x << y
>>= x >>= y x = x >> y
>>>= x >>>= y x = x >>> y

Bitwise Assignment Operators

Bitwise assignment operators converts values to 32-bit format and then compares them using bitwise operators then converts it back to decimal form.

Bitwise Assignment Operators
Operator Example Same As
&= x &= y x = x & y
^= x ^= y x = x ^ y
|= x |= y x = x | y

Logical Assignment Operators

Logical assignment operators compares the two values if they are true or false and then returns a boolean value.

Logical Assignment Operators
Operator Example Same As
&&= x &&= y x = x && (x = y)
||= x ||= y x = x || (x = y)
??= x ??= y x = x ?? (x = y)

The = Operator

The Simple Assignment Operator assigns a value to a variable:

let x = 10; //value of x is 10

The += Operator

The Addition Assignment Operator adds a value to a variable.

let x = 10; //x has a value of 10 x += 5; //x now has a value of 15

The variable x now has a value of 15 since the += operator assigns the value of x to be itself (x) plus 5.

Since the initial value of x is 10, the final expression is 10 + 5 which becomes 15.

We can also do this with strings as well:

let text = "Hello"; text += " World";

The final value of text would become "Hello World".

The -= Operator

The Subtraction Assignment Operator subtracts a value from a variable:

let x = 10; //x has a value of 10 x -= 5; //x now has a value of 5

The variable x now has a value of 5 since the -= operator assigns the value of x to be itself (x) minus 5.

Since the initial value of x is 10, the final expression is 10 - 5 which becomes 5.

The *= Operator

The Multiplication Assignment Operator multiplies a variable:

let x = 10; //x has a value of 10 x *= 5; //x now has a value of 50

The variable x now has a value of 50 since the *= operator assigns the value of x to be itself (x) multiplied by 5.

Since the initial value of x is 10, the final expression is 10 * 5 which becomes 50.

The **= Operator

The Exponentiation Assignment Operator raises a variable to the power of the operand:

let x = 10; //x has a value of 10 x **= 5; //x now has a value of 100,000

The variable x now has a value of 100,000 since the **= operator assigns the value of x to be itself (x) raised exponentially by 5.

Since the initial value of x is 10, the final expression is 10 ** 5 which becomes 100,000.

The /= Operator

The Division Assignment Operator divides a variable:

let x = 10; //x has a value of 10 x /= 5; //x now has a value of 2

The variable x now has a value of 2 since the /= operator assigns the value of x to be itself (x) divided by 5.

Since the initial value of x is 10, the final expression is 10 / 5 which becomes 2.

The %= Operator

The Remainder Assignment Operator assigns a remainder to a variable.

let x = 10; //x has a value of 10 x %= 5; //x now has a value of 0

The variable x now has a value of 0 since the %= operator assigns the value of x to be the remainder of itself (x) divided by 5.

Since the initial value of x is 10, the final value will become the remainder of 10 / 5 which is 0.

The <<= Operator

The Left Shift Assignment Operator left shifts a variable:

let x = -100; //x has a value of -100 x <<= 5; //x now has a value of -3200

The variable x now has a value of -3200 since the <<= operator assigns the value of x to be itself (x), converts it to binary and then shifted to the left by 5 places.

Since the initial value of x is 10, it will be converted to binary and then shifted to the left by 5 places and then convert the value back to decimal yielding -3200.

The >>= Operator

The Right Shift Assignment Operator right shifts a variable (signed).

let x = -100; //x has a value of -100 x >>= 5; //x now has a value of -4

The variable x now has a value of -4 since the >>= operator assigns the value of x to be itself (x), converts it to binary and then shifted to the right by 5 places.

Since the initial value of x is 10, it will be converted to binary and then shifted to the right by 5 places and then convert the value back to decimal yielding -4.

The >>>= Operator

The Unsigned Right Shift Assignment Operator right shifts a variable (unsigned).

let x = -100; //x has a value of -100 x >>>= 5; //x now has a value of 134,217,724

The variable x now has a value of 134,217,724 since the >>>= operator assigns the value of x to be itself (x), converts it to binary and then shifted to the right by 5 places without regards to its original sign.

Since the initial value of x is 10, it will be converted to binary and then shifted to the right by 5 places and then convert the value back to decimal yielding 134,217,724.

The &= Operator

The Bitwise AND Assignment Operator does a bitwise AND operation on two operands and assigns the result to the variable.

let x = 10; //x has a value of 10 x &= 5; //x now has a value of 4

The variable x now has a value of 4 since the &= operator assigns the value of x to be the resulting decimal of the binary form of itself (x) and then used the & operator to the binary form of 5.

Since the initial value of x is 10, the expression (10 & 5) will yield a decimal value of 4.

The |= Operator

The Bitwise OR Assignment Operator does a bitwise OR operation on two operands and assigns the result to the variable.

let x = 10; //x has a value of 10 x |= 5; //x now has a value of 101

The variable x now has a value of 101 since the |= operator assigns the value of x to be the resulting decimal of the binary form of itself (x) and then used the | operator to the binary form of 5.

Since the initial value of x is 10, the expression (10 | 5) will yield a decimal value of 101.

The ^= Operator

The Bitwise XOR Assignment Operator does a bitwise XOR operation on two operands and assigns the result to the variable.

let x = 10; //x has a value of 10 x ^= 5; //x now has a value of 97

The variable x now has a value of 97 since the ^= operator assigns the value of x to be the resulting decimal of the binary form of itself (x) and then used the ^ operator to the binary form of 5.

Since the initial value of x is 10, the expression (10 ^ 5) will yield a decimal value of 97.

The &&= Operator

The Logical AND assignment operator is used between two values.

If the first value is true, the second value is assigned:

let x = 10; //x has the value of 10 x &&= 5; //now x has the value of 5

The variable x now has a value of 5 since the &&= operator checks if the value of the first operand which is itself (x) is true (i.e. in this case 10 is a number and is true).

Since the initial value of x is true, the &&= operator assigns the second operand which is 5 to be the final value of x


In its entire definition, the && operator returns the first falsy value it finds when it is used with multiple values.

If no false value are found or all of them are true values, then the && operator returns the last value:

let x = "a true string" && 123 && "another true string"; //x has a value of "another true string" let x = "a true string" && null && "another true string"; //x has a value of null

In the first line of code above, the variable x has a final value of "another true string" since all of the operands are true.

In the second line, the variable x has a final value of null since null is a false value.

The ||= Operator

The Logical OR assignment operator is used between two values.

If the first value is false, the second value is assigned.

let x = undefined; //x has the value of undefined x ||= 5; //now x has the value of 5

The variable x now has a value of 5 since the ||= operator checks if the value of the first operand which is itself (x) is true (i.e. in this case undefined is a false value).

Since the initial value of x is false, the ||= operator assigns the second operand which is 5 to be the final value of x.


In its entire definition, the || operator returns the first truthy value it finds when it is used with multiple values.

If no true value are found or all of them are false values, then the || operator returns the last value:

let x = null || 0 || undefined; //x has a value of undefined let x = null || "a true string" || 0; //x has a value of "a true string"

In the first line of code above, the variable x has a final value of undefined since all of the operands are false.

In the second line, the variable x has a final value of "a true string" since "a true string" is a string and contains a true value.

The ??= Operator

The Nullish coalescing assignment operator is used between two values.

If the first value is undefined or null, the second value is assigned.

let x; //x is not assigned a value thus it is undefined x ??= 5; //now x has the value of 5

The variable x now has a value of 5 since the ??= operator checks if the value of the first operand which is itself (x) is null or undefined (i.e. in this case the variable is undefined).

Since the initial value of x is undefined, the ??= operator assigns the second operand which is 5 to be the final value of x.


In its entire definition, the ?? operator returns the right-hand value only if the left-hand value is null or undefined, otherwise, it returns the left-hand value.

It ignores other falsy values like 0, false, or "".

let x = null ?? "a string" //x has a value of string let x = undefined ?? 69; //x has a value of 69 let x = 0 ?? "hello world"; //x has a value of 0

In the first two lines of code above, the variable x has a final value of "a string" and 69 since their left-hand value is null and undefined, respectively.

The last line, however, has a left-hand value of 0 which is neither null nor undefined so the final value of x is still the left-hand value which is 0.

List of False Values in JavaScript

  • false - The boolean value false
  • 0 - The number 0
  • -0 - Negative 0
  • 0n - BigInt zero
  • "" '' and `` - An empty string which includes double quotes, single quotes, backticks
  • null - Represents "no value"
  • undefined - A declared variable with no assigned value
  • NaN - "Not a Number", usually the result of invalid math

JavaScript Data Types

JavaScript has 8 Datatypes:

  • String
  • Number
  • Bigint
  • Boolean
  • Undefined
  • Null
  • Symbol
  • Object

The object data type can contain both built-in objects, and user defined objects:

Built-in object types can be:

objects, arrays, dates, maps, sets, intarrays, floatarrays, promises, and more.

The following are some examples of data types:

// Numbers: let length = 16; let weight = 7.5; // Strings: let color = "Yellow"; let lastName = "Johnson"; // Booleans let x = true; let y = false; // Object: const person = {firstName:"John", lastName:"Doe"}; // Array object: const cars = ["Saab", "Volvo", "BMW"]; // Date object: const date = new Date("2022-03-25");

Note:

A JavaScript variable can hold any type of data.

The Concept of Data Types

In programming, data types is an important concept.

To be able to operate on variables, it is important to know something about the type.

Without data types, a computer cannot safely solve this:

let x = 16 + "Volvo";

Does it make any sense to add "Volvo" to 16? Will it produce an error or will it produce a result?

JavaScript will treat the example above as:

let x = "16" + "Volvo";

Note:

When adding a number and a string, JavaScript will treat the number as a string.

This process is called string coercion (type coercion) where JavaScript implicitly converts the number to a string to perform string concatenation or string joining.

There for the resulting value for x is a string with a value of "16Volvo"


JavaScript also evaluates expressions from left to right. Different sequences can produce different results:

let x = 16 + 4 + "Volvo";

The resulting value of x would be "20Volvo"

In this example, JavaScript treats 16 and 4 as numbers, adds it and storing the value as 20, until it reaches "Volvo".

This will tell JavaScript to change the process from number addition to string concatenation.

This will prompt the conversion of 20 to a string "20" through string coercion (type coercion).

Finally, performing string concatenation and giving us the value of "20Volvo".

Let's look at the second code:

let x = "Volvo" + 16 + 4;

In the second example, since the first operand is a string, all the remaining operands are treated as strings and the expression will undergo string concatenation.

Therefore, the final value for x will be "Volvo164".

JavaScript Types are Dynamic

JavaScript has dynamic types. This means that the same variable can be used to hold different data types:

let x; // Now x is undefined x = 5; // Now x is a Number x = "John"; // Now x is a String

JavaScript Strings

A string (or a text string) is a series of characters like "John Doe".

Strings are written with quotes. You can use single or double quotes:

// Using double quotes: let carName1 = "Volvo XC60"; // Using single quotes: let carName2 = 'Yamaha X20';

Both are rendered as strings.

You can also use quotes inside a string, as long as they don't match the quotes surrounding the string:

// Single quote inside double quotes: let answer1 = "It's alright"; // Single quotes inside double quotes: let answer2 = "He is called 'Johnny'"; // Double quotes inside single quotes: let answer3 = 'He is called "Johnny"';

Note:

We will learn more on strings in later topics.

JavaScript Numbers

All JavaScript numbers are stored as decimal numbers (floating point).

Numbers can be written with, or without decimals:

// With decimals: let x1 = 34.00; // Without decimals: let x2 = 34;

Exponential Notation

Extra large or extra small numbers can be written with scientific (exponential) notation:

let y = 123e5; //y has a value of 12300000 let z = 123e-5; //z has a value of 0.00123

Note:

Most programming languages have many number types.

Whole numbers (integers):

  • byte (8-bit)
  • short (16-bit)
  • int (32-bit)
  • long (64-bit)

Real numbers (floating-point):

  • float (32-bit)
  • double (64-bit)

Javascript numbers are always one type which is double (64-bit floating point).

We will learn more about numbers in later topics.

JavaScript BigInt

All JavaScript numbers are stored in a 64-bit floating-point format.

JavaScript BigInt is a new datatype (ES2020) that can be used to store integer values that are too big to be represented by a normal JavaScript Number.

let x = BigInt("123456789012345678901234567890");

The value of x has a BigInt data type.

BigInt data types cannot have decimals

We cannot perform math between BigInt and Number type.

Note:

We will learn more about BigInt data types in later topics.

JavaScript Booleans

Booleans can only have two values: true or false.

let x = 5; let y = 5; let z = 6; (x == y) // Returns true (x == z) // Returns false

Booleans are often used in conditional testing.

Note:

We will learn more about booleans in later topics.

JavaScript Arrays

JavaScript arrays are written with square brackets [].

Array items are separated by commas.

The following code declares (creates) an array called cars, containing three items (car names):

const cars = ["Saab", "Volvo", "BMW"];

Array indexes are zero-based, which means the first item is [0], second is [1], and so on.

Note:

We will learn more about arrays in later topics.

JavaScript Objects

JavaScript objects are written with curly braces {}.

Object properties are written as name:value pairs, separated by commas.

const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

The object (person) in the example above has 4 properties: firstName, lastName, age, and eyeColor.

Note:

We will learn more about objects in later topics.

The typeof Operator

You can use the JavaScript typeof operator to find the type of a JavaScript variable.

The typeof operator returns the type of a variable or an expression:

typeof "" // Returns "string" typeof "John" // Returns "string" typeof "John Doe" // Returns "string" typeof 0 // Returns "number" typeof 314 // Returns "number" typeof 3.14 // Returns "number" typeof (3) // Returns "number" typeof (3 + 4) // Returns "number"

Note:

We will learn more about the typeof operator in later topics.

Undefined

In JavaScript, a variable without a value, has the value undefined. The type is also undefined.

let car; // Value is undefined, type is undefined

Any variable can be emptied, by setting the value to undefined. The type will also be undefined.

Empty Values

An empty value has nothing to do with undefined.

An empty string has both a legal value and a type.

let car = ""; // The value is "", the typeof is "string"

JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

// Function to compute the product of p1 and p2 function myFunction(p1, p2) { return p1 * p2; }

The code above is a function with p1 and p2 as its parameters and returns an expression of p1 * p2.

When we try and call the function, say myFunction(3, 5), the resulting value would give us 15.

JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets {}:

function name(parameter1, parameter2, parameter3) { // code to be executed }

Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

Function Invocation

The code inside the function will execute when "something" invokes (calls) the function:

  • When an event occurs (when a user clicks a button)
  • When it is invoked (called) from JavaScript code
  • Automatically (self invoked)

Note:

We will learn more about function invocation in later topics.

Function Return

When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.

Functions often compute a return value. The return value is "returned" back to the "caller":

Demo 1: Resto Mania

You're the head chef of an esteemed restaurant and your waiter is about to take the order for 3 tables.

The first table ordered spring rolls, steak, wine, and pudding.

The second table ordered tacos, mashed potatoes and a vegetarian platter.

Lastly, the third table ordered soup, grilled chicken, rice, iced tea, and ice cream.

Then the order list was given to you. Can you cook (declare a function) and serve (return the value) the food the customers ordered?

First Table:
?

Second Table:
?

Third Table:
?

Explanation:

Why Functions?

With functions you can reuse code.

You can write code that can be used many times.

You can use the same code with different arguments, to produce different results.

The () Operator

The () operator invokes (calls) the function:

Demo 2: Fahrenheit to Celsius Converter

Please enter a temperature value in Fahrenheit below:

Answer: ?

Explanation:

Accessing a function with incorrect parameters can return an incorrect answer:

function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); } let value = toCelsius();

The resulting value will become NaN which is Not a Number.

Since we did not add any argument value when we called for the function toCelcius(), the value for the parameter named fahrenheit will become NaN, thus this will result of a value of also NaN when the function toCelcius() returns the value of the expression.


Accessing a function without () returns the function and not the function result:

function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); } let value = toCelsius;

The resulting value will become a string with a value of "function toCelsius(f) {; return (5/9) * (f-32); }".

Since we did not use the () operator which calls or invokes the function and its results after an execution, we only get the function object itself.

Note:

As you see from the examples above, toCelsius refers to the function object, and toCelsius() refers to the function result.

Functions Used as Variable Values

Functions can be used the same way as you use variables, in all types of formulas, assignments, and calculations.

Instead of using a variable to store the return value of a function:

let x = toCelsius(77); let text = "The temperature is " + x + " Celsius";

You can use the function directly, as a variable value:

let text = "The temperature is " + toCelsius(77) + " Celsius";

Don't worry, you will learn more about functions in later topics.

Local Variables

Variables declared within a JavaScript function, become LOCAL to the function.

Local variables can only be accessed from within the function.

// code here can NOT use carName function myFunction() { let carName = "Volvo"; // code here CAN use carName } // code here can NOT use carName

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is completed.

JavaScript Objects

In real life, objects are things like: houses, cars, people, animals, or any other subjects.

Here is a car object example:

Car Object, Properties, and Methods Table
Car Object Properties Methods
Car object example picture. car.name = Fiat car.start()
car.model = 500 car.drive()
car.weight = 850kg car.brake()
car.color = white car.stop()

Object Properties

A real life car has properties like weight and color:

  • car.name = Fiat
  • car.model = 500
  • car.weight = 850kg
  • car.color = white

Car objects have the same properties, but the values differ from car to car.

Object Methods

A real life car has methods like start and stop:

  • car.start()
  • car.drive()
  • car.brake()
  • car.stop()

Car objects have the same methods, but the methods are performed at different times.

JavaScript Variables

JavaScript variables are containers for data values.

This code assigns a simple value (Fiat) to a variable named car:

let car = "Fiat";

JavaScript Objects

Objects are variables too. But objects can contain many values.

The demo below assigns many values to an object named car:

Demo 1: *Slaps Roof of Car*

Car salesman dressed as Freddie Mercury and slapping the roof of car to a tune of 'We Will Rock You' to his customer.

You are a car salesperson and a Freddie Mercury fanatic.

You are tasked to sell a car to an inquiring customer.

As you *slap* the car to the beat of "We Will Rock You", a customer walks up and asks about its descriptions:

Customer: Freddie, what's that car you're *slapping*?

Freddie: ?

Customer: It sounds brand new. How about its engine?

Freddie: ?

Customer: That's kinda mean, Freddie. What about its total output?

Freddie: ?

Customer: Wow! That's promising. And its transmission?

Freddie: ?

Customer: That's amazing Freddie!. Can it reach great acceleration?

Freddie: ?

Customer: This is great, I think I'm buying it. What's its price?

Freddie: ?

Customer: Lead the way, thanks Freddie.

Freddie: No worries. In a moment, you'll be driving your new car . By the way, I'm not THE Freddie Mercury. You know that right?

Freddie Jonathan: I'm Jonathan who just happens to be a fan.

Customer: Huh?! Ahh yes, anything you say Freddie!. Keep it rockin' and rollin'.

Freddie (again): Sure thing, I guess... Enjoy your new ride (I got to get rid of this fake mustache for the next customer).

Explanation:

Note:

It is a common practice to declare objects with the const keyword.

JavaScript Object Definition

These are the methods to define a JavaScript Object:

  • Using an Object Literal
  • Using the new Keyword
  • Using an Object Constructor

JavaScript Object Literal

An object literal is a list of name:value pairs inside curly braces {}:

const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Note:

name:value pairs are also called key:value pairs.

Object literals are also called object initializers.

Creating a JavaScript Object

These examples create a JavaScript object with 4 properties:

// Create an Object const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Spaces and line breaks are not important. An object initializer can span multiple lines:

// Create an Object const person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue" };

This example creates an empty JavaScript object, and then adds 4 properties:

// Create an Object const person = {}; // Add Properties person.firstName = "John"; person.lastName = "Doe"; person.age = 50; person.eyeColor = "blue";

Using the new Keyword

This example create a new JavaScript object using new Object(), and then adds 4 properties:

// Create an Object const person = new Object(); // Add Properties person.firstName = "John"; person.lastName = "Doe"; person.age = 50; person.eyeColor = "blue";

Note:

The examples above do exactly the same.

But, there is no need to use new Object().

For readability, simplicity and execution speed, use the object literal method.

Object Properties

The named values, in JavaScript objects, are called properties.

Object Property and Value Pair
Property Value
firstName John
lastName Doe
age 50
eyeColor blue

Objects written as name value pairs are similar to:

  • Associative arrays in PHP
  • Dictionaries in Python
  • Hash tables in C
  • Hash maps in Java
  • Hashes in Ruby and Perl

Accessing Object Properties

You can access object properties in two ways:

objectName.propertyName; objectName["propertyName"];

Say you have an object named food.

You want to access or get what type this food is.

In this case we have the property name called type, therefore to obtain the property value, use the code below:

food.type;

We can also call the same property value using this:

food["type"];

JavaScript Object Methods

Methods are actions that can be performed on objects.

Methods are function definitions stored as property values.

Object Property and Value Pair
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function () {return this.firstName + " " + this.lastName;}

The following is an example object with a property value as an object method:

const person = { firstName: "John", lastName: "Doe", id: 5566, fullName: function() { return this.firstName + " " + this.lastName; } };

In the example above, this refers to the person object:

this.firstName means the firstName property of person.

this.lastName means the lastName property of person.

In JavaScript, Objects are King.

If you Understand Objects, you Understand JavaScript.

Objects are containers for Properties and Methods.

Properties are named Values.

Methods are Functions stored as Properties.

Properties can be primitive values, functions, or even other objects.

In JavaScript, almost "everything" is an object:

  • Objects are objects
  • Maths are objects
  • Functions are objects
  • Dates are objects
  • Arrays are objects
  • Maps are objects
  • Sets are objects

All JavaScript values, except primitives, are objects.

JavaScript Primitives

A primitive value is a value that has no properties or methods.

3.14 is a primitive value

A primitive data type is data that has a primitive value.

JavaScript defines 7 types of primitive data types:

  • string
  • number
  • boolean
  • null
  • undefined
  • symbol
  • bigint

JavaScript Primitives are Immutable

Primitive values are immutable (they are hardcoded and cannot be changed).

if x = 3.14, you can change the value of x, but you cannot change the value of 3.14:

Primitives and their Immutability
Value Type Comment
"Hello" string "Hello" is always "Hello"
3.14 number 3.14 is always 3.14
true boolean true is always true
false boolean false is always false
null null (object) null is always null
undefined undefined undefined is always undefined

JavaScript Objects are Mutable

Objects are mutable: They are addressed by reference, not by value.

If person is an object, the following statement will not create a copy of person:

const x = person;

The object x is not a copy of person. The object x is person.

The object x and the object person share the same memory address:

//Create an Object const person = { firstName:"John", lastName:"Doe", age:50, eyeColor:"blue" } // Try to create a copy const x = person; // This will change age in person: x.age = 10;

Changes in the age of x will also change the age of person since they are just simply one and the same and shares the same memory address.

Note:

We will learn more about objects in the following topics.

JavaScript Object Properties

An object is an unordered collection of properties.

Properties are the most important part of JavaScript objects.

Properties can be changed, added, deleted, and some are read only.

Accessing JavaScript Properties

The syntax for accessing the property of an object is:

// objectName.property let age = person.age;

or

//objectName["property"] let age = person["age"];

or

//objectName[expression] let age = person[x];

The following codes will yield the same result of "John Cena is 69 years old." which was extracted from the object person:

Code using the first syntax

let result = `${person.firstname} ${person.lastname} is ${person.age} years old.`;

Code using the second syntax

let result = `${person["firstname"]} ${person["lastname"]} is ${person["age"]} years old.`;

Code using the third syntax

const x = "firstname"; const y = "lastname"; const z = "age"; let result = `${person[x]} ${person[y]} is ${person[z]} years old.`;

Note:

In this case, we used template literals that uses backticks ` ` and ${ }. We will learn more about it in later topics.

Adding New Properties

You can add new properties to an existing object by simply giving it a value:

const person = { firstname: "John", lastname: "Cena", age: 69 }; person.language = "Chinese"; let result = person.firstname + "speaks" + person.language + ".";

The result variable will have a value of "John speaks Chinese."

The language property is not present in the assignment of the person object.

We added it later by calling the object and adding the property language and assigned it a value of "Chinese".

Deleting Properties

The delete keyword deletes a property from an object:

const person = { firstname: "John", lastname: "Cena", age: 69 }; delete person.age; let result = person.firstname + " is " + person.age + " years old.";

The result variable will have a value of "John is undefined years old."

This happens since we used the delete keyword to delete the property age and its value 69 from the object person.

We can also use this expression:

delete person["age"];

Or this:

const x = "age"; delete person[x];

Both works and deletes the property and its value.

Note:

The delete keyword deletes both the value of the property and the property itself.

After deletion, the property cannot be used before it is added back again.

Nested Objects

Property values in an object can be other objects:

myObj = { name:"John", age:69, myCars: { car1:"Ford", car2:"BMW", car3:"Fiat" } }

You can access nested objects using the dot notation or the bracket notation:

Code using the first syntax(dot notation):

myObj.myCars.car2;

Code using the second syntax(bracket notation):

myObj["myCars"]["car2"];

Code using both the dot and bracket notation:

myObj.myCars["car2"];

Code using the third syntax (using an expression):

let p1 = "myCars"; let p2 = "car2"; myObj[p1][p2];

Each of the code's final expression will have the same result with a value of "BMW".

Note:

For a complete reference, go to W3Schools.com's Complete JavaScript Object Reference.

The reference contains descriptions and examples of all Object Properties and Methods.

JavaScript Object Methods

Object methods are actions that can be performed on objects.

A method is a function definition stored as a property value.

The table below shows the following properties and values for the object named person.

Property and Value Table
Property Value
firstName John
lastName Cena
age 50
eyeColor blue
fullName function() {return this.firstName + " " + this.lastName;}

In the table above, we have a property named fullName and assigned it a function which makes it an object method.

We also used the this keyword which pertains to the object person.

So this.firstName is the same as person.firstName

Accessing Object Methods

You access an object method with the following syntax:

objectName.methodName();

If you invoke the fullName property with (), it will execute as a function:

const person = { firstName: "John", lastName: "Cena", id: 5566, fullName: function() { return `My full name is ${person.firstName} ${person.lastName}.`; } }; const name = person.fullName();

The value of the name variable results into "My full name is John Cena."

If you access the fullName property without (), it will return the function definition.

So if we used this last line of code instead:

const name = person.fullName;

The resulting value of name will now become "fullName() { return `My full name is ${person.firstName} ${person.lastName}.`; }"

Adding a Method to an Object

Adding a new method to an object is easy:

const person = { firstName: "John", lastName: "Cena", id: 5566, };

The above code declares person as an object. Now we will add a method by using this code:

person.fullName = function () { return `${this.firstName} ${this.lastName}`; };

If we call this method:

const result = person.fullname();

The result variable will have a value of "John Cena"

Using JavaScript Methods

This example uses the JavaScript toUpperCase() method to convert a text to uppercase:

Say we have person as an object and then we added a method:

person.name = function () { return this.firstName + " " + this.lastName; };

If we want to use a JavaScript method, say in this example the toUpperCase() method, we must first enclose the expression we want to apply the said method to with parenthesis ():

In our case, we will enclose this.firstName + " " + this.lastName since we want this expression to be applied with the toUpperCase() method.

person.name = function () { return (this.firstName + " " + this.lastName).toUpperCase(); };

Now, the resulting return value of our object method will have all its letters in uppercase.

Note:

For the complete reference, go to W3Schools.com Complete JavaScript Object Reference

The reference contains descriptions and examples of all Object Properties and Methods.

JavaScript Object Display

Displaying a JavaScript object will output [object Object].

For example, you created this person object and gave it the following properties and values:

const person = { name: "John", age: 30, city: "New York" };

If we try and display this object:

const element = document.getElementById("elementId"); element.innerHTML = person;

This will result into [object Object].

Some solutions to display JavaScript objects are:

  • Displaying the Object Properties by name
  • Displaying the Object Properties in a Loop
  • Displaying the Object using Object.values()
  • Displaying the Object using JSON.stringify()

Displaying Object Properties

The properties of an object can be displayed as a string.

This is what we are doing up to this point when we call the value for a specific property in our object.

Say you have this code:

const person = { name: "John Cena", age: 69, quote: "Bing Chillin'"; };

Then we display its properties using the dot notation or the bracket notation (in this case we used dot notation):

const element = document.getElementById("elementId"); element.innerHTML = person.age;

The element variable will simply display 69.

Displaying Properties in a Loop

The properties of an object can be collected in a loop:

const person = { name: "John Cena", age: 69, quote: "Bing Chillin'"; };

We can display the properties inside the person object using for...in which is designed to loop over keys(property names) in an object:

let properties = ""; for (key in person) { properties += person[key] + " / "; }

First we declared properties as a variable with a value of empty string "".

Then we used for...in where we set a variable key for each of the keys(property names) in the person object.

This means that we will try and loop all of the properties inside our object.

Inside the {} we stated that properties should add itself using += and is finally assigned with the value of person[key] plus the string " / ".

This will update the value of properties and will stop at once the loop is finished.

Remember, we used the bracket notation when we called for the property values in person since key is a variable and not the actual property name.

The variable key can be any other names of your choosing (except the prohibited keywords).

With all this, the final value for properties is "John Cena / 69 / Bing Chillin' / "

Note:

The concept of loops and for...in might be new to you. We will learn more about them in later topics.

Using Object.values()

Object.values() creates an array from the property values:

Say we have this code:

const person = { name: "John Cena", age: 69, quote: "Bing Chillin'" }

We can get the property values using Object.values() where we insert the object name person inside the ():

const properties = Object.values(person);

The properties variable will have a value of "John Cena,69,Bing Chillin'"

Using Object.entries()

Object.entries() makes it simple to use objects in loops.

Let's say you have this code for the object fruits:

const fruits = { Bananas: 300, Oranges: 200, Apples: 500 }

We will use Object.entries() to extract the property names and values in the fruits object.

const arrayFruits = Object.entries(fruits);

Now that we have the array list of the properties and values of our object, we proceed to undergo this into a for...of loop.

This loop is perfect for arrays. We will declare a variable arrayItems with an empty string "" as value.

This will hold our array items when we display it.

let arrayItems = ""; for (let fruit of arrayFruits) { let fruitName = fruit[0]; let fruitPrice = fruit[1]; arrayItems += `${fruitName}: ${fruitPrice}
`;
}

Let's take a look at our loop. Inside our for...of loop we defined a variable fruit that will hold the array items from arrayFruits.

Since each fruit variable holds an item which is also an array in itself (i.e. fruit = [Bananas, 300]), we assigned fruitName variable to hold the fruit[0] or the first item in the fruit array and the variable fruitPrice to hold the fruit[1] or the second item in the fruit array.

Then we reassigned the variable arrayItems to add in on itself a template literal expression of `${fruitName}: ${fruitPrice}<br>`

When the loop function is done in each item of arrayFruits, we are now ready to display the final value of the variable arrayItems:

let element = document.getElementById("elementId"); element.innerHTML = arrayItems;

This element will display this value:

Bananas: 300
Oranges: 200
Apples: 500

Note:

This for...of loop and the concept of arrays might be new to you. We will learn more about them in later topics.

Using JSON.stringify()

JavaScript objects can be converted to a string with JSON method JSON.stringify().

JSON.stringify() is included in JavaScript and supported in all major browsers.

Say you have this code:

const person = { name: "John Cena", age: 69, profession: "Actor" };

We will then declare a personString variable and assign it the value of JSON.stringify(person):

let personString = JSON.stringify(person); console.log(personString);

With this, the console log will return us a value of:

{"name":"John Cena","age":69,"profession":"Actor"}

For the complete object reference, go to W3Schools.com's Complete JavaScript Object Reference.

The reference contains descriptions and examples of all Object Properties and Methods.

JavaScript Object Constructors

Sometimes we need to create many objects of the same type.

To create an object type we use an object constructor function.

It is considered good practice to name constructor functions with an upper-case first letter:

function Person(first, last, age, eye) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eye; }

The code above is an example of a object constructor function.

It is a function that constructs new objects when called.

In this constructor function, the this keyword has no value as of this point.

It acts as a placeholder for the future object that we will create using this object constructor function.


Say you want to create a new object, we will first declare the variable name of the object and assign it the new keyword and the Person(first, last, age, eye) function where you give the arguments for that specific object:

const myFather = new Person("John", "Cena", 69, "Blue");

In this case, we have created the myFather object and stated it's arguments as "John" for the "first" parameter, "Cena" for the "last" parameter, and so on.


Next, we can try and calling out the property values of this new object:

const element = document.getElementById("elementId"); element.innerHTML = `My father's name is ${myFather.firstName} ${myFather.lastName}.`

The element variable will display "My father's name is John Cena."

With the object constructor function, we can create many objects with the same type:

const myMother = new Person("Sally", "Rally", 48, "green"); const mySister = new Person("Anna", "Rally", 18, "green"); const mySelf = new Person("Johnny", "Rally", 22, "green");

Property Default Values

A value given to a property will be a default value for all objects created by the constructor:

function Person(first, last, age, eyecolor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyecolor; this.nationality = "English"; } const myFather = new Person("John", "Doe", 50, "blue"); const myMother = new Person("Sally", "Rally", 48, "green");

In this case, we have made the value of the property nationality the same for all of the objects created by new Person(first, last, age, eyecolor).

We did not explicitly added a paramenter for the nationality property since it will be the same for all objects and will not be dynamic.

So if we call out the objects myFather and myMother:

const element = document.getElementById("elementId"); element.innerHTML = `My father is ${myFather.nationality} and my mother is ${myMother.nationality}.`

The resulting value for element will display "My father is English and my mother is English."

Adding a Property to an Object

Adding a property to a created object is easy.

Say you have this code:

function Fruit(p1, p2, p3) { this.name = p1; this.price = p2; this.stock = p3; } const banana = new Fruit("Banana", 300, 150); const apple = new Fruit("Apple", 200, 100);

With the Fruit(p1, p2, p3) object constructor function, we have created two objects.

However, we want to add another property to the banana object.

We can do this by simply writing this code:

banana.type = "Solo";

Finally, we can test this to see if the property type and its value "Solo" is added using console.log().

console.log("Result: ",`Our banana type is ${banana.type}.`);

Finally, the console log will give us the following return value:

Result: Our banana type is Solo.

This new property type is only added to the object banana and not added to the object apple.

If we do this in our console log:

console.log("Result: ",`Our apple type is ${apple.type}.`);

This console log will return:

Result: Our apple type is undefined.

Adding a Property to a Constructor

You can NOT add a new property to an object constructor if we used this code:

function Car(p1, p2, p3) { this.brand = p1; this.model = p2; this.year = p3; } const firstCar = new Car("Toyota", "Corolla", 2022); Car.color = "blue";

First, we created the Car(p1, p2, p3) object constructor function and we also created the firstCar object.

Now, we tried to add another property to our object constructor function but this will not work if we test it out with console.log():

console.log("Result: ", firstCar.color);

If a new property is indeed added, the result would become:

Result: blue

However, since we used the wrong syntax, we would get:

Result: undefined

Instead we should use this revised code by adding .prototype after Car:

Car.prototype.color = "blue";

Now the result from our console.log() will become:

Result: blue

Constructor Function Methods

A constructor function can also have methods:

function User(p1, p2, p3) { this.username = p1; this.email = p2; this.age = p3; this.description = function () { return `Your username is ${this.username} with the email: ${this.email}. You are ${this.age} years old.`; }; }

Then if we make an object:

const user1 = new User("noobmaster69", "noobmaster69@email.com", 69);

Then, calling the description() property method in console.log() :

console.log("Result: ", user1.description());

This will return us the following value:

Result: Your username is noobmaster69 with the email: noobmaster69@email.com. You are 69 years old.

Adding a Method to an Object

Adding a method to a created object is easy:

function User(p1, p2, p3) { this.username = p1; this.email = p2; this.age = p3; }

Using the User(p1, p2, p3) object constructor function above, we will make two objects:

const user1 = new User("noobmaster69", "noobmaster69@email.com", 69); const user2 = new User("ilovesundays", "sundaylover@email.com", 25);

However, we want to add a method for user2.

We can do this by running this code:

user2.description = function() { return `Hi I'm ${this.username}, ${this.age} years old, and my email is ${this.email}.`; };

To check if its working, we can use console.log() to see the return value of user2.description():

console.log("Result: ", user2.description());

The return value from the console log is:

Result: Hi I'm ilovesundays, 25 years old, and my email is sundaylover@email.com.

Note:

This method is only added to the user2 object and not to the other objects like user1 or any other future objects to be created.

Adding a Method to a Constructor

You cannot add a new method to an object constructor function.

Say you have this code:

function User(p1, p2, p3) { this.username = p1; this.email = p2; this.age = p3; } const user1 = new User("noobmaster69", "noobmaster69@email.com", 69);

Then we would like a add a new method to our User(p1, p2, p3) object constructor function using this code:

User.changeUsername = function (p1) { return this.username = p1; }

This will simply not work and if we test it in console.log():

console.log("Result: ", user1.changeUsername("noobmaster96"));

The returning value would become:

TypeError: user1.changeUsername is not a function

We can solve this by adding .prototype after User so we can directly add the new method in our constructor:

User.prototype.changeUsername = function (p1) { return this.username = p1; }

The returning value from our console log would be:

Result: noobmaster96

JavaScript Events

HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these events.

HTML Events

An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:

  • An HTML web page has finished loading
  • An HTML input field was changed
  • An HTML button was clicked

Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">

In the following example, an onclick attribute (with code), is added to a <button> element:

<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button> <p id="demo"></p>

So when that <button> is clicked, the <p> element below it will changed its innerHTML to the value of Date().


In the next example, the code changes the content of its own element (using this.innerHTML):

<button onclick="this.innerHTML = Date()">The time is?</button>

If the <button> element above is clicked, its content will change from "The time is?" to the value of Date().

JavaScript code is often several lines long. It is more common to see event attributes calling functions:

<button onclick="displayDate()">The time is?</button>

Common HTML Events

Here is a list of some common HTML events:

Common HTML Events
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page

The list is much longer. For a complete reference go to W3Schools JavaScript Reference HTML DOM Events.

JavaScript Event Handlers

Event handlers can be used to handle and verify user input, user actions, and browser actions:

  • Things that should be done every time a page loads
  • Things that should be done when the page is closed
  • Action that should be performed when a user clicks a button
  • Content that should be verified when a user inputs data
  • And more ...

Many different methods can be used to let JavaScript work with events:

  • HTML event attributes can execute JavaScript code directly
  • HTML event attributes can call JavaScript functions
  • You can assign your own event handler functions to HTML elements
  • You can prevent events from being sent or being handled
  • And more ...

Note:

We will learn more about events and event handlers in the HTML DOM topics.

JavaScript Strings

Strings are for storing text.

Strings are written with quotes.

Using Quotes

A JavaScript string is zero or more characters written inside quotes:

let name = "John Cena";

The name variable stores a string with a value of "John Cena".

You can use single or double quotes:

let name = "John Cena"; let name = 'John Cena';

Strings created with single or double quotes work the same.

There is no difference between the two.

Quotes Inside Quotes

You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

let answer1 = "It's alright"; let answer2 = "He is called 'Johnny'"; let answer3 = 'He is called "Johnny"';

Template Strings

Templates were introduced with ES6 (JavaScript 2016).

Templates are strings enclosed in ` ` backticks (`This is a template string`):

let text = `He's often called "Johnny"`;

The resulting value for text is He's often called "Johnny".

Templates allow multiline strings:

let text = `The quick brown fox jumps over the lazy dog`;

Note:

Templates are not supported in Internet Explorer.

String Length

To find the length of a string, use the built-in length property:

let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; let length = text.length;

Now if we check the value of length in console.log():

console.log("Result: ", length);

The return value would be:

Result: 26

Escape Characters

Because strings must be written within quotes, JavaScript will misunderstand this string:

let text = "We are the so-called "Vikings" from the north.";

The string will be chopped to "We are the so-called ".

To solve this problem, you can use a backslash escape character \.

The backslash escape character \ turns special characters into string characters:

Using Backlash to Convert Special Characters to Strings
Code Result Description
\' ' Single Quote
\" " Double Quote
\\ \ Backlash

\" inserts a double quote in a string:

let text = "We are the so-called \"Vikings\" from the north.";

\' inserts a single quote in a string:

let text= 'It\'s alright.';

\\ inserts a backslash in a string:

let text = "The character \\ is called backslash.";

Breaking Long Lines

For readability, programmers often like to avoid long code lines.

A safe way to break up a statement is after an operator:

document.getElementById("demo").innerHTML = "Hello Dolly!";

A safe way to break up a string is by using string concatenation:

document.getElementById("demo").innerHTML = "Hello " + "Dolly!";

JavaScript Strings as Objects

Normally, JavaScript strings are primitive values, created from literals:

let x = "John";

But strings can also be defined as objects with the keyword new:

let y = new String("John");

However, if we run the following codes in console.log() and find their data type using typeof:

console.log("Data Type: ", `x = ${typeof x}, y = ${typeof y}`);

The results of their data types are:

Data Type: x = string, y = object

This difference will make things complicated in the long run.

Do not create String objects.

The new keyword complicates the code and slows down execution speed.

String objects can produce unexpected results:

When using the == operator, x and y are equal

let x = "John"; let y = new String("John");

When using the === operator, x and y are not equal

let x = "John"; let y = new String("John");

Now if we compare two values both made from new String():

let x = new String("John"); let y = new String("John");

x == y is false since objects cannot be compared.

x === y is also false since both are still objects and cannot be compared.

Comparing two JavaScript objects always returns false.

For a complete String reference, go to W3Schools Complete JavaScript String Reference.

The reference contains descriptions and examples of all string properties and methods.

JavaScript String Methods

Javascript strings are primitive and immutable.

All string methods produce a new string without altering the original string.

JavaScript String Length

The length property returns the length of a string:

let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; let length = text.length;

The length variable will return a value of 26.

Extracting String Characters

There are 4 methods for extracting string characters:

  • The at(position) Method
  • The charAt(position) Method
  • The charCodeAt(position) Method
  • Using property access [] like in arrays

JavaScript String charAt()

The charAt() method returns the character at a specified index (position) in a string:

let text = "HELLO WORLD"; let char = text.charAt(0);

The value for char variable will be "H" since the letter "H" is the first letter or (index = 0) in the string of variable text.

JavaScript String charCodeAt()

The charCodeAt() method returns the code of the character at a specified index in a string:

The method returns a UTF-16 code (an integer between 0 and 65535)

let text = "HELLO WORLD"; let char = text.charCodeAt(0);

The resulting value for char variable is 72.

JavaScript String at()

ES2022 introduced the string method at():

const name = "W3Schools"; let letter = name.at(2);

The resulting value for the letter variable is S.

The at() method returns the character at a specified index (position) in a string.

The at() method is supported in all modern browsers since March 2022:

The difference between at() and charAt() is that the former allows the use of negative index while the latter do not.

Now you can use myString.at(-2) instead of charAt(myString.length-2).

Note that the negative index of (-1) is the last character of the string, while (-2) is the second to the last character in a string.

Property Access [ ]

Say you have the code below:

let text = "HELLO WORLD"; let char = text[0];

The resulting value for the variable char is H.

Note:

Property access might be a little unpredictable:

  • It makes strings look like arrays (but they are not)
  • If no character is found, [ ] returns undefined, while charAt() returns an empty string.
  • It is read only. str[0] = "A" gives no error (but does not work!)
let text = "HELLO WORLD"; text[0] = "A"; // Gives no error, but does not work

The value of text variable will still be "HELLO WORLD" and not "AELLO WORLD"

Extracting String Parts

There are 3 methods for extracting a part of a string:

  • slice(start, end)
  • substring(start, end)
  • substr(start, length)

JavaScript String slice()

slice() extracts a part of a string and returns the extracted part in a new string.

The method takes 2 parameters: start position, and end position (end not included).

Let's see the code below:

let text = "Apple, Banana, Kiwi"; let part = text.slice(7, 13);

Take note that JavaScript counts positions or indexes from 0(zero).

In the example above, the starting position (7) is "B" and the ending position (13) is ",".

Since slice() does not include the ending position, the string cuts off at "a".

Finally, the final value for part variable is "Banana".


The following are some of the examples of usage for slice():

let text = "Apple, Banana, Kiwi"; let part = text.slice(7);

If we only use one parameter for slice(), then it will slice out the rest of the string.

With this, the value for part becomes "Banana, Kiwi"

let text = "Apple, Banana, Kiwi"; let part = text.slice(-12);

If a parameter is negative, the position is counted from the end of the string:

The -12 index stops at "B" and therefore the final value of the part variable will still be "Banana, Kiwi".

let text = "Apple, Banana, Kiwi"; let part = text.slice(-12, -6);

This last example slices out a portion of a string from position -12 to position -6:

Position -12 is "B" and position -6 is "," and since the end position is not included, the value for the part variable will become "Banana".

JavaScript String substring()

substring() is similar to slice().

The difference is that start and end values less than 0 are treated as 0 in substring():

let str = "Apple, Banana, Kiwi"; let part = str.substring(-1);

The index of -1 will be treated as 0 and the resulting value for part is equal to "Apple, Banana, Kiwi"

JavaScript String substr()

substr() is similar to slice().

The difference is that the second parameter specifies the length of the extracted part.

WARNING:

The substr() method is removed (deprecated) in the latest JavaScript standard.

Use substring() or slice() instead.

Converting to Upper and Lower Case

A string is converted to upper case with toUpperCase().

A string is converted to lower case with toLowerCase().

Say you have this code:

let text = "Bing Chilling"; let textUpperCase = text.toUpperCase();

The resulting value for textUpperCase is "BING CHILLING"

However, if we use toLowerCase():

let text = "Bing Chilling"; let textLowerCase = text.toLowerCase();

The resulting value for textLowerCase is "bing chilling"

JavaScript String concat()

concat() joins two or more strings:

let text1 = "Bing"; let text2 = "Chilling"; let textConcat = text1.concat(" ", text2);

The value of the textConcat variable is "Bing Chilling".

The first parameter of this string method is a string that would be placed between text1 and the following parameter, text2.

In this case, the value is " " (a space).

We can also do this:

let textConcat = text1.concat(",", text2);

This will make the resulting value to become "Bing,Chilling".

The concat() method can be used instead of the plus operator. These two lines do the same:

textConcat = text1 + " " + text2; textConcat = text1.concat(" ", text2);

If we are adding multiple strings:

let text1 = "Bing"; let text2 = "Chilling"; let text3 = "- John Cena" let textConcat = text1.concat(" ", text2, " ", text3);

The resulting value for textConcat is "Bing Chilling - John Cena".

Note:

All string methods return a new string. They don't modify the original string.

Strings are immutable: Strings cannot be changed, only replaced.

JavaScript String trim()

The trim() method removes whitespace from both sides of a string:

let text = " Bing Chilling "; let textTrim = text.trim(); let textLength = text.length; let textTrimLength = textTrim.length;

The text variable has a value of " Bing Chilling " and there is an extra space on each of its sides.

Using trim() we removed those extra spaces and to prove it, we used length to measure the length of text and textTrim.

The resulting value of textLength is 15 while the value of textTrimLength is 13.

Note:

We are only trimming the sides and not the spaces inside the string.

JavaScript String trimStart() & trimEnd()

ECMAScript 2019 added the String method trimStart() and trimEnd() to JavaScript.

The trimStart() method works like trim(), but removes whitespace only from the start of a string.

Also, the trimEnd() method works like trim(), but removes whitespace only from the end of a string.

JavaScript String Padding

ECMAScript 2017 added two new string methods to JavaScript: padStart() and padEnd() to support padding at the beginning and at the end of a string.

The padStart() method pads a string from the start.

In the code below, we would like to pad the string with "0" until the length reaches 10:

let text = "Hello" let textPadded = text.padStart(10, "0");

As we can see, the text has a string value of "Hello" which has a length of 5.

Then we used padStart() and added 10 as its first parameter and "0" as its second parameter.

This method will add "0" at the start of text until it reaches a length of 10.

Therefore, the final value of textPadded is "00000Hello".


Next is to pad the end of the string with "0" until the length reaches 10:

let text = "Hello" let textPadded = text.padEnd(10, "0");

The difference with this method is that it will add "0" at the end of text until it reaches a length of 10.

Therefore, the final value of textPadded is "Hello00000".

Note:

Both the padStart() and the padEnd() method is a string method.

To pad a number, convert the number to a string first.

We can do this by using the toString() to a number:

let number = 7; let numberToString = number.toString();

Now if we check the typeof of number and numberToString, it will return number for the former and string for the latter.

JavaScript String repeat()

The repeat() method returns a string with a number of copies of a string.

This method returns a new string

It does not change the original string.

Say we have this code:

let text = "BingChilling"; let textRepeat = text.repeat(4);

The resulting value for textRepeat is:

BingChillingBingChillingBingChillingBingChilling

This is possible because repeat() returns a new string that repeats the string value of text four times.

The parameter for number of repetitions inside repeat() is required.

Replacing String Content

The replace() method replaces a specified value with another value in a string:

let text = "Bing Chilling"; let textNew = text.replace("Bing", "Google");

This method by default will replace the first match.

Therefore the value for newText is "Google Chilling".

Note:

The replace() method does not change the string it is called on.

It always returns a new string

This method only replaces the first match

If you want to replace all matches, use a regular expression with the /g flag set.


Let's try to change all string with a value of "Bing" to "Google" inside the variable text:

let text = "Bing Bing Bing Chilling"; let textNew = text.replace("Bing", "Google");

This will not work since this method only changes the first match.

Therefore the value of textNew is "Google Bing Bing Chilling"

To replace all matches, use a regular expression with a /g flag (global match):

let text = "Bing Bing Bing Chilling"; let textNew = text.replace(/Bing/g, "Google");

This will now replace all of the matches of "Bing" inside the text variable.


The replace() string method is also case senstive:

let text = "Bing Chilling"; let textNew = text.replace("BING", "Google");

This will not work and the value for textNew will just return "Bing Chilling".

To replace case insensitive, use a regular expression with an /i flag (insensitive):

let text = "Bing Chilling"; let textNew = text.replace(/BING/i, "Google");

This will now work and the resulting value for textNew is now "Google Chilling".

Note:

Regular expressions are written without quotes.

We will learn more about regular expressions in later topics.

JavaScript String ReplaceAll()

In 2021, JavaScript introduced the string method replaceAll():

let text = "Good morning, China. I have bing chilling with me right now. I like bing chilling."; let textNew = text.replaceAll("bing chilling", "ice cream");

The value for textNew is now "Good morning, China. I have ice cream with me right now. I like ice cream."

The replaceAll() method allows you to specify a regular expression instead of a string to be replaced.

If the parameter is a regular expression, the global flag (g) must be set, otherwise a TypeError is thrown.

You should code it like this:

let text = "Good morning, China. I have bing chilling with me right now. I like bing chilling."; let textNew = text.replaceAll(/bing chilling/g, "ice cream");

This code will give us the same value for textNew.

JavaScript String split()

If you want to work with a string as an array, you can convert it to an array.

A string can be converted to an array with the split() method.

Say you have this code:

let text = "BingChilling" let textArray = text.split("");

We used split("") which will split the text variable to individual letters.

Therefore the value for textArray is ['B', 'i', 'n', 'g', 'C', 'h', 'i', 'l', 'l', 'i', 'n', 'g']

Notice that the parameter inside the split() method is "" which is an empty string.

This tells the method to take a string value as an array item and then split it exactly after it matches an empty string.


To explain further, let's take another code example:

let fruits = "Banana, Coconut, Apple"; let fruitsArray = fruits.split(", ");

With this, the value of fruitsArray is ['Banana', 'Coconut', 'Apple'].

This happens since we told the split() to split the string fruits when it matches with ", " which is a comma followed by a space.

This parameter is also called the separator and if ommitted, the returned array will contain the whole string in index [0].


For a complete string reference go to W3Schools Complete JavaScript String Reference

The reference contains descriptions and examples of all string properties and methods.

JavaScript Template Strings

Template strings are also called string templates and template literals.

Back-Tics Syntax

Template Strings use back-ticks (` `) rather than the quotes (" ") to define a string:

let text = `Bing Chilling`; console.log("Result:", text);

The console log will return a value of Result: Bing Chilling

Quotes Inside Strings

Template Strings allow both single and double quotes inside a string:

let text = `He's often called "John Cena".`; console.log("Result:", text);

The console log will display a value of Result: He's often called "John Cena".

Multiline Strings

Template Strings allow multiline strings:

let text = `The quick brown fox jumps over the lazy dog`; console.log("Result:", text);

The resulting value for our console log is Result: The quick brown fox jumps over the lazy dog.

Interpolation

Template String provide an easy way to interpolate (include) variables and expressions into strings.

The method is called string interpolation.

The syntax is:

${...}

Say you have this code:

let fullName = "John Cena"; let age = 69; let description = `${fullName} is ${age} years old.`;

In the code above, we declared and assigned two variables fullName and age.

We also declared a third variable description and assigned it a string using string tempates.

Finally, we used ${} to interpolate the first two variables and display their respective values.

The value for description is "John Cena is 69 years old."

Variable Substitutions

Template Strings allow variables in strings:

let firstName = "John"; let lastName = "Cena"; let message = `Welcome ${firstName} ${lastName}!`;

The message variable will have a value of "Welcome John Cena!"

The automatic replacing of variables with real values is called string interpolation.

Expression Substitution

Template Strings allow expressions in strings:

let price = 10; const VAT = 0.25; let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;

In this example, we have inserted an expression inside ${} in the total variable.

This will result into a value of Total: 12.50

HTML Templates

We can also input html elements inside a template string:

let header = "Template Strings"; let list = ["template strings", "javascript", "es6"]; let html = `<h3 class="subtopic__title">${header}</h3><ul class="subtopic__ul">`; for (let item of list) { html += `<li>${item}</li>`; } html += `</ul>`;

When we call the html variable from this code, it will be able to insert the html code in the DOM.

Let's try and call this in console log.

console.log("Result:", html);

The result will be the html code that will be inserted:

<h3 class="subtopic__title">Template Strings</h3><ul class="subtopic__ul"><li>template strings</li><li>javascript</li><li>es6</li></ul>

Note:

For a complete string reference, go to W3Schools Complete JavaScript String Reference

The reference contains descriptions and examples of all string properties and methods.

JavaScript Numbers

JavaScript has only one type of number.

Numbers can be written with or without decimals.

let x = 3.14; // A number with decimals let y = 3; // A number without decimals

Extra large or extra small numbers can be written with scientific (exponent) notation:

let x = 123e5; // 12300000 let y = 123e-5; // 0.00123

JavaScript Numbers are Always 64-bit Floating Point

Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc.

JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.

This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63:

Integer Precision

Integers (numbers without a period or exponent notation) are accurate up to 15 digits:

let x = 999999999999999; // x will be 999999999999999 let y = 9999999999999999; // y will be 10000000000000000

The maximum number of decimals is 17.

Floating Precision

Floating point arithmetic is not always 100% accurate:

let x = 0.2; let y = 0.1; console.log("Result:", x + y);

The console log will return a value of Result: 0.30000000000000004.

To solve the problem above, it helps to multiply and divide:

let x = 0.2; let y = 0.1; console.log("Result:", ((x * 10) + (y * 10)) / 10 );

We multiplied both the x and y variables by 10 first and then added them.

Finally we divided the sum by 10. The final return value from the console log is Result: 0.3

Adding Numbers and Strings

WARNING!

JavaScript uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.


If you add two numbers, the result will be a number:

let x = 6; let y = 9; let z = x + y;

The value of z is 15.

If you add two strings, the result will be a string concatenation:

let x = "6"; let y = "9"; let z = x + y;

The value of z is "69".

If you add a number and a string, the result will be a string concatenation:

let x = 6; let y = "9"; let z = x + y;

The value of z is still "69".

If you add the following variables in this code below:

let x = 6; let y = 9; let z = "69"; let sum = x + y + z;

The value of sum will be "1569" and not "6969".

This is because the JavaScript interpreter works from left to right.

First 6 + 9 is added because x and y are both numbers.

Then 15 + "69" is concatenated because z is a string.

Therefore the final result for sum is "1569".

Numeric Strings

JavaScript strings can have numeric content:

let x = 69; // x is a number let y = "69"; // y is a string

JavaScript will try to convert strings to numbers in all numeric operations:

This will work:

let x = "100"; let y = "10"; let z = x / y;

The result of z is a number of value 10.

The following will also work:

let x = "100"; let y = "10"; let z = x * y;

The result of z is a number of value 1000.

let x = "100"; let y = "10"; let z = x - y;

The result of z is a number of value 90.

However, using the + operator will not work:

let x = "100"; let y = "10"; let z = x + y;

The result of z is a string of value "10010".

In this last example JavaScript uses the + operator to concatenate the strings.

NaN - Not a Number

NaN is a JavaScript reserved word indicating that a number is not a legal number.

Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number):

let x = 69 / "John Cena";

The value of x is NaN since the second operand is a string and when JavaScript tried to convert it into a number it determined it to be not a legal number.

However, if the string is numeric, the result will be a number:

let x = 69 / "3";

The value of x is 23 because JavaScript successfully converted the string "3" to a number 3 and then performed arithmetic division.

You can use the global JavaScript function isNaN() to find out if a value is a not a number:

let x = 69 / "John Cena"; console.log("Result:", isNan(x));

The return value from our console log is Result: NaN.

Watch out for NaN. If you use NaN in a mathematical operation, the result will also be NaN:

let x = 69 / "John Cena"; console.log("Result:", isNaN(x));

Since we tried to divide a number to a NaN, the value for x will also be NaN.

Thus, the return value from our console log is Result: true.

Or the result might be a concatenation like NaN69:

let x = NaN + "69";

The value of x is the string "NaN69".

NaN is a number. This is proven if we test it using typeof:

console.log("Result:", typeof NaN);

The return value from the console log is Result: number .

Infinity

Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number.

Say you have this code;

let x = 69; while (x != Infinity) { x *= x; }

The while() loop might be new to you and we will cover more of it in later topics.

For now, what's important is to have a value big enough for x by multiplying it by itself until it becomes Infinity

Division by 0 (zero) also generates Infinity:

let x = 1 / 0; let y = -1 / 0;

The resulting value for x is Infinity while the value for y is -Infinity.

Infinity is a number:

let x = typeof Infinity;

The value of x will return number.

Hexadecimal

JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x:

let x = 0xFF; console.log("Result:", x);

The console log will return a value of Result: 255.

Note:

Never write a number with a leading zero (like 07).

Some JavaScript versions interpret numbers as octal if they are written with a leading zero.


By default, JavaScript displays numbers as base 10 decimals.

But you can use the toString() method to output numbers from base 2 to base 36.

Hexadecimal is base 16. Decimal is base 10. Octal is base 8. Binary is base 2.

JavaScript Numbers as Objects

Normally JavaScript numbers are primitive values created from literals:

let x = 69;

But numbers can also be defined as objects with the keyword new:

let x = new Number(69); console.log("Result:", typeof x);

The return value from our console log is Result: object

Note:

The new keyword complicates the code and slows down execution speed.

Number Objects can produce unexpected results just like with String Objects.

For a complete Number reference, visit W3Schools Complete JavaScript Number Reference.

The reference contains descriptions and examples of all Number properties and methods.

JavaScript BigInt

JavaScript BigInt variables are used to store big integer values that are too big to be represented by a normal JavaScript Number.

JavaScript Integer Accuracy

JavaScript integers are only accurate up to 15 digits:

let x = 999999999999999; let y = 9999999999999999;

The value of x is an accurate 999999999999999.

While the value of y becomes inaccurate and is read as 10000000000000000.


In JavaScript, all numbers are stored in a 64-bit floating-point format (IEEE 754 standard).

With this standard, large integer cannot be exactly represented and will be rounded.

Because of this, JavaScript can only safely represent integers:

  • Up to 9007199254740991 or +(253-1)
  • Down to -9007199254740991 or -(253-1)

Integer values outside this range lose precision.

How to Create a BigInt

To create a BigInt, append n to the end of an integer or call BigInt():

let x = 1234567890123456789012345n; let y = BigInt(1234567890123456789012345);

BigInt: A new JavaScript Datatype

The JavaScript typeof a BigInt is "bigint":

let x = BigInt(999999999999999); let type = typeof x;

The value of type is bigint.


BigInt is the second numeric data type in JavaScript (after Number).

With BigInt the total number of supported data types in JavaScript is 8:

  • String
  • Number
  • BigInt
  • Boolean
  • Undefined
  • Null
  • Symbol
  • Object

BigInt Operators

Operators that can be used on a JavaScript Number can also be used on a BigInt:

let x = 9007199254740995n; let y = 9007199254740995n; let z = x * y;

The value of z would result to 81129638414606735738984533590025n.

Remember, arithmetic between a BigInt and a Number is not allowed (type conversion lose information).

Unsigned right shift (>>>) can not be done on a BigInt (it does not have a fixed width).

BigInt Decimals

A BigInt can not have decimals.

Say you have this code:

let x = 5n; let y = x / 2;

JavaScript will throw an error which states Cannot mix BigInt and other types, use explicit conversion.

Therefore, we need to convert x first into a number using Number():

let x = 5n; let y = Number(x) / 2;

This way it will not throw an error and y has a value of 2.5

BigInt Hex, Octal and Binary

BigInt can also be written in hexadecimal, octal, or binary notation:

let hex = 0x20000000000003n; let oct = 0o400000000000000003n; let bin = 0b100000000000000000000000000000000000000000000000000011n;

Minimum and Maximum Safe Integers

ES6 added max and min properties to the Number object:

  • MAX_SAFE_INTEGER
  • MIN_SAFE_INTEGER

These values when put in variables will have the following results:

let max = Number.MAX_SAFE_INTEGER; // max will have a value of 9007199254740991 let min = Number.MIN_SAFE_INTEGER; // min will have a value of -9007199254740991

The Number.isInteger() and Number.isSafeInteger() Method

The Number.isInteger() method returns true if the argument is an integer:

Number.isInteger(10); // will return true Number.isInteger(10.5); // will return false

A safe integer is an integer that can be exactly represented as a double precision number.

The Number.isSafeInteger() method returns true if the argument is a safe integer:

Number.isSafeInteger(10); // returns true Number.isSafeInteger(12345678901234567890); // returns false

Safe integers are all integers from -(253 - 1) to +(253 - 1).

This is safe: 9007199254740991. This is not safe: 9007199254740992.

JavaScript Number Methods

These number methods can be used on all JavaScript numbers:

Number Methods
Method Description
toString() Returns a number as a string
toExponential() Returns a number written in exponential notation
toFixed() Returns a number written with a number of decimals
toPrecision() Returns a number written with a specified length
valueOf() Returns a number as a number

The toString() Method

The toString() method returns a number as a string.

All number methods can be used on any type of numbers (literals, variables, or expressions):

Say you have this code for variables storing a number value:

let x = 69; let str = x.toString();

The variable str has a string value of "69".

This also goes for literals and expressions:

let x = (69).toString(); let y = (23 + 46).toString();

Both will result to a string of value "69".

This method also accepts an optional radix argument that converts a number to a different base first and then turns it to a string:

let x = (69).toString(2);

The value of x is "1000101" because this value is the binary form of 69.

The toExponential() Method

toExponential() returns a string, with a number rounded and written using exponential notation.

A parameter defines the number of characters behind the decimal point:

let x = 3.1415926535; let y = x.toExponential(2); let z = x.toExponential(4);

The value of y is "3.14e+0" while the value of z is "3.1416e+0".

Both y and z is a string.

The parameter is optional. If you don't specify it, JavaScript will not round the number:

let x = 3.1415926535; let y = x.toExponential();

The value of y is "3.1415926535e+0".

The toFixed() Method

toFixed() returns a string, with the number written with a specified number of decimals:

let x = 3.1415926535; let y = x.toFixed(2); let z = x.toFixed(4);

The value for y is "3.14" while the value for z is "3.1416"

Each of these variables is a string.

toFixed(2) is perfect for working with money.

The toPrecision() Method

toPrecision() returns a string, with a number written with a specified length:

let x = 3.1415926535; let y = x.toPrecision(2); let z = x.toPrecision(4);

The value for y is "3.1" while the value for z is "3.142".

Each of these variables is a string.

However, if we omit the parameter inside this method:

let x = 3.1415926535; let y = x.toPrecision();

The value of y will just return the same length which in this case is "3.1415926535".

The valueOf() Method

valueOf() returns a number as a number.

In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof = object).

The valueOf() method is used internally in JavaScript to convert Number objects to primitive values.

There is no reason to use it in your code.

Note:

All JavaScript data types have a valueOf() and a toString() method.

Converting Variables to Numbers

There are 3 JavaScript methods that can be used to convert a variable to a number:

3 Methods for Converting a Variable to a Number
Method Description
Number() Returns a number converted from its argument.
parseFloat() Parses its argument and returns a floating point number
parseInt() Parses its argument and returns a whole number

The methods above are not number methods. They are global JavaScript methods.

The Number() Method

The Number() method can be used to convert JavaScript variables to numbers:

Note:

If the number cannot be converted, NaN (Not a Number) is returned.

The Number() Method Used on Dates

Number() can also convert a date to a number:

let date = new Date("1999-11-07"); let x = Number(date);

The value for x is 941932800000.

Note:

This number is computed by returning the number of milliseconds since 1970-01-01.

Thus, the number of milliseconds between 1970-01-01 and 1999-11-07 is 941932800000.

The parseInt() Method

parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned:

let x = parseInt("69.69"); let y = parseInt("69.69 word") let z = parseInt("word 69.69")

The value of x is 69 since this method only keeps integers.

The value of y is also 69 because this method only converts the first group of characters in a string (no spaces).

Finally, the value of z is NaN since "word" cannot be converted into a number.

The parseFloat() Method

parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned:

let x = parseFloat("69.69"); let y = parseFloat("69.69 word") let z = parseFloat("word 69.69")

The logic is the same as parseInt(), the only difference is that this method returns us a floating number (with decimal).

So the value of x is 69.69, the value of y is 69.69 and lastly the value of z is NaN.

Number Object Methods

These object methods belong to the Number object:

Object Methods for Number Object
Method Description
Number.isInteger() Returns true if the argument is an integer
Number.isSafeInteger() Returns true if the argument is a safe integer
Number.parseFloat() Converts a string to a number
Number.parseInt() Converts a string to a whole number

Note:

The number methods above belong to the JavaScript Number Object.

These methods can only be accessed like Number.isInteger().

Using X.isInteger() where X is a variable, will result in an error:

TypeError X.isInteger is not a function.

The Number.isInteger() Method

The Number.isInteger() method returns true if the argument is an integer:

let x = Number.isInteger(69); let y = Number.isInteger(69.69);

The value of x is true

While the value of y is false.

The Number.isSafeInteger() Method

A safe integer is an integer that can be exactly represented as a double precision number.

The Number.isSafeInteger() method returns true if the argument is a safe integer:

let x = Number.isSafeInteger(69); let y = Number.isSafeInteger(6969696969696969696969696969);

The value of x returns true

While the value of y returns false.

The Number.parseFloat() Method

Number.parseFloat() parses a string and returns a number.

This is the same as global method parseFloat().

The Number.parseInt() Method

Number.parseInt() parses a string and returns a whole number.

This is the same as global method parseInt().

Note:

The Number methods Number.parseInt() and Number.parseFloat() are the same as the Global methods parseInt() and parseFloat().

The purpose is modularization of globals (to make it easier to use the same JavaScript code outside the browser).


For a complete Number reference visit W3Schools Complete JavaScript Number Reference

The reference contains descriptions and examples of all Number properties and methods.

JavaScript Number Properties

JavaScript Number Properties and Description Table
Property Description
EPSILON The difference between 1 and the smallest number > 1.
MAX_VALUE The largest number possible in JavaScript
MIN_VALUE The smallest number possible in JavaScript
MAX_SAFE_INTEGER The maximum safe integer (253 - 1)
MIN_SAFE_INTEGER The minimum safe integer -(253 - 1)
POSITIVE_INFINITY Infinity (returned on overflow)
NEGATIVE_INFINITY Negative infinity (returned on overflow)
NaN A "Not-a-Number" value

JavaScript EPSILON

Number.EPSILON is the difference between the smallest floating point number greater than 1 and 1:

let x = Number.EPSILON;

The value of x is 2.220446049250313e-16

JavaScript MAX_VALUE

Number.MAX_VALUE is a constant representing the largest possible number in JavaScript:

let x = Number.MAX_VALUE;

The value of x is 1.7976931348623157e+308

Note:

Number properties cannot be used on variables.

Number properties belong to the JavaScript Number Object.

These properties can only be accessed as Number.MAX_VALUE.

Using x.MAX_VALUE, where x is a variable or a value, will return undefined:

let x = 69; let result = x.MAX_VALUE;

The value of result is undefined.

JavaScript MIN_VALUE

Number.MIN_VALUE is a constant representing the lowest possible number in JavaScript:

let x = Number.MIN_VALUE;

The value of x is 5e-324.

JavaScript MAX_SAFE_INTEGER & MIN_SAFE_INTEGER

Number.MAX_SAFE_INTEGER represents the maximum safe integer in JavaScript.

Number.MAX_SAFE_INTEGER is (253 - 1).

Number.MIN_SAFE_INTEGER represents the minimum safe integer in JavaScript.

Number.MIN_SAFE_INTEGER is -(253 - 1).

JavaScript POSITIVE_INFINITY & NEGATIVE_INFINITY

The value for Number.POSITIVE_INFINITY is Infinity while the value for Number.NEGATIVE_INFINITY is -Infinity

We can also get a value of Infinity with this code:

let x = 1 / 0;

Likewise, we can also get a value of -Infinity with this code:

let x = -1 / 0;

JavaScript NaN - Not a Number

NaN is a JavaScript reserved word for a number that is not a legal number:

let x = Number.NaN;

The value for x is NaN.

Trying to do arithmetic with a non-numeric string will result in NaN. (Not a Number):

let x = 69 * "John Cena";

The value of x is NaN.


For a complete Number reference, visit our W3Schools Complete JavaScript Number Reference

The reference contains descriptions and examples of all Number properties and methods.

JavaScript Arrays

An array is a special variable, which can hold more than one value:

const cars = ["Toyota", "Honda", "BMW"];

The cars variable is an array which contains 3 values.

Why Use Arrays?

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

let car1 = "Saab"; let car2 = "Volvo"; let car3 = "BMW";

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.

Creating an Array

Using an array literal is the easiest way to create a JavaScript Array.

Syntax:

const array_name = [item1, item2, ...];

It is a common practice to declare arrays with the const keyword.

We will learn more about this in later topics.


Here's an example array:

const cars = ["Saab", "Volvo", "BMW"];

Spaces and line breaks are not important. A declaration can span multiple lines:

const cars = [ "Saab", "Volvo", "BMW" ];

You can also create an array, and then provide the elements:

const cars = []; cars[0] = "Saab"; cars[1] = "Volvo"; cars[2] = "BMW";

Using the JavaScript Keyword new

The following example also creates an Array, and assigns values to it:

const cars = new Array("Saab", "Volvo", "BMW");

Note:

The two examples above do exactly the same.

There is no need to use new Array().

For simplicity, readability and execution speed, use the array literal method.

Accessing Array Elements

You access an array element by referring to the index number:

const cars = ["Saab", "Volvo", "BMW"]; let car = cars[0];

The value of car is "Saab".

Note:

Array indexes start with 0.

[0] is the first element. [1] is the second element.

Changing an Array Element

This statement changes the value of the first element in cars:

const cars = new Array("Saab", "Volvo", "BMW"); cars[0] = "Opel";

Now the value of the first index [0] for the array cars is now "Opel".

Converting an Array to a String

The JavaScript method toString() converts an array to a string of (comma separated) array values:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let x = fruits.toString();

The array fruits is now converted to a string and assigned in the x variable.

The resulting value for x is "Banana,Orange,Apple,Mango"

Access the Full Array

With JavaScript, the full array can be accessed by referring to the array name:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; console.log("Result:", fruits);

We just called the variable name fruits in our console log and it returns Result: Banana,Orange,Apple,Mango

Arrays are Objects

Arrays are a special type of objects. The typeof operator in JavaScript returns object for arrays.

But, JavaScript arrays are best described as arrays.

Arrays use numbers to access its "elements". In this example, person[0] returns John:

const person = ["John", "Cena", 69]; let x = person[0]

The value of x is "John".

While objects use names to access its "members". In this example, person.firstName returns "John":

const person = { firstName: "John", lastName: "Cena", age: 69 }; let x = person.firstName;

The value of x is "John"

Array Elements Can Be Objects

JavaScript variables can be objects. Arrays are special kinds of objects.

Because of this, you can have variables of different types in the same Array.

You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

const myArray = []; myArray[0] = person; // an object myArray[1] = Date.now; // a function myArray[2] = cars; // an array

Array Properties and Methods

The real strength of JavaScript arrays are the built-in array properties and methods:

cars.length; // Returns the number of elements cars.sort(); // Sorts the array

Array methods are covered in the next topic.

The length Property

The length property of an array returns the length of an array (the number of array elements):

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let x = fruits.length;

The value of x is 4 since there are four values inside the fruits array.

The length property is always one more than the highest array index.

Accessing the First and Last Array Element

To access the first array use an index of [0]:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let first = fruits[0];

The value of first is "Banana".

To access the last array use an index of [fruits.length - 1]:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let last = fruits[fruits.length - 1];

The value of last is "Mango".

Looping Array Elements

One way to loop through an array, is using a for loop:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let text = `<ul class="subtopic__ul">`; for (let i = 0; i < fruits.length; i++) { text += `<li>${fruits[i]}</li>`; } text += "</ul>"; document.getElementById("arrays__demo1").innerHTML = text;

The code above made the unordered list below through the use of loop.

You can also use the Array.forEach() function:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let text = `<ul class="subtopic__ul">`; fruits.forEach(fruit => { text += `<li>${fruit}</li>`; }); text += `</ul>`; document.getElementById("arrays__example2").innerHTML = text;

The code above generated the unordered list below using Array.forEach() function.

Adding Array Elements

The easiest way to add a new element to an array is using the push() method:

const fruits = ["Banana", "Orange", "Apple"]; fruits.push("Dragonfruit"); let x = fruits[fruits.length - 1];

The value of x is the last item of the array fruits which returns "Dragonfruit".

New element can also be added to an array using the length property:

const fruits = ["Banana", "Orange", "Apple"]; fruits[fruits.length] = "Dragonfruit"; let x = fruits[fruits.length - 1];

The value of x is still "Dragonfruit".

WARNING!

Adding elements with high indexes can create undefined "holes" in an array:

const fruits = ["Banana", "Orange", "Apple"]; fruits[10] = "Dragonfruit";

Now if we display fruits in our document, it returns "Banana,Orange,Apple,,,,,,,,Dragonfruit".

If we try and call for fruits[6] it will return undefined.

Associative Arrays

Many programming languages support arrays with named indexes.

Arrays with named indexes are called associative arrays (or hashes).

JavaScript does not support arrays with named indexes.

In JavaScript, arrays always use numbered indexes:

const person = []; person[0] = "John"; person[1] = "Cena"; person[2] = 69; person.length; person[0]; // will return "John"

WARNING!

If you use named indexes, JavaScript will redefine the array to an object.

After that, some array methods and properties will produce incorrect results:

const person = []; person["firstName"] = "John"; person["lastName"] = "Cena"; person["age"] = 69; person.length; // will return 0 person[0]; // will return undefined

The Difference Between Arrays and Objects

In JavaScript, arrays use numbered indexes.

In JavaScript, objects use named indexes.

Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays & When to use Objects.

JavaScript does not support associative arrays.

You should use objects when you want the element names to be strings (text).

You should use arrays when you want the element names to be numbers.

JavaScript new Array()

JavaScript has a built-in array constructor new Array().

But you can safely use [] instead.

These two different statements both create a new empty array named points:

const points = new Array(); const points = [];

These two different statements both create a new array containing 6 numbers:

const points = new Array(40, 100, 1, 5, 25, 10); const points = [40, 100, 1, 5, 25, 10];

Avoid using new Array(). Use [] instead.

Using new Array() can produce unexpected results.

The following is a common error:

const points = [40]; const points = new Array(40);

The two codes above are not the same and will not return the same value.

The latter will create 40 undefined values instead of an array with a single item of value 40.

How to Recognize an Array

A common question is: How do I know if a variable is an array?

The problem is that the JavaScript operator typeof returns "object":

const fruits = ["Banana", "Orange", "Apple"]; let type = typeof fruits;

The type variable will return object.

The typeof operator returns object because a JavaScript array is an object.

To solve this problem ECMAScript 5 (JavaScript 2009) defined a new method Array.isArray():

const fruits = ["Banana", "Orange", "Apple"]; let x = Array.isArray(fruits);

The value of x would be true.

We can also do this method by using the instanceof operator returns true if an object is created by a given constructor:

const fruits = ["Banana", "Orange", "Apple"]; let x = (fruits instanceof Array);

The value of x would also become true.

Nested Arrays and Objects

Values in objects can be arrays, and values in arrays can be objects:

const myObj = { name: "John", age: 69, cars: [ {name: "Ford", models: ["Fiesta", "Focus", "Mustang"]}, {name: "BMW", models: ["320", "X3", "X5"]}, {name: "Fiat", models: ["500", "Panda"]} ] };

To access arrays inside arrays, use a for-in loop for each array:

for (let i in myObj.cars) { x += "<h1>" + myObj.cars[i].name + "</h1>"; for (let j in myObj.cars[i].models) { x += myObj.cars[i].models[j]; } }

For a complete array reference go to W3Schools Complete JavaScript Array Reference

The reference contains descriptions and examples of all Array properties and methods.

JavaScript Array Methods

The following table lists the basic array methods:

Basic Array Methods
Method Description
Array length Returns the length (size) of an array
Array toString() Converts an array to a comma separated string of values
Array at() Returns an indexed element from an array
Array join() Joins all array elements into a string
Array pop() Removes the last element from an array
Array push() Adds a new element to an array
Array shift() Removes the first array element
Array unshift() Adds a new element at the beginning of an array
Array delete() Creates undefined holes in the array
Array concat() Creates a new array by merging existing arrays
Array copyWithin() Copies array elements to another position in the array
Array flat() Creates a new array from sub-array elements
Array slice() Slices out a part of an array
Array splice() Adds new items to an array
Array toSpliced() Adds new items to an array in a new array

JavaScript Array length

The length property returns the length (size) of an array:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let size = fruits.length;

The value of size returns 4.

The length property can also be used to set the length of an array:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.length = 2; console.log("Result:", fruits);

Now the console log will return us an array of ['Banana', 'Orange'] only.

JavaScript Array toString()

The toString() method returns the elements of an array as a comma separated string:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let result = fruits.toString();

The value of result returns "Banana,Orange,Apple,Mango".

Note:

Every JavaScript object has a toString() method.

The toString() method is used internally by JavaScript when an object needs to be displayed as a text (like in HTML), or when an object needs to be used as a string.

JavaScript Array at()

ES2022 intoduced the array method at():

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let result = fruits.at(2);

The value of result is Apple.

The same result will also be returned if we used [] to call out the index:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let result = fruits[2];

The at() method returns an indexed element from an array.

The at() method returns the same as [].

The at() method is supported in all modern browsers since March 2022:

Note:

Many languages allow negative bracket indexing like [-1] to access elements from the end of an object / array / string.

This is not possible in JavaScript, because [] is used for accessing both arrays and objects. obj[-1] refers to the value of key -1, not to the last property of the object.

The at() method was introduced in ES2022 to solve this problem.

JavaScript Array join()

The join() method also joins all array elements into a string.

It behaves just like toString(), but in addition you can specify the separator:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let result = fruits.join(" | ");

The value of result returns "Banana | Orange | Apple | Mango".

JavaScript Array pop() & Array push()

When you work with arrays, it is easy to remove elements and add new elements.

This is what popping and pushing is:

Popping items out of an array, or pushing items into an array.


The pop() method removes the last element from an array:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.pop();

Now fruits has the value ['Banana', 'Orange', 'Apple'] with only 3 elements left.

The pop() method returns the value that was "popped out":

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let popped = fruits.pop();

The value of popped returns "Mango".


The push() method adds a new element to an array (at the end):

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Kiwi");

Now the value for the array fruits is now ['Banana', 'Orange', 'Apple', 'Mango', 'Kiwi'].

Unlike the pop() method, the push() method returns a value of the new array length instead of the "pushed element":

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let result = fruits.push("Kiwi");

The value of result is 5.

JavaScript Array shift() & Array unshift()

Shifting is equivalent to popping, but working on the first element instead of the last.

The shift() method removes the first array element and "shifts" all other elements to a lower index:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.shift();

Now the value of the array fruits is ['Orange', 'Apple', 'Mango']

The shift() method returns the value that was "shifted out":

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let result = fruits.shift();

The value of result returns "Banana".


The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.unshift("Lemon");

Now the array fruits has a value of ['Lemon', 'Banana', 'Orange', 'Apple', 'Mango']

Unlike the shift() method, the unshift() method returns the new array length instead:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let result = fruits.unshift("Lemon");

The value of result returns 5.

Changing Elements

Array elements are accessed using their index number.

To change an array element, we need to call it using its index number and then assign it another value:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[0] = "Kiwi"

Now the value of the array fruits is ['Kiwi', 'Orange', 'Apple', 'Mango'].

JavaScript Array length

The length property provides an easy way to append a new element to an array:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[fruits.length] = "Kiwi";

The value for the array fruits now returns ['Banana', 'Orange', 'Apple', 'Mango', 'Kiwi'].

This happens since the length of an array is always greater than one of its last index.

This serves as an alternative for the push() method.

JavaScript Array delete()

WARNING!

Using delete() leaves undefined holes in the array.

Use pop() or shift() instead.

Below is an example of using the delete operator.

const fruits = ["Banana", "Orange", "Apple", "Mango"]; delete fruits [1];

Now the array fruits return ['Banana', undefined, 'Apple', 'Mango'].

Merging Arrays (Concatenating) using Array concat()

In programming languages, concatenation means joining strings end-to-end.

Concatenation "snow" and "ball" gives "snowball".

Concatenating arrays means joining arrays end-to-end.

The concat() method creates a new array by merging (concatenating) existing arrays:

const myGirls = ["Cecilie", "Lone"]; const myBoys = ["Emil", "Tobias", "Linus"]; let result = myGirls.concat(myBoys);

The value of result is an array of value ['Cecilie', 'Lone', 'Emil', 'Tobias', 'Linus'].

The order matter so if we used this code instead:

const myGirls = ["Cecilie", "Lone"]; const myBoys = ["Emil", "Tobias", "Linus"]; let result = myBoys.concat(myGirls);

The result will return an array of value ['Emil', 'Tobias', 'Linus', 'Cecilie', 'Lone'].

Note:

The concat() method does not change the existing arrays. It always returns a new array.

The concat() method can take any number of array arguments:

const arr1 = ["Cecilie", "Lone"]; const arr2 = ["Emil", "Tobias", "Linus"]; const arr3 = ["Robin", "Morgan"]; let result = arr1.concat(arr2, arr3);

The value of result is an array which returns ['Cecilie', 'Lone', 'Emil', 'Tobias', 'Linus', 'Robin', 'Morgan'].

We can also add independent strings as an argument for the concat() method:

const array = ["Cecilie", "Lone"]; let result = array.concat("John");

Now result returns an array of value ['Cecilie', 'Lone', 'John'].

Array copyWithin()

The copyWithin() method copies array elements to another position in an array:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.copyWithin(2, 0);

The code above copies the array element with index 0 and then replaces the array element in index 2.

Thus the returning value for fruits is ['Banana', 'Orange', 'Banana', 'Orange']

We can also copy index from 0 to 2 and replace the array elements starting from index 2:

const fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"]; fruits.copyWithin(2, 0, 2);

Now the array fruits returns a value of ['Banana', 'Orange', 'Banana', 'Orange', 'Kiwi'].

Note:

The copyWithin() method overwrites the existing values.

The copyWithin() method does not add items to the array.

The copyWithin() method does not change the length of the array.

Flattening an Array using JavaScript Array flat() and flatMap()

Flattening an array is the process of reducing the dimensionality of an array.

Flattening is useful when you want to convert a multi-dimensional array into a one-dimensional array.

The flat() method creates a new array with sub-array elements concatenated to a specified depth:

const myArr = [[1,2],[3,4],[5,6]]; const newArr = myArr.flat();

The array newArr returns a simpler value of [1, 2, 3, 4, 5, 6].

The flatMap() method first maps all elements of an array and then creates a new array by flattening the array:

const myArr = [1, 2, 3, 4, 5, 6]; const newArr = myArr.flatMap(x => [x, x * 10]);

The array newArr returns a value of [1, 10, 2, 20, 3, 30, 4, 40, 5, 50, 6, 60].

Splicing and Slicing Arrays

The splice() method adds new items to an array.

The slice() method slices out a piece of an array.

First, the splice() method can be used to add new items to an array:

The first parameter (2) defines the position where new elements should be added (spliced in).

The second parameter (0) defines how many elements should be removed.

The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.

Thus the returning value for the array fruits is now ['Banana', 'Orange', 'Lemon', 'Kiwi', 'Apple', 'Mango']

The splice() method returns an array with the deleted items:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let deleted = fruits.splice(2, 2, "Lemon", "Kiwi");

The value of deleted returns an array of ['Apple', 'Mango'] while the array fruits now has a value of ['Banana', 'Orange', 'Lemon', 'Kiwi'].


With clever parameter setting, you can use splice() to remove elements without leaving "holes" in the array:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(0, 1);

The first parameter (0) defines the position where new elements should be added (spliced in).

The second parameter (1) defines how many elements should be removed.

The rest of the parameters are omitted. No new elements will be added.

Thus the resulting value for the array fruits is now ['Orange', 'Apple', 'Mango'].

ES2023 added the Array toSpliced() method as a safe way to splice an array without altering the original array.

The difference between the new toSpliced() method and the old splice() method is that the new method creates a new array, keeping the original array unchanged, while the old method altered the original array.


The slice() method slices out a piece of an array into a new array:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; const fruitSliced = fruits.slice(1);

The value of fruitSliced is ['Orange', 'Apple', 'Mango'].

Note:

The slice() method creates a new array.

The slice() method does not remove any elements from the source array.

The sslice() method can take two arguments like slice(1, 3).

The method then selects elements from the start argument, and up to (but not including) the end argument:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; const fruitSliced = fruits.slice(1, 3);

The value for fruitSliced array is ['Orange', 'Apple']

If the end argument is omitted, like in the first examples, the slice() method slices out the rest of the array.

Automatic toString()

JavaScript automatically converts an array to a comma separated string when a primitive value is expected.

This is always the case when you try to output an array.

These two examples will produce the same result:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("exampleID").innerHTML = fruits.toString(); document.getElementById("exampleID").innerHTML = fruits;

Both will display "Banana,Orange,Apple,Mango"

For a complete array reference go to W3Schools Complete JavaScript Array Reference.

The reference contains descriptions and examples of all Array properties and methods.

JavaScript Sorting Arrays

Sorting arrays in JavaScript is a fundamental operation used to organize data.

Whether you're arranging numbers in ascending order or alphabetizing a list of strings, sorting helps make your data more usable and presentable

Sorting an Array

The sort() method sorts an array alphabetically:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort();

Now if we displayed fruits it will result into "Apple,Banana,Mango,Orange" which is now alphabetically ordered.

Reversing an Array

The reverse() method reverses the elements in an array:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.reverse();

Now the value of fruits when displayed is "Mango,Apple,Orange,Banana".

We can also combine sort() and reverse() to order the array in descending order:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); //sorts the array alphabetically first fruits.reverse(); // then reverse it

Now the value of fruits when displayed is "Orange,Mango,Banana,Apple"

JavaScript Array toSorted() Method

ES2023 added the toSorted() method as a safe way to sort an array without altering the original array.

The difference between toSorted() and sort() is that the first method creates a new array, keeping the original array unchanged, while the last method alters the original array:

const months = ["Jan", "Feb", "Mar", "Apr"]; const sorted = months.toSorted();

We created a new array in sorted using toSorted().

The value of sorted displays "Apr,Feb,Jan,Mar".

JavaScript Array toReversed() Method

ES2023 added the toReversed() method as a safe way to reverse an array without altering the original array.

The difference between toReversed() and reverse() is that the first method creates a new array, keeping the original array unchanged, while the last method alters the original array:

const months = ["Jan", "Feb", "Mar", "Apr"]; const reversed = months.toReversed();

Now we created a new array in reversed using "toReversed".

The display value of reversed returns "Apr,Mar,Feb,Jan".

Numeric Sort

By default, the sort() function sorts values as strings.

This works well for strings ("Apple" comes before "Banana").

If numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than "1".

Because of this, the sort() method will produce incorrect result when sorting numbers.

You can fix this by providing a compare function (callback function):

const points = [40, 100, 1, 5, 25, 10]; points.sort((a, b) => a - b);

We passed a compare function (callback function) inside the sort() function.

This method is special since if we returned a value of negative, zero, or positive it will automatically sort the numbers from lowest to highest.

We just need to supply the compare function inside it.

Thus the value of points when displayed is "1,5,10,25,40,100"

We can also use the same trick for sorting the numbers in descending order:

const points = [40, 100, 1, 5, 25, 10]; points.sort((a, b) => b - a);

Now, the value of points when displayed is "100,40,25,10,5,1".

The Compare Function

The purpose of the compare function is to define an alternative sort order.

The compare function should return a negative, zero, or positive value, depending on the arguments:

function(a, b){return a - b}; // compare function (a, b) => a - b; // also a compare function

When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.

If the result is negative, a is sorted before b.

If the result is positive, b is sorted before a.

If the result is 0, no changes are done with the sort order of the two values.

The compare function compares all the values in the array, two values at a time (a, b).

When comparing 40 and 100, the sort() method calls the compare function(40, 100).

The function calculates 40 - 100 (a - b), and since the result is negative (-60), the sort function will sort 40 as a value lower than 100.

Sorting an Array in Random Order

Using a sort function, like explained above, you can sort an numeric array in random order

We can use the Fisher Yates shuffle and was introduced in data science as early as 1938.

In JavaScript the method can be translated to this:

const points = [40, 100, 1, 5, 25, 10]; for (let i = points.length - 1; i > 0; i--) { let j = Math.floor(Math.random() * (i + 1)); let k = points[i]; points[i] = points[j]; points[j] = k; }

We haven't learned about for loops yet but for now we can use this code to randomized our array.

We will learn more about for loops in later topics.

Find the Lowest (or Highest) Array Value

There are no built-in functions for finding the max or min value in an array.

To find the lowest or highest value you have 3 options:

  • Sort the array and read the first or last element
  • Use Math.min() or Math.max()
  • Write a home made function

Find Min or Max with sort()

After you have sorted an array, you can use the index to obtain the highest and lowest values:

const points = [40, 100, 1, 5, 25, 10]; points.sort((a, b) => a - b) let max = points.at(-1); // returns 100 let min = points.at(0); // returns 1

Note:

Sorting a whole array is a very inefficient method if you only want to find the highest (or lowest) value.

Using Math.min() & Math.max() on an Array

You can use Math.min.apply to find the lowest number in an array:

const points = [40, 100, 1, 5, 25, 10]; function myArrayMin(arr) { return Math.min.apply(null, arr); } let min = myArrayMin(points);

The value of min returns 1.

This is an old way of spreading array elements inside an array.

We will still use Math.min().

But now we will use the ... (spread operator):

Math.min(...points);

The code above is the same as the old one below:

Math.min.apply(null, points);

We can also use Math.max.apply to find the highest number in an array:

The same code and logic applies for this method as with the previous one.

JavaScript Array Minimum & Maximum Home Made Method

There is no built-in function for finding the lowest value in a JavaScript array.

The fastest code to find the lowest number is to use a home made method.

This function loops through an array comparing each value with the lowest value found:

const points = [40, 100, 1, 5, 25, 10]; function myArrayMin(arr) { let length = arr.length; let min = Infinity; while (length--) { if (arr[length] < min) { min = arr[length]; } } return min; } console.log("Result:", myArrayMin(points))

Our console log will return a value of 1.

This same logic goes with finding the maximum number in an array using a home made method:

const points = [40, 100, 1, 5, 25, 10]; function myArrayMax(arr) { let length = arr.length; let max = -Infinity; while (length--) { if (arr[length] > max) { max = arr[length]; } } return max; } console.log("Result:", myArrayMax(points))

Our console log will return a value of 100.

Don't worry if you don't understand quite yet the while...loop.

Just know that it is used to loop all the numbers and compare it each other and then finally returns the final value.

We will learn more about while...loop in later topics.

Sorting Object Arrays

JavaScript arrays often contain objects:

const cars = [ {type:"Volvo", year:2016}, {type:"Saab", year:2001}, {type:"BMW", year:2010} ];

Even if objects have properties of different data types, the sort() method can be used to sort the array.

The solution is to write a compare function to compare the property values:

const cars = [ {type:"Volvo", year:2016}, {type:"Saab", year:2001}, {type:"BMW", year:2010} ]; cars.sort((a, b) => a.year - b.year);

Now cars will have its array items arranged in ascending order from year 2001 to year 2016.


For a complete array reference go to W3Schools Complete JavaScript Array Reference.

The reference contains descriptions and examples of all Array properties and methods.

JavaScript Array Iteration

Array iteration methods operate on every array item:

Array Iteration Methods
Method Description
Array forEach Calls a function for each array element
Array map() Creates a new array by performing a function on each element
Array flatMap() Creates a new array by mapping and flattening all elements
Array filter() Creates a new array with all elements that pass a test
Array reduce() Runs a function on each element to produce a single value
Array reduceRight() Runs a function on each element to produce a single value
Array every() Returns true if every elements pass a test
Array some() Returns true if some elements pass a test
Array from() Returns an array object from an iterable object
Array keys() Returns an array with the keys of an array
Array entries() Returns an array with the entries of an array
Array with() Update elements without altering the original array
Array Spread (...) Expands an array into individual elements
Array Rest (...) Destruct an array and collect the leftovers

JavaScript Array forEach()

The forEach() method calls a function (a callback function) once for each array element:

const numbers = [45, 4, 9, 16, 25]; let txt = ""; numbers.forEach((value, index, array) => { txt += ` ${value} |`; }); console.log("Result:", txt)

The value of txt will become " 45 | 4 | 9 | 16 | 25 |"

Notice that for array methods, the callback function (passing function) accepts three parameters, the value, index, and array which all pertains to the array we applied the method to.

The value parameter refers to the array element, the index parameter refers to the index of the array element, and lastly the array parameter refers to the whole array itself.

In our example, we are only using one parameter which is the value one.

JavaScript Array map()

The map() method creates a new array by performing a function on each array element.

The map() method does not execute the function for array elements without values.

The map() method does not change the original array.

This example multiplies each array value by 2:

const numbers = [45, 4, 9, 16, 25]; const numbersDouble = numbers.map(value => value *= 2);

With this code, the value of numbersDouble returns [90, 8, 18, 32, 50].

JavaScript Array flatMap()

ES2019 added the Array flatMap() method to JavaScript.

The flatMap() method first maps all elements of an array and then creates a new array by flattening the array:

const myArr = [1, 2, 3, 4, 5, 6]; const newArr = myArr.flatMap(value => [value, value * 2]);

With this example, we explicitly tell the code that myArr should be mapped first and each of the array elements (value) should become an array themselves and assigned the value [value, value * 2].

Now that we have an array of arrays after mapping, flattening occurs for newArr returning "[1, 2, 2, 4, 3, 6, 4, 8, 5, 10, 6, 12]"

JavaScript Array filter()

The filter() method creates a new array with array elements that pass a test.

This example creates a new array from elements with a value larger than 69:

const numbers = [91, 100, 45, 4, 125, 9, 16, 25, 70, 77]; const greaterThan69 = numbers.filter(x => x > 69);

The variable greaterThan69 returns an array of value [91, 100, 125, 70, 77].

With filter() method, we need to create a callback function that returns a boolean value to be able to "filter" the array elements that passes the test (i.e. returns true).

JavaScript Array reduce()

The reduce() method runs a function on each array element to produce a single value.

The reduce() method works from left-to-right in the array.

The reduce() method does not reduce the original array:

const numbers = [91, 100, 45, 4, 125, 9, 16, 25, 70, 77]; const sum = numbers.reduce((total, value, index, array) => total + value);

Let's break it down first by saying that the reduce() method accepts a callback function with 4 parameters (total, value, index, array).

The last three is the same as the first array methods, however the total parameter refers to the initial value or the second optional parameter of the reduce() method.

In our example we have set no initial value so the value for total is equal to value of the first array element and the reduce() method will start iterating at the second array element.

So in our case, the initial value for total is 91 and then added to the rest of the value.

Finally this method will produce a single result which in this case is a total of all the values inside the array.

The final value for sum returns 562.

Below is the syntax for reduce():

array.reduce(callback, initial-value);

Where callback has 4 parameters (i.e. total, value, index, array).

The reduceRight() method is similar with reduce() but the only difference is that the former works from right-to-left in the array.

JavaScript Array every()

The every() method checks if all array values pass a test.

This example checks if all array values are larger than 69:

const numbers = [91, 100, 45, 4, 125, 9, 16, 25, 70, 77]; const result = numbers.every(value => value > 69);

Just like the other array methods, we pass a callback function in every() method and this function accepts three parameters (value, index, array).

In our example, we only used value and our callback function returns a boolean value.

The every() method will immediately return false as soon as the callback returns false for any element. Only if every single element passes the test will it return true.

In this case, result returns us a value of false.

JavaScript Array some()

The some() method checks if some array values pass a test.

This example checks if some array values are larger than 69:

const numbers = [91, 100, 45, 4, 125, 9, 16, 25, 70, 77]; const result = numbers.some(value => value > 69);

Just like the other array methods, we pass a callback function in some() method and this function accepts three parameters (value, index, array).

In our example, we only used value and our callback function returns a boolean value.

The some() method will immediately return true as soon as the callback returns true for any element. Only if some single element passes the test will it return true.

In this case, result returns us a value of true.

JavaScript Array.from()

The Array.from() method returns an Array object from any object with a length property or any iterable object (i.e. strings, NodeList, argument, HTMLCollection, map/set).

In this example below, we create an array from a simple string:

const myArray = Array.from("Hello World");

The variable myArray returns an array with a value of ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'].

JavaScript Array keys()

The Array.keys() method returns an Array Iterator object with the keys of an array:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; const keys = fruits.keys(); console.log("Result:", Array.from(keys));

Arrays also have keys in the form of numeric indexes so when we used the keys() method, we extracted an iterator representing the indexes and assigned in the keys variable.

Finally, to show the content of the iterator keys, we used Array.from() in our console log to give us the values inside the iterator in array form.

The console log returns us a value of [0, 1, 2, 3] as expected.

JavaScript Array entries()

The entries() method returns an Array Iterator object with key/value pairs:

The entries() method does not change the original array:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; const entries = fruits.entries(); console.log("Result:", Array.from(entries));

Since entries() method returns an iterator, we used Array.from() to display the iterator content inside in array form.

Now the console log returns us an array of value [[0, 'Banana'], [1, 'Orange'], [2, 'Apple'], [3, 'Mango']].

JavaScript Array with() Method

ES2023 added the Array with() method as a safe way to update elements in an array without altering the original array.

The with() method accepts 2 parameters where the first is the index number of the element you want to update and the second is the updated value of the element:

const months = ["January", "February", "Mar", "April"]; const monthsUpdated = months.with(2, "March");

Now, monthsUpdated returns an array of value ['January', 'February', 'March', 'April'].

JavaScript Array Spread (...)

The ... operator expands an array into individual elements.

This can be used join arrays:

const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; const arrCombined = [...arr1, ...arr2];

First the ... spread operator "spreads" the contents of arr1 and arr2 and are now part of a bigger array (i.e. arrCombined) as its elements.

Finally, the returning value for arrCombined is an array of value [1, 2, 3, 4, 5, 6].

The spread operator (...) can also be used to copy an array:

const arr1 = [1, 2, 3]; const arr1Copy = [...arr1];

Now the value of arr1Copy is the same as arr1 which both returns [1, 2, 3].

And lastly, the spread operator (...) can be used to pass arguments to a function:

const numbers = [23,55,21,87,56]; const min = Math.min(...numbers); const max = Math.max(...numbers);

The value for min returns 21 while the value for max returns 87.

JavaScript Array Rest (...)

The rest operator (...) allows us to destructure an array and collect the leftovers:

let a, rest; const arr1 = [1,2,3,4,5,6,7,8]; [a, ...rest] = arr1;

In this example we used a basic destructuring and assigned the first element inside arr1 to the variable a and the remaining elements to the variable rest.

Thus, the value of a will have 1 and the value of rest is a new array that returns [2, 3, 4, 5, 6, 7, 8].

Note that ...rest must always be the last variable in the destructuring assignment and that destructuring does not affect the original array.


For a complete Array reference, go to W3Schools Complete JavaScript Array Reference.

The reference contains descriptions and examples of all Array properties and methods.

JavaScript Array Const

In 2015, JavaScript introduced an important new keyword: const.

It has become a common practice to declare arrays using const:

const cars = ["Saab", "Volvo", "BMW"];

Cannot be Reassigned

An array declared with const cannot be reassigned:

const cars = ["Saab", "Volvo", "BMW"]; cars = ["Toyota", "Volvo", "Audi"]; // ERROR

Arrays are Not Constants

The keyword const is a little misleading.

It does NOT define a constant array. It defines a constant reference to an array.

Because of this, we can still change the elements of a constant array.

Elements Can be Reassigned

You can change the elements of a constant array:

const cars = ["Saab", "Volvo", "BMW"]; cars[0] = "Toyota"; cars.push("Audi");

Now the returning value of the constant array cars is ["Toyota", "Volvo", "BMW", "Audi"].

Assigned when Declared

JavaScript const variables must be assigned a value when they are declared.

Meaning: An array declared with const must be initialized when it is declared.

Using const without initializing the array is a syntax error:

const cars; cars = ["Saab", "Volvo", "BMW"]; // ERROR

Arrays declared with var can be initialized at any time.

You can even use the array before it is declared:

cars = ["Saab", "Volvo", "BMW"]; var cars;

However, it is still better to use let or const keywords for variable declarations.

Const Block Scope

An array declared with const has Block Scope.

An array declared in a block is not the same as an array declared outside the block:

const cars = ["Saab", "Volvo", "BMW"]; // Here cars[0] is "Saab" { const cars = ["Toyota", "Volvo", "BMW"]; // Here cars[0] is "Toyota" } // Here cars[0] is "Saab"

An array declared with var does not have block scope:

var cars = ["Saab", "Volvo", "BMW"]; // Here cars[0] is "Saab" { var cars = ["Toyota", "Volvo", "BMW"]; // Here cars[0] is "Toyota" } // Here cars[0] is "Toyota"

We will learn more about block scopes in later topics.

Redeclaring Arrays

Redeclaring an array declared with var is allowed anywhere in a program:

var cars = ["Volvo", "BMW"]; // Allowed var cars = ["Toyota", "BMW"]; // Allowed cars = ["Volvo", "Saab"]; // Allowed

Redeclaring or reassigning an array to const, in the same scope, or in the same block, is not allowed:

var cars = ["Volvo", "BMW"]; // Allowed const cars = ["Volvo", "BMW"]; // Not allowed { var cars = ["Volvo", "BMW"]; // Allowed const cars = ["Volvo", "BMW"]; // Not allowed }

Redeclaring or reassigning an existing const array, in the same scope, or in the same block, is not allowed:

const cars = ["Volvo", "BMW"]; // Allowed const cars = ["Volvo", "BMW"]; // Not allowed var cars = ["Volvo", "BMW"]; // Not allowed cars = ["Volvo", "BMW"]; // Not allowed { const cars = ["Volvo", "BMW"]; // Allowed const cars = ["Volvo", "BMW"]; // Not allowed var cars = ["Volvo", "BMW"]; // Not allowed cars = ["Volvo", "BMW"]; // Not allowed }

Redeclaring an array with const, in another scope, or in another block, is allowed:

const cars = ["Volvo", "BMW"]; // Allowed { const cars = ["Volvo", "BMW"]; // Allowed } { const cars = ["Volvo", "BMW"]; // Allowed }

For a complete array reference go to W3Schools Complete JavaScript Array Reference.

The reference contains descriptions and examples of all Array properties and methods.

JavaScript Date Objects

JavaScript uses the built-in Date object to handle dates and times.

You can create dates, get the current time, and manipulate values like days, months, or years.

It's a key tool for building features like clocks, calendars, or time-based logic.

Date Objects are Static

Date objects are static. The "clock" is not "running".

The computer clock is ticking, date objects are not.

JavaScript Date Output

By default, JavaScript will use the browser's time zone and display a date as a full text string:

const date = new Date(); document.getElementById("date__example1").innerHTML = `${date}`;

The code above generates the text below:

We will learn much more about how to display dates, later in this topic.

Creating Date Objects

Date objects are created with the new Date() constructor.

There are 9 ways to create a new date object:

  • new Date()
  • new Date(date string)
  • new Date(year,month)
  • new Date(year,month,day)
  • new Date(year,month,day,hours)
  • new Date(year,month,day,hours,minutes)
  • new Date(year,month,day,hours,minutes,seconds)
  • new Date(year,month,day,hours,minutes,seconds,ms)
  • new Date(milliseconds)

JavaScript new Date()

new Date() creates a date object with the current date and time:

Demo 1: You have a Date Tonight?

Click the button if you want to get a date.

Explanation:

new Date(date string)

new Date(date string) creates a date object from a date string:

const date = new Date("October 13, 2014 11:13:00");

This code will return a value of Mon Oct 13 2014 11:13:00 GMT+0800 (Philippine Standard Time).

While this code:

const d = new Date("2022-03-25");

Will return a value of Fri Mar 25 2022 08:00:00 GMT+0800 (Philippine Standard Time).

We will learn more about date string formats in later topics.

new Date(year, month, ...)

new Date(year, month, ...) creates a date object with a specified date and time.

7 numbers specify year, month, day, hour, minute, second, and millisecond (in that order):

const date = new Date(2018, 11, 24, 10, 33, 30, 0);

The resulting value for date is Mon Dec 24 2018 10:33:30 GMT+0800 (Philippine Standard Time)

Note:

JavaScript counts months from 0 to 11.

Thus, January is assigned 0 and December is assigned 11.

Specifying a month higher than 11, will not result in an error but add the overflow to the next year.

Both of these codes return the same value:

const date = new Date(2018, 15, 24, 10, 33, 30); const date = new Date(2019, 3, 24, 10, 33, 30);

Specifying a day higher than max, will not result in an error but add the overflowto the next month.

Both of these codes return the same value:

const date = new Date(2018, 5, 35, 10, 33, 30); const date = new Date(2018, 6, 5, 10, 33, 30);

Using 6, 4, 3, or 2 Numbers

6 numbers specify year, month, day, hour, minute, second:

const date = new Date(2018, 11, 24, 10, 33, 30);

This results to Mon Dec 24 2018 10:33:30 GMT+0800 (Philippine Standard Time)


5 numbers specify year, month, day, hour, and minute:

const date = new Date(2018, 11, 24, 10, 33);

This results to Mon Dec 24 2018 10:33:00 GMT+0800 (Philippine Standard Time).


4 numbers specify year, month, day, and hour:

const date = new Date(2018, 11, 24, 10);

This results to Mon Dec 24 2018 10:00:00 GMT+0800 (Philippine Standard Time).


3 numbers specify year, month, and day:

const date = new Date(2018, 11, 24);

This results to Mon Dec 24 2018 00:00:00 GMT+0800 (Philippine Standard Time).


2 numbers specify year and month:

const date = new Date(2018, 11);

This results to Sat Dec 01 2018 00:00:00 GMT+0800 (Philippine Standard Time).

Note:

You cannot omit month. If you supply only one parameter it will be treated as milliseconds.

Only 1 number specify milliseconds:

const date = new Date(2018);

This results to Thu Jan 01 1970 08:00:02 GMT+0800 (Philippine Standard Time).

Previous Century

One and two digit years will be interpreted as 19xx:

const date1 = new Date(99, 11, 24); const date2 = new Date(9, 11, 24);

The variable date1 returns a value of Fri Dec 24 1999 00:00:00 GMT+0800 (Philippine Standard Time) while date2 returns a value of Fri Dec 24 1909 00:00:00 GMT+0800 (Philippine Standard Time).

JavaScript Stores Dates as Milliseconds

JavaScript stores dates as number of milliseconds since January 01, 1970.

Zero time is January 01, 1970 00:00:00 UTC.

One day (24 hours) is 86 400 000 milliseconds.

new Date(milliseconds) creates a new date object as milliseconds plus zero time.

01 January 1970 plus 100 000 000 000 milliseconds is:

const date = new Date(100000000000);

Which has a value of Sat Mar 03 1973 17:46:40 GMT+0800 (Philippine Standard Time).


January 01 1970 minus 100 000 000 000 milliseconds is:

const date = new Date(-100000000000);

Which has a value of Mon Oct 31 1966 22:13:20 GMT+0800 (Philippine Standard Time).


January 01 1970 plus 24 hours is:

const date = new Date(1000 * 60 * 60 * 24);

Which has a value of Fri Jan 02 1970 08:00:00 GMT+0800 (Philippine Standard Time).


Lastly, 01 January 1970 plus 0 milliseconds is:

const date = new Date(0);

Is just Thu Jan 01 1970 08:00:00 GMT+0800 (Philippine Standard Time)

Date Methods

When a date object is created, a number of methods allow you to operate on it.

Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of date objects, using either local time or UTC (universal, or GMT) time.

Date methods and time zones are covered more in later topics.

Displaying Dates

JavaScript will (by default) output dates using the toString() method. This is a string representation of the date, including the time zone. The format is specified in the ECMAScript specification:

Tue Jun 17 2025 14:34:12 GMT+0800 (Philippine Standard Time)

When you display a date object in HTML, it is automatically converted to a string, with the toString() method:

const date = new Date(); // date here is converted to string when displayed

The toDateString() method converts a date to a more readable format:

const date = new Date(2025, 2, 22); date.toDateString();

date.toDateString() will display a value of "Sat Mar 22 2025".


The toUTCString() method converts a date to a string using the UTC standard:

const date = new Date(2025, 2, 22); date.toUTCString();

date.toUTCString() will display a value of "Fri, 21 Mar 2025 16:00:00 GMT".


The toISOString() mmethod converts a date to a string using the ISO standard:

const date = new Date(2025, 2, 22); date.toISOString();

date.toISOString(); will display a value of "2025-03-21T16:00:00.000Z".


For a complete Date reference, go to W3Schools Complete JavaScript Date Reference.

The reference contains descriptions and examples of all Date properties and methods.

JavaScript Date Formats

There are generally 3 types of JavaScript date input formats:

Date Input Formats
Type Example
ISO Date "2015-03-25" (The International Standard)
Short Date "03/25/2015"
Long Date "Mar 25 2015" or "25 Mar 2015"

The ISO format follows a strict standard in JavaScript.

The other formats are not so well defined and might be browser specific.

JavaScript Date Output

Independent of input format, JavaScript will (by default) output dates in full text string format:

const date = new Date(2025, 2, 22);

The variable date returns a string of value "Sat Mar 22 2025 00:00:00 GMT+0800 (Philippine Standard Time)".

JavaScript ISO Dates

ISO 8601 is the international standard for the representation of dates and times.

The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date format:

// this is a complete date const date = new Date("2025-03-22");

The value for date is "Sat Mar 22 2025 08:00:00 GMT+0800 (Philippine Standard Time)".

The computed date will be relative to your time zone.

Depending on your time zone, the result above will vary between March 21 and March 22.

ISO Dates (Year and Month)

ISO dates can be written without specifying the day (YYYY-MM):

const date = new Date("2025-03");

The resulting value for date is "Sat Mar 01 2025 08:00:00 GMT+0800 (Philippine Standard Time)"

Time zones will vary the result above between February 28 and March 01.

ISO Dates (Only Year)

ISO dates can be written without month and day (YYYY):

const date = new Date("2025");

The resulting value for date is "Wed Jan 01 2025 08:00:00 GMT+0800 (Philippine Standard Time)".

Time zones will vary the result above between December 31 2024 and January 01 2025.

ISO Dates (Date-Time)

ISO dates can be written with added hours, minutes, and seconds (YYYY-MM-DDTHH:MM:SSZ):

const date = new Date("2025-03-22T12:00:00Z");

The date variable returns a value of "Sat Mar 22 2025 20:00:00 GMT+0800 (Philippine Standard Time)"

Date and time is separated with a capital T.

UTC time is defined with a capital letter Z.

If you want to modify the time relative to UTC, remove the Z and add +HH:MM or -HH:MM instead:

const date = new Date("2025-03-22T12:00:00-06:30");

Now the date variable returns a value of "Sun Mar 23 2025 02:30:00 GMT+0800 (Philippine Standard Time)"

Note:

UTC (Universal Time Coordinated) is the same as GMT (Greenwich Mean Time).

Omitting T or Z in a date-time string can give different results in different browsers.

Time Zones

When setting a date, without specifying the time zone, JavaScript will use the browser's time zone.

When getting a date, without specifying the time zone, the result is converted to the browser's time zone.

In other words, if a date/time is created in GMT (Greenwich Mean Time), the date/time will be converted to CDT (Central US Daylight Time) if a user browses from central US.

JavaScript Short Dates.

Short dates are written with an "MM/DD/YYYY" syntax like this:

const date = new Date("03/22/2025");

WARNING!

In some browsers, months or days with no leading zeroes may produce an error:

const date = new Date("2025-3-22"); // no leading zero on month

The behavior of "YYYY/MM/DD" is undefined. Some browsers will try to guess the format. Some will return NaN.

const date = new Date("2025/03/22");

The behavior of "DD-MM-YYYY" is also undefined. Some browsers will try to guess the format. Some will return NaN.

const date = new Date("22/03/2025");

JavaScript Long Dates.

Long dates are most often written with a "MMM DD YYYY" syntax like this:

const date = new Date("Mar 22 2025");

Month and day can be in any order:

const date = new Date("22 Mar 2025");

And, month can be written in full (January), or abbreviated (Jan):

const date = new Date("March 22 2025");

Commas are ignored. Names are case insensitive:

const date = new Date("march 22, 2025");

Date Input - Parsing Dates

If you have a valid date string, you can use the Date.parse() method to convert it to milliseconds.

Date.parse() returns the number of milliseconds between the date and January 1, 1970:

const date = new Date("March 22, 2025"); const dateParsed = Date.parse(date);

The returning value of dateParsed is 1742572800000.

You can then use the number of milliseconds to convert it to a date object:

const dateParsed = Date.parse("March 22, 2025"); const date = new Date(dateParsed)

Now the value for date goes back to "Sat Mar 22 2025 00:00:00 GMT+0800 (Philippine Standard Time)".


For a complete Date reference, go to W3Schools Complete JavaScript Date Reference.

The reference contains descriptions and examples of all Date properties and methods.

JavaScript Get Date Methods

JavaScript provides powerful built-in Date methods that allow developers to work with dates and times.

The Date object gives you access to the current time, day, month, year and more making it possible to create dynamic and time-aware web applications with just a few lines of code.

The new Date() Constructor

In JavaScript, date objects are created with new Date().

new Date() returns a date object with the current date and time.

So if we want to get the current date and time, we code it like this:

const date = new Date();

Date Get Methods

The following is a table for date get methods:

Date Get Methods
Method Description
getFullYear() Get year as a four digit number (yyyy)
getMonth() Get month as a number (0-11)
getDate() Get day as a number (1-31)
getDay() Get weekday as a number (0-6)
getHours() Get hour (0-23)
getMinutes() Get minute (0-59)
getSeconds() Get second (0-59)
getMilliseconds() Get millisecond (0-999)
getTime() Get time (milliseconds since January 1, 1970)

Note:

The get methods above return Local time.

Universal time (UTC) is documented at the bottom of this page.

The get methods return information from existing date objects.

In a date object, the time is static. The "clock" is not "running".

The time in a date object is NOT the same as current time.

The getFullYear() Method

The getFullYear() method returns the year of a date as a four digit number:

const date = new Date("March 22, 2025"); const year = date.getFullYear();

The variable year returns a value of 2025.

WARNING!

Old JavaScript code might use the non-standard method getYear().

getYear() is supposed to return a 2-digit year.

getYear() is deprecated. Do not use it!

The getMonth() Method

The getMonth() method returns the month of a date as a number (0-11).

Note:

In JavaScript, January is month number 0, February is number 1, ...

Finally, December is month number 11.

Say you have this code:

const date = new Date("March 22, 2025"); const month = date.getMonth();

The returning value for month is 2.

Note:

You can use an array of names to return the month as a name:

const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; const date = new Date("2025-03-22"); const monthIndex = date.getMonth(); const monthName = months[monthIndex];

The value for monthName returns "March".

The getDate() Method

The getDate() method returns the day of a date as a number (1-31):

const date = new Date("2025-03-22"); const d = date.getDate();

The value of d returns 22.

The getHours() Method

The getHours() method returns the hours of a date as a number (0-23):

const date = new Date("2025-03-22"); const hours = date.getHours();

The value of hours is 8 (local hours).

The getMinutes() Method

The getMinutes() method returns the minutes of a date as a number (0-59):

const date = new Date("2025-03-22"); const minutes = date.getMinutes();

The value of minutes is 0.

The getSeconds() Method

The getSeconds() method returns the seconds of a date as a number (0-59):

const date = new Date("2025-03-22"); const seconds = date.getSeconds();

The value of seconds is 0.

The getMilliseconds() Method

The getMilliseconds() method returns the milliseconds of a date as a number (0-999):

const date = new Date("2025-03-22"); const ms = date.getMilliseconds();

The value for ms is 0.

The getDay() Method

The getDay() method returns the weekday of a date as a number (0-6).

Note:

In JavaScript, the first day of the week (day 0) is Sunday.

Some countries in the world consider the first day of the week to be Monday.

Say you have this code:

const date = new Date("2025-03-22"); const day = date.getDay();

The value for day is 6 (a Saturday).

Note:

You can use an array of names, and getDay() to return weekday as a name:

const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; const date = new Date("2025-03-22"); const dayIndex = date.getDay(); const dayName = days[dayIndex];

The value for dayName returns "Saturday".

The getTime() Method

The getTime() method returns the number of milliseconds since January 1, 1970:

const date = new Date("2025-03-22"); const time = date.getTime();

The value for time is 1742601600000.

The Date.now() Method

Date.now() returns the number of milliseconds since January 1, 1970.

Date.now() is a static method of the Date object.

You cannot use it on a date object like myDate.now().

The syntax is always Date.now().

UTC Date Get Methods

Method Description
getUTCDate() Returns the UTC date
getUTCFullYear() Returns the UTC year
getUTCMonth() Returns the UTC month
getUTCDay() Returns the UTC day
getUTCHours() Returns the UTC hour
getUTCMinutes() Returns the UTC minutes
getUTCSeconds() Returns the UTC seconds
getUTCMilliseconds() Returns the UTC milliseconds

UTC methods use UTC time (Coordinated Universal Time).

UTC time is the same as GMT (Greenwich Mean Time).

The difference between Local time and UTC time can be up to 24 hours.

The getTimezoneOffset() Method

The getTimezoneOffset() method returns the difference (in minutes) between local time and UTC time:

const date = new Date(); const offset = date.getTimezoneOffset();

The value of offset is -480(for PH time).

For a complete Date reference, go to W3Schools Complete JavaScript Date Reference.

The reference contains descriptions and examples of all Date properties and methods.

JavaScript Set Date Methods

Set Date methods let you set date values (years, months, days, hours, minutes, seconds, milliseconds) for a Date Object.

Set Date Methods

Set Date methods are used for setting a part of a date:

Set Date Methods Table
Method Description
setDate() Set the day as a number (1-31)
setFullYear() Set the year (yyyy)
setHours() Set the hour (0-23)
setMilliseconds() Set the milliseconds (0-999)
setMinutes() Set the minutes (0-59)
setMonth() Set the month (0-11)
setSeconds() Set the seconds (0-59)
setTime() Set the time (milliseconds since January 1, 1970)

The setFullYear() Method

The setFullYear() method sets the year of a date object. In this example to 2020:

const date = new Date("2025-03-22"); date.setFullYear("2020");

The value for date is now "Sun Mar 22 2020 08:00:00 GMT+0800 (Philippine Standard Time)".

The setFullYear() method can optionally set month and day:

const date = new Date("2025-03-22"); date.setFullYear(2020, 0, 1);

The value of date is now "Wed Jan 01 2020 08:00:00 GMT+0800 (Philippine Standard Time)"

The setMonth() Method

The setMonth() method sets the month of a date object (0-11):

const date = new Date("2025-03-22"); date.setMonth(11);

The value of date is now "Mon Dec 22 2025 08:00:00 GMT+0800 (Philippine Standard Time)".

The setDate() Method

The setDate() method sets the day of a date object (1-31):

const date = new Date("2025-03-22"); date.setDate(7);

The value of date is now "Fri Mar 07 2025 08:00:00 GMT+0800 (Philippine Standard Time)"

The setDate() method can also be used to add days to a date:

const date = new Date("2025-03-22"); date.setDate(date.getDate() + 30);

The value of date is now "Mon Apr 21 2025 08:00:00 GMT+0800 (Philippine Standard Time)"

Note:

If adding days shifts the month or year, the changes are handled automatically by the Date object.

The setHours() Method

The setHours() method sets the hours of a date object (0-23):

const date = new Date("2025-03-22"); date.setHours(12);

The value of date is now "Sat Mar 22 2025 12:00:00 GMT+0800 (Philippine Standard Time)"

The setHours() method can also be used to set minutes and seconds:

const date = new Date("2025-03-22"); date.setHours(12, 12, 12);

The value of date is now "Result: Sat Mar 22 2025 12:12:12 GMT+0800 (Philippine Standard Time)"

The setMinutes() Method

The setMinutes() method sets the minutes of a date object (0-59):

const date = new Date("2025-03-22"); date.setMinutes(30);

The value of date is now "Sat Mar 22 2025 08:30:00 GMT+0800 (Philippine Standard Time)"

The setSeconds() Method

The setSeconds() method sets the seconds of a date object (0-59):

const date = new Date("2025-03-22"); date.setSeconds(30);

The value of date is now "Sat Mar 22 2025 08:00:30 GMT+0800 (Philippine Standard Time)"

Compare Dates

Dates can easily be compared.

The following example compares an example date with January 1, 2100:

const date = new Date("2025-03-22"); const dateFuture = new Date("2100-01-01"); const isBefore = date < dateFuture;

The value of isBefore returns true.

Note:

JavaScript counts months from 0 to 11. January is 0. December is 11.


For a complete Date reference, go to W3Schools Complete JavaScript Date Reference.

The reference contains descriptions and examples of all Date properties and methods.

JavaScript Math Object

The JavaScript Math object allows you to perform mathematical tasks on numbers:

const pi = Math.PI;

The code above uses Math.PI which returns a value of 3.141592653589793.

The Math Object

Unlike other objects, the Math object has no constructor.

The Math object is static.

All methods and properties can be used without creating a Math object first.

Math Properties (Constants)

The syntax for any Math property is Math.property.

JavaScript provides 8 mathematical constants that can be accessed as Math properties:

Math Constants Table
Constant Value
Math.E returns Euler's number
Math.PI returns PI
Math.SQRT2 returns the square root of 2
Math.SQRT1_2 returns the square root of 1/2
Math.LN2 returns the natural logarithm of 2
Math.LN10 returns the natural logarithm of 10
Math.LOG2E returns base 2 logarithm of E
Math.LOG10E returns base 10 logarithm of E

Math Methods

The syntax for Math any methods is : Math.method(number)

There are 4 common methods to round a number to an integer:

Math Rounding Method Table
Method Value
Math.round(x) Returns x rounded to its nearest integer
Math.ceil(x) Returns x rounded up to its nearest integer
Math.floor(x) Returns x rounded down to its nearest integer
Math.trunc(x) Returns the integer part of x (new in ES6)

Math.round()

Math.round(x) returns the nearest integer:

const round1 = Math.round(69.69); // returns 70 const round2 = Math.round(69.59); // returns 70 const round3 = Math.round(69.49); // returns 69

Math.ceil()

Math.ceil(x) returns the value of x rounded up to its nearest integer:

const roundUp1 = Math.ceil(69.69); // returns 70 const roundUp2 = Math.ceil(69.49); // returns 70 const roundUp3 = Math.ceil(-69.69); // returns -69

Math.floor()

Math.floor(x) returns the value of x rounded down to its nearest integer:

const roundDown1 = Math.floor(69.69); // returns 69 const roundDown2 = Math.floor(69.49); // returns 69 const roundDown3 = Math.floor(-69.69); // returns -70

Math.trunc()

Math.trunc(x) returns the integer part of x:

const roundTrunc1 = Math.trunc(69.69); // returns 69 const roundTrunc2 = Math.trunc(69.49); // returns 69 const roundTrunc3 = Math.trunc(-69.69); // returns -69

Math.sign()

Math.sign(x) returns if x is negative, null or positive:

const sign1 = Math.sign(69); // returns 1 const sign2 = Math.sign(-69); // returns -1 const sign3 = Math.sign(0); // returns 0

Math.pow()

Math.pow(x, y) returns the value of x to the power of y:

const power = Math.pow(69, 3); // returns 328509

Math.sqrt()

Math.sqrt(x) returns the square root of x:

const sqrt = Math.sqrt(69); // returns 8.306623862918075

Math.abs()

Math.abs(x) returns the absolute (positive) value of x:

const abs = Math.abs(-69); // returns 69

Math.sin()

Math.sin(x) returns the sine (a value between -1 and 1) of the angle x (given in radians).

If you want to use degrees instead of radians, you have to convert degrees to radians:

Angle in radians = Angle in degrees x PI / 180.

const number = Math.sin(90 * Math.PI / 180) // returns 1

Math.cos()

Math.cos(x) returns the cosine (a value between -1 and 1) of the angle x (given in radians).

If you want to use degrees instead of radians, you have to convert degrees to radians:

Angle in radians = Angle in degrees x PI / 180.

const number = Math.cos(0 * Math.PI / 180) // returns 1 (cos 0 deg is 1)

Math.min() and Math.max()

Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments:

const min = Math.min(0, 150, 30, 20, -8, -200); // returns -200 const max = Math.max(0, 150, 30, 20, -8, -200); // returns 150

Math.random()

Math.random() returns a random number between 0 (inclusive), and 1 (exclusive):

const random = Math.random(); // returns a value of 0 up to 0.999...

We will learn more about Math.random() in later topics.

The Math.log() Method

Math.log(x) returns the natural logarithm of x.

The natural logarithm returns the time needed to reach a certain level of growth:

const log = Math.log(69); // returns 4.23410650459726

The Math.log2() Method

Math.log2(x) returns the base 2 logarithm of x.

How many times must we multiply 2 to get 69?

const log2 = Math.log2(69); // returns 6.108524456778169

The Math.log10() Method

Math.log10(x) returns the base 10 logarithm of x.

How many times must we multiply 10 to get 69?

const log10 = Math.log10(69); // returns 1.8388490907372552

For a complete reference, go to W3Schools Complete Math Object Reference.

The reference contains descriptions and examples of all Math properties and methods.

JavaScript Random

Math.random() returns a random number between 0 (inclusive), and 1 (exclusive):

Math.random() always returns a number lower than 1.

JavaScript Random Integers

Math.random() used with Math.floor() can be used to return random integers.

There is no such thing as JavaScript integers.

We are talking about numbers with no decimals here.

Say you have this code:

const random1 = Math.floor(Math.random() * 10); const random2 = Math.floor(Math.random() * 11);

The variable random1 will return an integer value between 0-9 both included.

The variable random2 will return an integer value between 0-10 both included.

A Proper Random Function

As you can see from the examples above, it might be a good idea to create a proper random function to use for all random integer purposes.

This JavaScript function always returns a random number between min (included) and max (excluded):

function getRandomInteger(min, max) { return Math.floor((Math.random() * (max - min) ) + min); } getRandomInteger(2, 5);

So if we inputted 2 and 5 as arguments, the getRandomInteger() function will return us a value of 2, 3, or 4.

In another hand, this JavaScript function always returns a random number between min (included) and max (included):

function getRandomInteger(min, max) { return Math.floor((Math.random() * (max - min + 1) ) + min); } getRandomInteger(2, 5);

So if we inputted 2 and 5 as arguments, the getRandomInteger() function will return us a value of 2, 3, 4, or 5.

JavaScript Booleans

A JavaScript Boolean represents one of two values: true or false.

Boolean Values

Very often, in programming, you will need a data type that can only have one of two values, like

  • YES / NO
  • ON / OFF
  • TRUE / FALSE

For this, JavaScript has a Boolean data type. It can only take the values true or false.

The Boolean() Function

You can use the Boolean() function to find out if an expression (or a variable) is true:

const isTrue = Boolean(69 > 1);

The value for isTrue returns true.

Or we can code it like this:

const isTrue = 69 > 1;

The value for isTrue still returns true.

Comparisons and Conditions

We will learn more about JavaScript Comparisons and If Else in later topics.

For now, here is a table some comparison operators:

JavaScript Comparison Operators
Operator Description Example
== equal to if (day == "Monday")
> greater than if (salary > 9000)
< less than if (age < 18)

The Boolean value of an expression is the basis for all JavaScript comparisons and conditions.

Everything With a "Value" is True

The following values and expressions are true:

  • 100
  • 3.14
  • -15
  • "Hello"
  • "false"
  • 7 + 1 + 3.14

Everything Without a "Value" is False

The Boolean value of 0 (zero) is false:

const x = 0; Boolean(x); // returns false

The Boolean value of -0 (minus zero) is false:

const x = -0; Boolean(x); // returns false

The Boolean value of "" (empty string) is false:

const x = ""; Boolean(x); // returns false

The Boolean value of undefined is false:

let x; Boolean(x); // returns false

The Boolean value of null is false:

let x = null; Boolean(x); // returns false

The Boolean value of NaN is false:

let x = NaN; Boolean(x); // returns false

The Boolean value of false is (you guessed it) false:

let x = false; Boolean(x); // returns false

JavaScript Booleans as Objects

Normally JavaScript booleans are primitive values created from literals:

let x = false;

But booleans can also be defined as objects with the keyword new:

let y = new Boolean(false);

The variable x is a boolean while the variable y is an object.

Note:

Do not create Boolean objects.

The new keyword complicates the code and slows down execution speed.

Boolean objects can produce unexpected results.


For a complete reference, go to W3Schools Complete JavaScript Boolean Reference.

The reference contains descriptions and examples of all Boolean properties and methods.

JavaScript Comparison and Logical Operators

Comparison and Logical operators are used to test for true or false.

Comparison Operators

Comparison operators are used in logical statements to determine equality or difference between variables or values.

Given that x = 5, the table below explains the comparison operators:

Comparison Operators Table
Operator Description Comparing Returns
== equal to x == 8 false
x == 5 true
x == "5" true
=== equal value and equal type x === 5 true
x === "5" false
!= not equal x != 8 true
!== not equal value or not equal type x !== 5 false
x !== "5" true
x !== 8 true
> greater than x > 8 false
< less than x < 8 true
>= greater than or equal to x >= 8 false
<= less than or equal to x <= 8 true

How Can it be Used

Comparison operators can be used in conditional statements to compare values and take action depending on the result:

if (age ⊴ 18) alert("Too young to buy alcohol");

We will learn more about the use of conditional statements in the next topic.

Logical Operators

Logical operators are used to determine the logic between variables or values.

Given that x = 6 and y = 3, the table below explains the logical operators:

Logical Operators Table
Operator Description Example
&& and (x < 10 && y > 1) is true
|| or (x == 5 || y == 5) is false
! not !(x == y) is true

Conditional (Ternary) Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

The following is its general syntax:

variablename = (condition) ? value1 : value2;

Say you have this code:

const age = +prompt("How old are you?", 18); const isVoter = (age < 18) ? alert("You are underage.") : alert("You are a voter.");

If the variable age is a value below 18, the value of the variable isVoter will be an alert stating "You are underage.", otherwise the value of isVoter will be "You are a voter."

Comparing Different Types

Comparing data of different types may give unexpected results.

When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison.

An empty string converts to 0.

A non-numeric string converts to NaN which is always false.

Comparisons Example Table
Case Value
2 < 12 true
2 < "12" true
2 < "John" false
2 > "John" false
2 == "John" false
"2" < "12" false
"2" > "12" true
"2" == "12" false

When comparing two strings, "2" will be greater than "12", because (alphabetically) 1 is less than 2.

To secure a proper result, variables should be converted to the proper type before comparison:

const age = Number(prompt("How old are you?", 18)); if (isNaN(age)) { alert(`Your age is not a number.`); } else { alert(`Your age is ${age}`) }

In the code above, we first converted the value from the user input from prompt() to a number using Number().

Then in our if...else statement, we will check first if the value for age is in fact a number by using isNaN, and if it's true, an alert will pop up with a text "Your age is not a number."

Otherwise, an alert will pop up with a text `Your age is ${age}`, which uses template strings and ${} to include the value of age.

The Nullish Coalescing Operator (??)

The ?? operator returns the first argument if it is not nullish (null or undefined).

Otherwise it returns the second argument:

let x = null; // null value let y; // undefined value let text = "just a string"; let result1 = x ?? text; // returns text let result2 = y ?? text; // returns text

The nullish operator is supported in all browsers since March 2020:

The Optional Chaining Operator (?.)

The ?. operator returns undefined if an object is undefined or null (instead of throwing an error):

const car = {type:"Fiat", model:"500", color:"white"}; // create an object const x = car?.name; // returns undefined

The optional chaining operator is supported in all browsers since March 2020:

JavaScript if, else, and else if

Conditional statements are used to perform different actions based on different conditions.

Conditional Statements

Very often when you write code, you want to perform different actions for different decisions.

You can use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false
  • Use switch to specify many alternative blocks of code to be executed

We will learn more about switch in the next topic.

The if Statement

Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

The following is its syntax code:

if (condition) { // block of code to be executed if the condition is true }

Note:

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.

The following is a quick example of the usage of if:

const today = new Date(); const hour = today.getHours(); if (hour < 18) { alert("Good day!"); }

This code checks if the hour variable from today's date is less than 18.

If proven true, then a windows alert will pop up with a value of "Good day!"

The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

Below is the syntax for this statement:

if (condition) { // block of code to be executed if the condition is true } else { // block of code to be executed if the condition is false }

The following is the continuation code example from if:

const today = new Date(); const hour = today.getHours(); if (hour < 18) { alert("Good day!"); } else { alert("Good night!"); }

This makes the code alert "Good night!" whenever the hour variable is not less than 18.

The else if Statement

Use the else if statement to specify a new condition if the first condition is false.

Below is its syntax:

if (condition1) { // block of code to be executed if condition1 is true } else if (condition2) { // block of code to be executed if the condition1 is false and condition2 is true } else { // block of code to be executed if the condition1 is false and condition2 is false }

For example, if hour is less than 10, create a "Good morning" greeting, if not, but hour is less than 20, create a "Good day" greeting, otherwise a "Good evening":

const today = new Date(); const hour = today.getHours(); if (hour < 10) { alert("Good morning"); } else if (hour < 20) { alert("Good day"); } else { alert("Good evening"); }

JavaScript Switch Statement

The switch statement is used to perform different actions based on different conditions.

The JavaScript Switch Statement

Use the switch statement to select one of many code blocks to be executed.

Below is its syntax:

switch(expression) { case x: // code block break; case y: // code block break; default: // code block }

This is how it works:

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.
  • If there is no match, the default code block is executed.

The getDay() method returns the weekday as a number between 0 and 6.

This example uses the weekday number to calculate the weekday name:

const today = new Date(); const day = today.getDay(); switch(day) { case 0: alert("Today is Sunday!"); break; case 1: alert("Today is Monday!"); break; case 2: lert("Today is Tuesday!"); break; case 3: alert("Today is Wednesday!"); break; case 4: alert("Today is Thursday!"); break; case 5: alert("Today is Friday!"); break; case 6: alert("Today is Saturday!"); break; }

This code will check the value of day and compare it to each case value and if it matches, the code underneath will execute.

The default case is optional.

The break Keyword

When JavaScript reaches a break keyword, it breaks out of the switch block.

This will stop the execution inside the switch block.

It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.

Note:

If you omit the break statement, execution will continue to the next case regardless of whether its condition matches.

The default Keyword

The default keyword specifies the code to run if there is no case match.

The getDay() method returns the weekday as a number between 0 and 6.

If today is neither Saturday (6) nor Sunday (0), write a default message:

const today = new Date(); const day = today.getDay(); switch(day) { case 0: alert("Today is Sunday!"); break; case 6: alert("Today is Saturday!"); break; default: alert("Today is a weekday!") }

If today is Monday-Friday, the alert window will display a value of "Today is a weekday!".

The default case does not have to be the last case in a switch block:

const today = new Date(); const day = today.getDay(); switch(day) { default: alert("Today is a weekday!"); break; case 0: alert("Today is Sunday!"); break; case 6: alert("Today is Saturday!"); break; }

The code above works as well just make sure that if default is not the last case in the switch block, remember to end the default case with a break.

Common Code Blocks

Sometimes you will want different switch cases to use the same code.

In this example case 4 and 5 share the same code block, and 0 and 6 share another code block:

const today = new Date(); const day = today.getDay(); switch(day) { case 4: case 5: alert("Soon to be weekend!"); break; case 0: case 6: alert("It's the weekend!"); break; default: alert("Looking forward to the weekend!"); }

Switching Details

If multiple cases matches a case value, the first case is selected.

If no matching cases are found, the program continues to the default label.

If no default label is found, the program continues to the statement(s) after the switch.

Strict Comparison

Switch cases use strict comparison (===).

The values must be of the same type to match.

A strict comparison can only be true if the operands are of the same type.

In this example there will be no match for x:

let x = "0"; // x value is a string switch (x) { case 0: // "0" === 0 is false text = "Off"; break; case 1: // "0" === 1 is false text = "On"; break; default: // no case match, will run default code block text = "No value found"; }

The value of text is "No value found".

JavaScript For Loop

Loops can execute a block of code a number of times.

JavaScript Loops

Loops are handy, if you want to run the same code over and over again, each time with a different value.

Often this is the case when working with arrays:

const cars = ["Toyota", "BMW", "Audi", "Ford"]; for (let i = 0; i < cars.length ; i++) { alert(cars[i]); }

On page load, the site will alert the user with values "Toyota", "BMW", "Audi" and "Ford" in that order because of the loop function.

Different Kinds of Loops

JavaScript supports different kinds of loops:

  • for - loops through a block of code a number of times
  • for/in - loops through the properties of an object
  • for/of - loops through the values of an iterable object
  • while - loops through a block of code while a specified condition is true
  • do/while - also loops through a block of code while a specified condition is true

The For Loop

The for statement creates a loop with 3 optional expressions:

for (expression 1; expression 2; expression 3) { // code block to be executed }

Expression 1 is executed (one time) before the execution of the code block.

Expression 2 defines the condition for executing the code block.

Expression 3 is executed (every time) after the code block has been executed:

for(let i = 0; i < 5 ; i++) { alert(`The value of i is ${i}`); }

From the example above, you can read:

Expression 1 sets a variable before the loop starts (let i = 0).

Expression 2 defines the condition for the loop to run (i must be less than 5).

Expression 3 increases a value (i++) each time the code block in the loop has been executed.

Finally, alert runs with the values for i which are 0, 1, 2, 3, and 4.

How to use Expression 1

Expression 1 is used to initialize the variable(s) used in the loop (let i = 0).

But, expression 1 is optional.

You can omit expression 1 when your values are set before the loop starts:

const cars = ["Toyota", "Ford", "BMW", "Audi"]; let i = 0; for (; i < cars.length; i++) { alert(`Your car is ${cars[i]}.`); }

In the code above, we have an array cars and declared the variable i and assigned a value of 1 before starting any loop functions.

Right after, we coded the for loop function.

Notice that we did not include an expression 1 since the variable we will be using, i, is already initialized.

Note:

Do not forget to add the ; (semicolon) separator for each expressions in the for loop function even if there are no values for it.

You can intiate many values in Expression 1 (separated by comma):

const cars = ["Toyota", "Ford", "BMW", "Audi"]; let i, carsLength; for (i = 0, carsLength = cars.length ; i < carsLength; i++) { alert(`Your car is ${cars[i]}.`); }

The result will be the same with the first code we have.

How to use Expression 2

Expression 2 is used to evaluate the condition of the initial variable such as (i < cars.length).

But, expression 2 is also optional.

If expression 2 returns true, the loop will start over again. If it returns false, the loop will end.

Note:

If you omit expression 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser.

We will learn more about the break keyword in later topics.

How to use Expression 3

Expression 3 increments the value of the initial variable (i++).

But, expression 3 is also optional.

Expression 3 can do anything like negative increment (i--), positive increment (i = i + 15), or anything else.

Expression 3 can also be omitted (like when you increment your values inside the loop):

const cars = ["Toyota", "Ford", "BMW", "Audi"]; let i, carsLength; for (i = 0, carsLength = cars.length ; i < carsLength;) { alert(`Your car is ${cars[i]}.`); i++; }

In this case, we just added i++ inside the block code of the for loop function.

This code does the same as if we have included i++ as our expression 3.

Loop Scope

Using var in a loop:

var i = 5; for (var i = 0; i < 10; i++) { // some code } // Here i is 10

Using let in a loop:

let i = 5; for (let i = 0; i < 10; i++) { // some code } // Here i is 5

In the first example, using var, the variable declared in the loop redeclares the variable outside the loop.

In the second example, using let, the variable declared in the loop does not redeclare the variable outside the loop.

When let is used to declare the i variable in a loop, the i variable will only be visible within the loop.

Note:

The for...in, for...of, while, and do...while loops will be explained in the following topics.

JavaScript For In

The JavaScript for in statement loops through the properties of an Object:

Below is the syntax for this loop:

for (key in object) { // code block to be executed }

Say you have this code:

const person = {fname:"John", lname:"Cena", age:69}; for (let x in person) { alert(person[x]); }

The for in loop iterates over a person object

Each iteration returns a key (x)

The key is used to access the value of the key

The value of the key is person[x]

So in this example, windows alert will return a value of "John", "Cena", and 69 in that order on page load.

For In Over Arrays

The JavaScript for in statement can also loop over the properties of an Array:

Below is the syntax for this loop when used on arrays:

for (variable in array) { // code block }

Below is an example code:

const numbers = [45, 4, 9, 16, 25]; for (let x in numbers) { alert(numbers[x]); }

This will generate window alerts which returns values of 45, 4, 9, 16, and 25 in that order.

Note:

Do not use for in over an Array if the index order is important.

The index order is implementation-dependent, and array values may not be accessed in the order you expect.

It is better to use a for loop, a for of loop, or Array.forEach() when the order is important.

Array.forEach()

The forEach() method calls a function (a callback function) once for each array element:

const numbers = [45, 4, 9, 16, 25]; numbers.forEach((value, index, array) => alert(value)); numbers.forEach((value, index, array) => alert(index)); numbers.forEach((value, index, array) => alert(array));

The callback function we used is a simple arrow function.

The callbacks for the Array.forEach() function accepts three parameters namely value, index, and array in that order.

The parameter value refers to each value in the array, index refers to their index number starting with 0, and lastly array refers to the whole array itself.

So in our example, the first Array.forEach() function returns us a windows alert returning each value inside the array numbers (45, 4, 9, 16, 25).

The second returns only the indexes (0, 1, 2, 3, 4) in the window alert.

Then the last returns the whole array [45, 4, 9, 16, 25] five times in the window alert.

JavaScript For Of

The JavaScript for of statement loops through the values of an iterable object.

It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more

Below is the loop's syntax:

for (variable of iterable) { // code block to be executed }

Where variable is assigned the value of every iteration.

They can be declared using const, let, or var

While the iterable is an object that has iterable properties.

Looping over an Array

Say we have this code:

const cars = ["BMW", "Volvo", "Mini"]; for (let x of cars) { alert(x); }

In this code, we tried to loop through all the values (x) of the array cars.

On page load, the alert window will return us the values "BMW", "Volvo", and "Mini" in that order.

Looping over a String

Say we have this code:

let language = "JavaScript"; for (let letter of language) { alert(letter); }

With this code, the for of loop will loop over each letter (letter) of the string language.

This will then result into an alert window returning values of each letter of the word "JavaScript" in that order.

JavaScript While Loop

Loops can execute a block of code as long as a specified condition is true.

The while loop loops through a block of code as long as a specified condition is true.

Below is the syntax of this loop:

while (condition) { // code block to be executed }

Below is an example code using this loop:

let i = 1; while (i < 5) { alert(i); i++; }

In the example above, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:

The alert window will give us the values 1, 2, 3, and 4 in that order.

Note:

If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser.

The Do While Loop

The do while loop is a variant of the while loop.

This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Below is its syntax:

do { // code block to be executed } while (condition);

Below is an example code using this loop:

let i = 1; do { alert(i); i++; } while (i < 5);

The result from each alert window is the same as the while loop example.

The only difference is that the loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested.

Note:

Do not forget to increase the variable used in the condition, otherwise the loop will never end!

Comparing For and While

If you have read the previous chapter, about the for loop, you will discover that a while loop is much the same as a for loop, with statement 1 and statement 3 omitted.

The loop in this example uses a for loop to display the car names from the cars array:

const cars = ["BMW", "Volvo", "Saab", "Ford"]; let i = 0; for (;cars[i];) { alert(cars[i]); i++; }

For as long as cars[i] is true, the for loop continues to display the array values in the alert window.

The loop in this next example uses a while loop to display the car names from the cars array:

const cars = ["BMW", "Volvo", "Saab", "Ford"]; let i = 0; while(cars[i]) { alert(cars[i]); i++; }

The results from the alert window is the same as the first one using for loop.

JavaScript Break and Continue

The break statement "jumps out" of a loop.

The continue statement "jumps over" one iteration in the loop.

The Break Statement

You have already seen the break statement used in an earlier chapter of this tutorial.

It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop:

for (let i = 0; i < 10; i++) { if(i === 3) {break;} alert(i); }

In the example above, the break statement ends the loop ("breaks" the loop) when the loop counter (i) is 3.

Even though there is a condition to continue looping until (i < 10), the break prematurely ends or breaks out the loop function.

Therefore the only values displayed by the alert window are 0, 1, and 2.

The Continue Statement

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.

The example code below skips the value of 3:

for (let i = 0; i < 10; i++) { if(i === 3) {continue;} alert(i); }

The only values displayed by the alert window will be 0, 1, 2, 4, 5, 6, 7, 8, and 9.

JavaScript Labels

To label JavaScript statements you precede the statements with a label name and a colon:

Below is its syntax code:

label: statements

The break and the continue statements are the only JavaScript statements that can "jump out of" a code block.

Therefore we can jump out to a specific statement by using its label name:

break labelname; continue labelname;

The continue statement (with or without a label reference) can only be used to skip one loop iteration.

The break statement, without a label reference, can only be used to jump out of a loop or a switch.

With a label reference, the break statement can be used to jump out of any code block:

const cars = ["BMW", "Volvo", "Saab", "Ford"]; list: { alert(cars[0]); alert(cars[1]); break list; alert(cars[2]); alert(cars[3]); }

In the example above, we first labelled a code block {...} with a label name of list.

Inside the list code block, we coded the window alert to display each value inside the cars array by referencing their respective indices.

However, when it comes to the break statement, it jumps out or breaks out of the list code block even though this code block is not a loop code block.

Thus the values displayed by the alert window are only "BMW", and "Volvo".

Note:

A code block is a block of code inside curly brackets { }

JavaScript Iterables

Iterables are iterable objects (like Arrays).

Iterables can be accessed with simple and efficient code.

Iterables can be iterated over with for of loops

The For Of Loop

The JavaScript for of statement loops through the elements of an iterable object:

for (variable of iterable) { // code block to be executed }

Iterating

Iterating is easy to understand.

It simply means looping over a sequence of elements.

Here are some easy examples:

  • Iterating over a String
  • Iterating over an Array

Iterating Over a String

You can use a for of loop to iterate over the elements of a string:

const word = "Soda"; for (let x of word) { alert(x); }

In this example, we looped over each letter of the string word and then displayed them each using window alert.

The resulting values will be "S", "o", "d", and "a" in that order.

Iterating Over an Array

You can use a for of loop to iterate over the elements of an Array:

const fruits = ["Banana", "Apple", "Orange"]; for (let x of fruits) { alert(x); }

In this example, we looped over the fruits and displayed each value using window alert.

The resulting value will display "Banana", "Apple", and "Orange" in that order.

Iterating Over a Set

You can use a for of loop to iterate over the elements of a Set:

const letters = new Set(["a","b","c"]); for(x of letters) { alert(x); }

Just like with strings and arrays, a set is also an iterable object which we can use the for of loop.

In this case, the result will be displayed by the alert window with values "a", "b", and "b" in that order.

Iterating Over a Map

You can use a for of loop to iterate over the elements of a Map:

const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); for (let x of fruits) { alert(x); }

Thus the results from the window alert will display "apples,500", "bananas,300", and "oranges,200" in that order.

Note:

We will learn more about sets and maps in the next topics.

JavaScript Iterators

The iterator protocol defines how to produce a sequence of values from an object.

An object becomes an iterator when it implements a next() method.

The next() method must return an object with two properties:

  • value (the next value)
  • done (true or false)

Where value is the value returned by the iterator (can be ommitted when done is true)

And done have two values: true if the iterator is completed and false if the iterator has produced a new value.

Note:

Technically, iterables must implement the Symbol.iterator method.

String, Array, TypedArray, Map and Set are all iterables, because their prototype objects have a Symbol.iterator method.

Home Made Iterable

We can make home made iterables with simple functions.

However, the problem with home made iterable is that it does not support the JavaScript for of statement.

A JavaScript iterable is an object that has a Symbol.iterator.

The Symbol.iterator is a function that returns a next() function.

An iterable can be iterated over with the code:

for (const x of iterable) { }

JavaScript Sets

A JavaScript Set is a collection of unique values.

Each value can only occur once in a Set.

The values can be of any type, primitive values or objects.

How to Create a Set

You can create a JavaScript Set by:

  • Passing an array to new Set()
  • Create an empty set and use add() to add values

The new Set() Method

Pass an array to the new Set() constructor:

The example below is an example of creating a set:

const letters = new Set(["a", "b", "c"]);

We can also create an empty set and just use add() method to add values:

const letters = new Set(); letters.add("a"); letters.add("b"); letters.add("c");

This code will contain the same set values as the set in the first example.

We can also add variables as a parameter inside the add() method:

const letters = new Set(); const a ="a"; const b ="b"; const c ="c"; letters.add(a); letters.add(b); letters.add(c);

This will also return the same values as the the first example set.

The add() Method

As we can see, this method adds new values to our sets.

However, if you add equal elements, only the first will be saved:

const letters = new Set(); letters.add("a"); letters.add("b"); letters.add("c"); letters.add("c"); letters.add("c");

Even though we added two extra "c" strings, the first "c" will only be recognized by the letters set.

Set values must be unique so duplicates will not be rendered.

Therefore, the values for letters are still ["a", "b", "c"].

Listing the Elements

You can list all Set elements (values) with a for of loop:

const letters = new Set(["a", "b", "c"]); for (let x of letters) { alert(x); }

With this code, we simply displayed each value of the letters set in a window alert.

The values will return "a", "b", and "c" in that order.

Sets are Objects

If we ever checked the type of a set:

const letters = new Set(["a", "b", "c"]); console.log("Result:", typeof letters) console.log("Result:", letters instanceof Set);

The first console log will return a value of "Result: object"

While the second console log will return a value of "Result: true"


For a complete reference, go to W3Schools Complete JavaScript Set Reference

The reference contains descriptions and examples of all Set Properties and Methods.

JavaScript Set Methods

The following is a list of the basic set methods:

  • new Set()
  • add()
  • clear()
  • delete()
  • entries()
  • forEach()
  • has()
  • keys()
  • values()

The new Set() Method

We simply pass an array to the new Set() constructor to make a set:

const mySet = new Set([1, 2, 3]);

The set mySet has three values.

The add() Method

We can add additional values in a set using the add() method:

const numbers = new Set([1, 2, 3]); numbers.add(4); numbers.add(5); console.log("Result:", numbers.size);

The set numbers originally have 3 values but when we check it in our console log, it now returns Result: 5.

However, we we add equal elements, only the first will be saved:

const numbers = new Set([1, 2, 3]); numbers.add(4); numbers.add(5); numbers.add(5); numbers.add(5); numbers.add(5); console.log("Result:", numbers.size);

The console log will still return us Result: 5

Duplicates will be ignored in a set.

Note:

The primary feature of Set objects is that they only store unique values.

If an attempt is made to add an element that already exists in the set, the add() method will have no effect, and the set will remain unchanged.

The size Property

This property simply returns us the number of values inside a set:

const numbers = new Set([1, 2, 3]); const x = numbers.size;

The variable x will return a value of 3.

Listing Set Elements

You can list all Set elements (values) with a for of loop:

const numbers = new Set([1, 2, 3]); for (let x of numbers) { alert(x); }

We can display each value of the numbers set by using for of loop.

The window alert will return us the values 1, 2, and 3 in that order.

The has() Method

The has() method returns true if a specified value exists in a set:

const numbers = new Set([1, 2, 3]); const has4 = numbers.has(4);

The has4 variable will return us a value of false since numbers don't have the number 4 in its set.

The forEach() Method

The forEach() method invokes a function for each Set element:

const numbers = new Set([1, 2, 3]); numbers.forEach(number => alert(number + 5));

In this example, we passed a simple arrow function for each number in the numbers set.

The function will return us an alert with value of number + 5 when displayed.

Thus the values displayed will be 6, 7, and 8 in that order.

The values() Method

The values() method returns an Iterator object with the values in a Set:

const numbers = new Set([1, 2, 3]); const myIterator = numbers.values(); for (let i of myIterator) { alert(i); }

We can get all the values in the set numbers by using values() and also converting it into an iterator.

Finally we used the for of loop to display these values just like before.

The keys() Method

The keys() method returns an Iterator object with the values in a Set.

Note:

A Set has no keys, so keys() returns the same as values().

This makes Sets compatible with Maps.

The entries() Method

The entries() method returns an Iterator with [value,value] pairs from a Set.

Note:

The entries() method is supposed to return a [key,value] pair from an object.

A Set has no keys, so the entries() method returns [value,value].

This makes Sets compatible with Maps.

Say we have this code:

const numbers = new Set([1, 2, 3]); const myIterator = numbers.entries(); for (let i of myIterator) { alert(i); }

The for of loop will return us window alerts with values 1,1, 2,2, and 3,3 in that order.


For a complete reference, go to W3Schools Complete JavaScript Set Reference.

The reference contains descriptions and examples of all Set Properties and Methods.

JavaScript Set Logic

In JavaScript 2025, 7 new logigal methods were added to the Set object:

  • union()
  • difference()
  • intersection()
  • isDisjointFrom()
  • isSubsetOf()
  • isSupersetOf()
  • symmetricDifference()

The new Set methods are supported all modern browsers since June 2024:

The union() Method

The union() method returns the union of two sets.

The union() method returns a new set containing the elements which are in this set, or in the argument set, or in both:

A set union graph illustration. const A = new Set(["a", "b", "c"]); const B = new Set(["d", "e", "f"]); const C = A.union(B);

The value of the variable C will be a set that contains the value ["a", "b", "c", "d", "e", "f"]

Note that this is a new set from the union of sets A and B.

The intersection() Method

The intersection() method returns the intersection of two sets.

The intersection() method returns a new set containing the elements which are in this set and in the argument set:

Intersection graph illustration. const A = new Set(["a", "b", "c"]); const B = new Set(["b", "c", "d"]); const C = A.intersection(B);

The variable C will return a set with value of ["b", "c"].

The difference() Method

The difference() method returns the difference between two sets.

The difference() method returns a new set containing elements which are in this set but not in the argument set:

Difference graph illustration. const A = new Set(["a", "b", "c"]); const B = new Set(["b", "c", "d"]); const C = A.difference(B);

The variable C will return a set value of ["a"].

The symmetricDifference() Method

The symmetricDifference() method returns the symmetric difference between to sets.

The symmetricDifference() method returns a new set containing elements which are in this set or in the argument set, but not in both:

Symmetric difference graphic illustration. const A = new Set(["a", "b", "c"]); const B = new Set(["b", "c", "d"]); const C = A.symmetricDifference(B);

The variable C returns a set value of ["a", "d"].

The isSubsetOf() Method

The isSubsetOf() method returns true if all elements in this set is also elements in the argument set:

Subset graphic illustration. const A = new Set(["a", "b", "c"]); const B = new Set(["b", "c", "d"]); const result = A.isSubsetOf(B); // returns false

The isSupersetOf() Method

The isSupersetOf() method returns true if all elements in the argument set are also in this set:

Superset graphic illustration. const A = new Set(["a", "b", "c"]); const B = new Set(["b", "c", "d"]); const result = A.isSupersetOf(B); // returns false

The isDisjointFrom() Method

The isDisjointFrom() method returns true if this set has no elements in common with the argument set:

Disjoint graphic illustration. const A = new Set(["a", "b", "c"]); const B = new Set(["b", "c", "d"]); const result = A.isDisjointFrom(B); // returns false

For a complete reference, go to W3Schools Complete JavaScript Set Reference.

The reference contains descriptions and examples of all Set Properties and Methods.

JavaScript Maps

A Map holds key-value pairs where the keys can be any datatype.

A Map remembers the original insertion order of the keys.

How to Create a Map

You can create a JavaScript Map by:

  • Passing an Array to new Map()
  • Create a Map and use Map.set()

The new Map() Method

You can create a Map by passing an Array to the new Map() constructor:

const fruits = new Map ([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]);

This code simply creates a map.

The set() Method

You can add elements to a Map with the set() method:

// Create a map const fruits = new Map(); // Set values fruits.set("apples", 500); fruits.set("bananas", 300); fruits.set("oranges", 200);

The fruits variable will be map with the same values as the first example code.

The set() method can also be used to change existing Map values:

// Create a map const fruits = new Map(); // Set initial values fruits.set("apples", 500); fruits.set("bananas", 300); fruits.set("oranges", 200); // Change a value fruits.set("apples", 200); // Check the value for apples fruits.get("apples");

The new value for the key "apples" now returns 200.

The get() Method

The get() method gets the value of a key in a Map:

// Create a map const fruits = new Map(); // Set initial values fruits.set("apples", 500); fruits.set("bananas", 300); fruits.set("oranges", 200); // Get value for apples fruits.get("apples");

Using the get() method, the last line of code will return us a value of 500.

Maps are Objects

Maps are objects.

We can test it using typeoff keyword.

Also we can use the instanceof keyword to check if a variable is really a map:

const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); const whatType = typeof fruits; // returns object const isMap = fruits instanceof Map; // returns true

JavaScript Objects vs Maps

The following table shows the difference between maps and objects:

Maps Vs Objects Difference Table
Object Map
Not directly iterable Directly iterable
Do not have a size property Have a size property
Keys must be Strings (or Symbols) Keys can be any datatype
Keys are not well ordered Keys are ordered by insertion
Have default keys Do not have default keys

For a complete reference, go to W3Schools Complete JavaScript Map Reference.

The reference contains descriptions and examples of all Map Properties and Methods.

JavaScript Map Methods

The following are map methods:

The new Map() Method

You can create a map by passing an array to the new Map() constructor:

// Create a Map const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]);

Map.get()

You get the value of a key in a map with the get() method:

// Create a Map const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); fruits.get("apples"); // returns 500

Map.get()

You can add elements to a map with the set() method:

// Create empty map const fruits = new Map(); // Set map values fruits.set("apples", 500); fruits.set("bananas", 300); fruits.set("oranges", 200);

The set() method can also be used to change existing map values:

const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); // Change a map value fruits.set("apples", 200); // Check new value fruits.get("apples"); // returns 200

Map.size

The size property returns the number of elements in a map:

const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); // Get map size fruits.size; // returns 3

Map.delete()

The delete() method removes a map element:

const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); // Delete a map element fruits.delete("apples"); // Check new size fruits.size; // returns 2

Map.clear()

The clear() method removes all the elements from a map:

const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); // Clear all elements fruits.clear(); // Check new size fruits.size; // returns 0

Map.has()

The has() method returns true if a key exists in a map:

const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); // Check if map has "apples" fruits.has("apples"); // returns true

Map.forEach()

The forEach() method invokes a callback for each key/value pair in a map:

const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); // Display each entry fruits.forEach( (value, key) => { alert(`Key: ${key}, Value: ${value}`); });

Map.entries()

The entries() method returns an iterator object with the [key,values] in a map:

const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); // Loop each entries for (let ent of fruits) { alert(ent); }

This code will display all entries of the fruits variable in an alert window.

The values displayed are "apples,500", "bananas,300", and "oranges,200" in that order.

Map.keys()

The keys() method returns an iterator object with the keys in a map:

const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); // Loop each keys for (let keys of fruits.keys()) { alert(keys); }

The window alert will display the values "apples", "bananas" and "oranges" in that order.

Map.values()

The values() method returns an iterator object with the values in a map:

const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); // Loop each values for (let values of fruits.values()) { alert(values); }

The window alert will display the values 500, 300 and 200 in that order.

Objects as Keys

Being able to use objects as keys is an important Map feature:

// Create objects const apples = {name: "Apples"}; const bananas = {name: "Bananas"}; const oranges = {name: "Oranges"}; // Create a map const fruits = new Map(); // Add elements to map fruits.set(apples, 500); fruits.set(bananas, 300); fruits.set(oranges, 200);

With this the keys for the fruits map is an object.

We can get the value of one element by calling the object:

fruits.get(apples) // returns 500

We will get undefined if we try to call the key as a string:

fruits.get("apples") // returns undefined

JavaScript Map.groupBy()

ES2024 added the Map.groupBy() method to JavaScript.

The Map.groupBy() method groups elements of an object according to string values returned from a callback function.

The Map.groupBy() method does not change the original object.


For a complete reference, go to W3Schools Complete JavaScript Map Reference

The reference contains descriptions and examples of all Map Properties and Methods.

JavaScript Typed Arrays

Typed arrays are array-like objects designed for handling of raw binary data.

Unlike standard arrays, typed arrays are array buffers of fixed length.

Typed arrays store elements of fixed types like 8-bit integers or 32-bit numbers.

Typed Array Benefits

Typed arrays provide a way to handle binary data as efficiently as arrays in C.

Typed arrays are raw memory, so JavaScript can pass them directly to any function without converting the data to another representation.

Typed arrays are seriously faster than normal arrays for passing data to functions that can use raw binary data. Typed Arrays are highly suitable for:

  • WebGL and Canvas: Fast graphics rendering and image processing.
  • File APIs: Fast reading and writing of local files.
  • Media APIs: Fast handling of audio and video data.
  • WebSockets: Efficient binary data transfer over network.

Differences from Regular Arrays

Fixed Length: Typed Arrays cannot be dynamically resized using methods like push() or pop().

Type Restriction: Elements must adhere to the specified data type of the typed array.

Underlying Buffer: Typed Arrays are views into an ArrayBuffer, allowing direct manipulation of binary data.

JavaScript Typed Array Methods

The following are examples of the typed array methods:

The from() Method

The from() method creates a new typed array from any iterable object:

Create a typed array from a string:

const myArr = Int16Array.from("1234567890");

Create a typed array from an array:

const myArr = Int16Array.from([1,2,3,4,5,6,7,8,9,0]);

The of() Method

The of() mathod creates a new typed array from a number of arguments:

const myArr = Int16Array.of(1,2,3,4,5,6,7,8,9,0);

The constructor.name Property

The constructor.name property returns the name (type) of a typed array:

// Create a Typed Array const myArr = new Int32Array(10); console.log(myArr.constructor.name);

This console log returns a value of "Int32Array".

The BYTES_PER_ELEMENT Property

BYTES_PER_ELEMENT returns the number of bytes used to store each array element:

// Create a Typed Array const myArr = new Int32Array(10); console.log(myArr.BYTES_PER_ELEMENT);

The console log returns a value of 4.

Common Array Methods

Typed Arrays share many methods with Standard Arrays:

  • Iteration: forEach(), map(), filter(), reduce(), reduceRight(), every(), some(), find(), findIndex(), findLast(), findLastIndex()
  • Searching: includes(), indexOf(), lastIndexOf().
  • Manipulation: at(), copyWithin(), fill(), reverse(), set(), slice(), sort(), subarray().
  • Conversion: join(), toLocaleString(), toString().
  • Non-mutating methods: toReversed(), toSorted(), with().

The fill() Method

The fill() method changes all elements in a typed array to a value.

Fill all array elements with a value:

const myArr = new Int16Array(10); myArr.fill(200); console.log("Result:", myArr);

The console log returns a value of Int16Array(10) [200, 200, 200, 200, 200, 200, 200, 200, 200, 200]

The fill() method takes two optional arguments: start index and end index:

Fill some array elements with a value:

const myArr = new Int16Array(10); myArr.fill(200, 0, 3); console.log("Result:", myArr);

The console log returns a value of Int16Array(10) [200, 200, 200, 0, 0, 0, 0, 0, 0, 0]

The find() Method

The find() method returns the first element that satisfies a test:

const myArr = Int16Array.from([10,15,20,25,30,35,40,45,50]); let x = myArr.find((x) => x > 18) // x returns a value of 20

The some() Method

The some() method returns true if an element for which a provided function returns true:

const myArr = Int16Array.from([10,15,20,25,30,35,40,45,50]); let x = myArr.some((x) => x > 18) // x returns true

Note:

Some array methods are NOT available for typed array.

This is due to the fixed-length nature and the lack of fixed structure.


For a complete reference to all Typed Arrays and Methods, go to W3Schools Complete Typed Array Reference.

JavaScript Iterators

An Iterator is an object that provides a standard way to access elements sequentially.

An Iterator must adheres to the Iterator Protocol: It must have a next() method.

The next() Method

The next() method returns an object with two properties:

  • The value property holds the next value in the iteration sequence.
  • The done property returns false if there are more elements to iterate over, otherwise it returns true.

The For Of Loop

The JavaScript for of statement loops through the elements of an iterable object.

Below is its code syntax:

for (variable of iterable) { // code block to be executed }

Note:

Technically, iterables must implement the Symbol.iterator method.

In JavaScript the following are iterables:

  • Strings
  • Arrays
  • Typed Arrays
  • Sets
  • Maps

Because their prototype objects have a Symbol.iterator method:

Iterators provide a controlled way to work with data sequences, enabling custom iteration logic for various data structures.

They are particularly useful for handling streams of data, lazy computation of values, and building custom data structures with defined iteration behaviors.

Helper Functions

JavaScript 2025 (ECMAScript 2025) officially approved a set of new Iterator Helper methods that significantly enhance the functionality of iterators in JavaScript.

The methods provide a more functional and efficient way to work with iterable objects, including generators, by allowing direct manipulation and transformation without first converting them to arrays:

Iterator Methods Table
Function Description
drop() Returns an iterator that skips a specified number of elements before yielding the rest
every() Returns true if all elements satisfy a test function
filter() Returns an iterator containing elements that satisfy a filter function
find() Returns the first element that satisfies a test function
flatMap() Returns an iterator by mapping each element and then flattening the results
forEach() Executes a function once for each element in the iterator.
from() creates an iterator object from an iterable
map() Returns an iterator with all elements transformed by a map function
reduce() Applies a reducer function against each element to reduce it to a single value
some() Returns true if at least one element satisfy a test function
take() Returns an iterator that yields a specified number of elements

The Iterator.from() Method

The Iterator.from() creates an iterator object from an existing iterable or iterator object:

// Create an iterator from an array const myIterator = Iterator.from([1, 2, 3]);

The filter() Method

The filter() method returns a new iterator containing elements that satisfy a filter function.

// Create an iterator from an array const myIterator = Iterator.from([32, 33, 16, 40]); // Filter the iterator const filteredIterator = myIterator.filter(x => x > 18); // Display the values of the new iterator for (let x of filteredIterator) { alert(x); }

This code will return an alert window with values 32, 33, and 40 in that order.

The map() Method

The map() method returns a new iterator with all elements transformed by a map function:

// Create an iterator const myIterator = Iterator.from("123456789"); // Now you can use the map method const mappedIterator = myIterator.map(x => x * 2);

The values of the variable mappedIterator is now [2, 4, 6, 8, 10, 12, 14, 16, 18]

The flatMap() Method

The flatMap() method returns a new iterator by mapping each element and then flattening the results into a single iterator.

// Create an iterator const myIterator = Iterator.from([1, 2, 3, 4, 5, 6]); // Map the Iterator const mappedIterator = myIterator.flatMap(x => [x, x * 10]);

The values inside the mappedIterator is [1, 10, 2, 20, 3, 30, 4, 40, 5, 50, 6, 60]

The take() Method

The take() method returns a new iterator that yields at most a specified number of elements:

const myIterator = Iterator.from([1, 2, 3, 4, 5, 6]); // Take the first five elements const firstFive = myIterator.take(5);

The iterator firstFive has only the values [1, 2, 3, 4, 5]

The drop() Method

The drop() method returns a new iterator that skips a specified number of elements before yielding the rest:

const myIterator = Iterator.from([1, 2, 3, 4, 5, 6]); // Remove the first five const firstFive = myIterator.drop(5);

The firstFive iterator now only has a value of [6]

The find() Method

The find(fn) method returns the first element that satisfies a test function:

const myIterator = Iterator.from([3, 10, 18, 30, 20]); // Find first greater than 18 let result = myIterator.find(x => x > 18); // returns 30

The reduce() Method

The reduce() method applies a reducer function against an accumulator and each element to reduce it to a single value:

function myFunc(total, num) { return total + num; } const myIterator = Iterator.from([175, 50, 25]); // Reduce the Iterator let result = myIterator.reduce(myFunc); // returns 250

The every() Method

The every(fn) method returns true if all elements in the iterator satisfy the provided test function:

const myIterator = Iterator.from("123456789"); // Is every Element greater than 7? let result = myIterator.every(x => x > 7); // returns false

The some() Method

The some() method returns true if at least one element in the iterator satisfies the provided test function:

const myIterator = Iterator.from("123456789"); // Is some Element greater than 7? let result = myIterator.some(x => x > 7); // returns true

The forEach() Method

The forEach() method executes a provided function once for each element in the iterator.

const myIterator = Iterator.from("123456789"); myIterator.forEach(x => console.log(x));

The console log will return us individual values of 1, 2, 3, 4, 5, 6, 7, 8, 9 in that order.

The typeof Operator

The typeof operator returns the data type of a JavaScript variable.

Primitive Data Types

In JavaScript, a primitive value is a single value with no properties or methods.

JavaScript has 7 primitive data types:

  • string
  • number
  • boolean
  • bigint
  • symbol
  • null
  • undefined

The typeof operator returns the type of a variable or an expression.

typeof "John" // Returns string typeof ("John"+"Doe") // Returns string typeof 3.14 // Returns number typeof 33 // Returns number typeof (33 + 66) // Returns number typeof true // Returns boolean typeof false // Returns boolean typeof 1234n // Returns bigint typeof Symbol() // Returns symbol typeof x // Returns undefined typeof null // Returns object

Note:

In JavaScript, null is a primitive value. However, typeof returns "object".

This is a well-known bug in JavaScript and has historical reasons.

Complex Data Types

A complex data type can store multiple values and/or different data types together.

JavaScript has one complex data type: object

All other complex types like arrays, functions, sets, and maps are just different types of objects.

The typeof operator returns only two types:

  • object
  • function

Here are some example codes:

typeof {name:'John'} // Returns object typeof [1,2,3,4] // Returns object typeof new Map() // Returns object typeof new Set() // Returns object typeof function (){} // Returns function

Note:

The typeof operator returns object for all types of objects:

  • objects
  • arrays
  • sets
  • maps

You cannot use typeof to determine if a JavaScript object is an array or a date.

How to Recognize an Array

How to know if a variable is an array?

ECMAScript 5 (2009) defined a new method for this: Array.isArray():

// Create an array const fruits = ["apples", "bananas", "oranges"]; let result = Array.isArray(fruits); // returns true

The instanceof Operator

The instanceof operator returns true if an object is an instance of a specified object type:

// Create a date const time = new Date(); let result = time instanceof Date; // returns true // Create an array const fruits = ["apples", "bananas", "oranges"]; let result = fruits instanceof Array; // returns true // Create a map const fruits = new Map([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); let result = fruits instanceof Map; // returns true // Create a set const fruits = new Set(["apples", "bananas", "oranges"]); let result = fruits instanceof Set; // returns true

Undefined Variables

The typeof of an undefined variable is undefined:

typeof car // returns undefined

The typeof of a variable with no value is undefined. The value is also undefined:

let car; let result = typeof car; // still returns undefined

Any variable can be emptied, by setting the value to undefined:

let car = "Volvo"; car = undefined; let result = typeof car; // returns undefined

Empty Values

An empty value has nothing to do with undefined.

An empty string has both a legal value and a type:

let car = ""; let result = typeof car; // returns string

Null

In JavaScript null is "nothing". It is supposed to be something that doesn't exist.

Unfortunately, in JavaScript, the data type of null is an object.

You can empty an object by setting it to null:

// Create an object let person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue" }; person = null; // returns null typeof person // returns object

You can also empty an object by setting it to undefined.

The resulting value and type for the object will be both undefined.

Difference Between Undefined and Null

undefined and null are equal in value but different in type:

typeof undefined // undefined typeof null // object null === undefined // false null == undefined // true

The constructor Property

The constructor property returns the constructor function for all JavaScript variables:

// Returns function Object() {[native code]}: {name:'John',age:34}.constructor // Returns function Array() {[native code]}: [1,2,3,4].constructor // Returns function Date() {[native code]}: new Date().constructor // Returns function Set() {[native code]}: new Set().constructor // Returns function Map() {[native code]}: new Map().constructor // Returns function Function() {[native code]}: function () {}.constructor

With the constructor, you can check if an object is an Array:

const myArray = [1, 2, 3]; (myArray.constructor === Array); // returns true

With the constructor, you can check if an object is a Date:

const myDate = new Date(); myDate.constructor === Date; // returns true

Note:

The data type of NaN (Not a Number) is number !

The void Operator

The void operator evaluates an expression and returns undefined. This operator is often used to obtain the undefined primitive value, using "void(0)" (useful when evaluating an expression without using the return value).

JavaScript toString()

The JavaScript toString() method converts a variable (or a value) to a string.

It is a built-in method for many data types, including numbers, arrays, dates, and objects.

The method is useful for:

  • Converting data to a readable format for display
  • Ensuring type compatibility when a string is required
  • Customizing objects other user interfaces
  • Customizing objects for debugging

JavaScript Array toString()

When used on an array, toString() returns the array elements as a comma separated string:

const fruits = ["Banana", "Orange", "Apple", "Mango"]; let x = fruits.toString();

The variable x returns a value of "Banana,Orange,Apple,Mango"

JavaScript Date toString()

When used on a date, toString() returns a human-readable date and time string:

const date = new Date("2025-03-22"); let x = date.toString();

The variable x returns a value of "Sat Mar 22 2025 08:00:00 GMT+0800 (Philippine Standard Time)"

JavaScript Number toString()

When used on a number, toString() returns the number as a string:

let x = 123; x.toString(); // returns "123"

JavaScript Function toString()

When used on a function, toString() returns the source code of the function as a string.

JavaScript Object toString()

When used on a object, toString() returns "[object Object]".

JavaScript Type Conversion

JavaScript variables can be converted to a new variable and another data type:

  • By the use of a JavaScript function
  • Automatically by JavaScript itself

Converting Strings to Numbers

The global method Number() converts a variable (or a value) into a number.

A numeric string (like "3.14") converts to a number (like 3.14).

An empty string (like "") converts to 0.

A non numeric string (like "John") converts to NaN (Not a Number).

The Unary + Operator

The unary + operator can be used to convert a variable to a number:

let y = "5"; // y is a string let x = + y; // x is a number

If the variable cannot be converted, it will still become a number, but with the value NaN (Not a Number):

let y = "John"; // returns as a string let x = + y; // returns as a number of value NaN

Converting Numbers to Strings

The global method String() can convert numbers to strings.

It can be used on any type of numbers, literals, variables, or expressions:

String(x); // returns a string from a number variable x String(123); // returns a string from a number literal 123 String(100 + 23); // returns a string from a number from an expression

The Number method toString() does the same:

x.toString(); (123).toString(); (100 + 23).toString();

Converting Dates to Numbers

The global method Number() can be used to convert dates to numbers:

const date = new Date("March 22, 2025"); let x = Number(date); // returns 1742572800000

The date method getTime() does the same:

const date = new Date("March 22, 2025"); let x = date.getTime(); // returns 1742572800000

Converting Dates to Strings

The global method String() can convert dates to strings:

const date = new Date("March 22, 2025"); let x = String(date);

The variable x returns a value of "Sat Mar 22 2025 00:00:00 GMT+0800 (Philippine Standard Time)"

The Date method toString() does the same:

const date = new Date("March 22, 2025"); let x = date.toString(); // returns the same value

Converting Booleans to Numbers

The global method Number() can also convert booleans to numbers:

Number(false); // returns 0 Number(true) // returns 1

Converting Booleans to Strings

The global method String() can convert booleans to strings:

String(false) // returns "false" String(true) // returns "true"

The Boolean method toString() does the same:

false.toString() // returns "false" true.toString() // returns "true"

Automatic Type Conversion

When JavaScript tries to operate on a "wrong" data type, it will try to convert the value to a "right" type.

The result is not always what you expect:

5 + null; // returns 5 "5" + null // returns "5null" "5" + 2 // returns "52" "5" - 2 // returns 3 "5" * "2" // returns 10

Automatic String Conversion

JavaScript automatically calls the variable's toString() function when you try to "output" an object or a variable.

Numbers and booleans are also converted, but this is not very visible.

JavaScript Destructuring

The destructuring assignment syntax unpack object properties into variables:

let {firstName, lastName} = person;

It can also unpack arrays and any other iterables:

let [firstName, lastName] = person;

Object Destructuring

Say we have this code:

// Create an object const person = { firstName: "John", lastName: "Doe", age: 50 }; // Destructuring let {firstName, lastName} = person; // Display console.log(firstName); // returns "John" console.log(lastName); // returns "Doe"

What happens here is that destructuring finds the properties firstName and lastName from the object person.

Then it creates these two as variables with the same names and their corresponding values in the person object.

The order of the properties does not matter.

Note:

Destructuring is not destructive.

Destructuring does not change the original object.

Object Default Values

For potentially missing properties we can set default values:

// Create an object const person = { firstName: "John", lastName: "Doe", age: 50 }; // Destructuring let {firstName, lastName, country = "US"} = person; // Display console.log(country); // returns "US"

Object Property Alias

We can also set the variable name differently from its original property name:

// Create an object const person = { firstName: "John", lastName: "Doe", age: 50 }; // Destructuring let {lastname : name} = person; // Display console.log(name); // returns "Doe"

String Destructuring

One use for destructuring is unpacking string characters:

const yourName = "John"; // Destructuring let [a1, a2, a3, a4] = yourName; console.log(a1); // returns "J"

Note:

Destructuring can be used with any iterables.

Array Destructuring

We can pick up array variables into our own variables:

const fruits = ["Bananas", "Oranges", "Apples", "Mangos"]; let [fruit1, fruit2, fruit3, fruit4] = fruits; console.log(fruit3); // returns "Apples"

Skipping Array Values

We can skip array values using two or more commas:

const fruits = ["Bananas", "Oranges", "Apples", "Mangos"]; let [fruit1,,,fruit2] = fruits; console.log(fruit2); // returns "Mangos"

Array Position Values

We can pick up values from specific index locations of an array:

const fruits = ["Bananas", "Oranges", "Apples", "Mangos"]; let {[0]:fruit1 ,[1]:fruit2} = fruits; console.log(fruit2); // returns "Oranges"

The Rest Property

You can end a destructuring syntax with a rest property.

This syntax will store all remaining values into a new array:

const numbers = [10, 20, 30, 40, 50, 60, 70]; const [a, b, ...rest] = numbers; console.log(rest); // returns [30, 40, 50, 60, 70]

Destructuring Maps

const fruits = new Map ([ ["apples", 500], ["bananas", 300], ["oranges", 200] ]); for (const [key, value] of fruits) { console.log(`${key}, ${value}`); }

The console log will return us values "apples, 500", "bananas, 300", and "oranges, 200" in that order.

Swapping JavaScript Variables

You can swap the values of two variables using a destructuring assignment:

let firstName = "John"; let lastName = "Doe"; [firstName, lastName] = [lastName, firstName]; console.log(firstName); // returns "Doe";

JavaScript Regular Expressions

A regular expression is a sequence of characters that forms a search pattern.

The search pattern can be used for text search and text replace operations.

What Is a Regular Expression?

A regular expression is a sequence of characters that forms a search pattern.

When you search for data in a text, you can use this search pattern to describe what you are searching for.

A regular expression can be a single character, or a more complicated pattern.

Regular expressions can be used to perform all types of text search and text replace operations.

Below is its syntax:

/pattern/modifiers;

Here's an example:

/w3schools/i;

The example above /w3schools/i is a regular expression.

w3schools is a pattern (to be used in a search).

i is a modifier (modifies the search to be case-insensitive).

Using String Methods

In JavaScript, regular expressions are often used with the two string methods: search() and replace().

The search() method uses an expression to search for a match, and returns the position of the match.

The replace() method returns a modified string where the pattern is replaced.

Using String search() With a String

The search() method searches a string for a specified value and returns the position of the match:

Use a string to do a search for "W3schools" in a string:

let text = "Visit W3Schools!"; let n = text.search("W3Schools"); console.log(n); // returns 6

Using String search() With a Regular Expression

Use a regular expression to do a case-insensitive search for "w3schools" in a string:

let text = "Visit W3Schools!"; let n = text.search(/w3schools/i); console.log(n); // returns 6

Using String replace() With a String

The replace() method replaces a specified value with another value in a string:

let text = "Visit Microsoft!"; let result = text.replace("Microsoft", "W3Schools"); console.log(result); // returns "Visit W3Schools!"

Use String replace() With a Regular Expression

Use a case insensitive regular expression to replace Microsoft with W3Schools in a string:

let text = "Visit Microsoft!"; let result = text.replace(/microsoft/i, "W3Schools"); console.log(result); // returns "Visit W3Schools!"

Did you notice?

Regular expression arguments (instead of string arguments) can be used in the methods above.

Regular expressions can make your search much more powerful (case insensitive for example).

Regular Expression Modifiers

Modifiers can be used to perform case-insensitive or global searches:

RegExp Modifiers Table
Modifier Description
i Perform case-insensitive matching
g Perform a global match (find all)
m Perform multiline matching
d Perform start and end matching (New in ES2022)

Regular Expression Patterns

Brackets are used to find a range of characters:

RegExp Patterns Table
Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |

Metacharacters are characters with a special meaning:

RegExp Metacharacters Table
Metacharacter Description
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx

Quantifiers define quantities:

RegExp Quantifiers Table
Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n

Using the RegExp Object

In JavaScript, the RegExp object is a regular expression object with predefined properties and methods.

Using test()

The test() method is a RegExp expression method.

It searches a string for a pattern, and returns true or false, depending on the result.

The following example searches a string for the character "e":

const pattern = /e/; pattern.test("The best things in life are free!"); // returns true

You don't have to put the regular expression in a variable first. The two lines above can be shortened to one:

/e/.test("The best things in life are free!"); // returns true

Using exec()

The exec() method is a RegExp expression method.

It searches a string for a specified pattern, and returns the found text as an object.

If no match is found, it returns an empty (null) object.

The following example searches a string for the character "e":

let x = /e/.exec("The best things in life are free!"); // returns an object

The RegExp.escape() Method

The RegExp.escape() method returns string where characters that belongs to the regular expression syntax are escaped.

This makes it possible to treat characters like +, *, ?, ^, $, (, ), [, ], {, }, |, and \ literally, and not as part of a regular expression.

// Escape a text for to use as a regular expression const safe = RegExp.escape("[*]"; // Build a new reglar expression const regex = new RegExp(safe); // Text to replace within const oldText = "[*] is a web school."; // Perform the replace const newText = oldText.match(regex, "W3Schools");

For a complete reference, go to W3Schools Complete JavaScript RegExp Reference.

The reference contains descriptions and examples of all RegExp properties and methods.

JavaScript Errors

Throw, and Try...Catch...Finally

The try statement defines a code block to run (to try).

The catch statement defines a code block to handle any error.

The finally statement defines a code block to run regardless of the result.

The throw statement defines a custom error.

Errors Will Happen!

When executing JavaScript code, different errors can occur.

Errors can be coding errors made by the programmer, errors due to wrong input, and other unforeseeable things.

In this example we misspelled "alert" as "adddlert" to deliberately produce an error:

try { adddlert("Welcome guest!"); } catch(err) { alert(err); }

The alert will display "ReferenceError: adddlert is not defined"

JavaScript catches adddlert as an error, and executes the catch code to handle it.

JavaScript try and catch

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

The JavaScript statements try and catch come in pairs:

try { Block of code to try } catch(err) { Block of code to handle errors }

JavaScript Throws Errors

When an error occurs, JavaScript will normally stop and generate an error message.

The technical term for this is: JavaScript will throw an exception (throw an error).

JavaScript will actually create an Error object with two properties: name and message.

The throw Statement

The throw statement allows you to create a custom error.

Technically you can throw an exception (throw an error).

The exception can be a JavaScript String, a Number, a Boolean or an Object:

throw "Too big"; // throw a text throw 500; // throw a number

If you use throw together with try and catch, you can control program flow and generate custom error messages.

Input Validation Example

This example examines input. If the value is wrong, an exception (err) is thrown.

The exception (err) is caught by the catch statement and a custom error message is displayed:

let x = prompt("Enter a number between 5 and 10 (both included):", 5); try { if (x.trim() === "") throw "Please enter a number"; if (isNaN(x)) throw "Input is not a number"; Number(x); if (x < 5) throw "Input is too low"; if (x > 10) throw "Input is too high"; if (x <= 10 && x >= 5) throw `Your input value is ${x}`; } catch(err) { alert(err); }

In this example, depending on the user's input, a different alert message will be displayed.

HTML Validation

The code above is just an example.

Modern browsers will often use a combination of JavaScript and built-in HTML validation, using predefined validation rules defined in HTML attributes:

<input id="demo" type="number" min="5" max="10" step="1">

We will learn more about forms validation in a later chapter of this tutorial.

The finally Statement

The finally statement lets you execute code, after try and catch, regardless of the result:

try { Block of code to try } catch(err) { Block of code to handle errors } finally { Block of code to be executed regardless of the try / catch result }

Below is an example code:

let x = prompt("Enter a number between 5 and 10 (both included):", 5); try { if (x.trim() === "") throw "Please enter a number"; if (isNaN(x)) throw "Input is not a number"; Number(x); if (x < 5) throw "Input is too low"; if (x > 10) throw "Input is too high"; if (x <= 10 && x >= 5) throw `Your input value is ${x}`; } catch(err) { alert(err); } finally { alert("Thank you!"); }

An alert window displaying "Thank you!" will always execute regardless of what the user input is.

The Error Object

JavaScript has a built in error object that provides error information when an error occurs.

The error object provides two useful properties: name and message.

Error Object Properties

  • name: Sets or returns an error name
  • message: Sets or returns an error message (a string)

Error Name Values

Six different values can be returned by the error name property:

  • EvalError: An error has occurred in the eval() function
  • RangeError: A number "out of range" has occurred
  • ReferenceError: An illegal reference has occurred
  • SyntaxError: A syntax error has occurred
  • TypeError: A type error has occurred
  • URIError: An error in encodeURI() has occurred

Eval Error

An EvalError indicates an error in the eval() function.

Newer versions of JavaScript do not throw EvalError. Use SyntaxError instead.

Range Error

A RangeError is thrown if you use a number that is outside the range of legal values.

For example: You cannot set the number of significant digits of a number to 500:

try { let x = 1; x.toPrecision(500); // a number cannot have 500 significant digits } catch(err) { alert(err.message); // display the error message }

The alert message will display a value of "toPrecision() argument must be between 1 and 100"

Reference Error

A ReferenceError is thrown if you use (reference) a variable that has not been declared:

try { let x = 1; x = y + 1; // y is never declared } catch(err) { alert(err.name); // display the error name }

Syntax Error

A SyntaxError is thrown if you try to evaluate code with a syntax error:

try { eval("alert('Hello)") } catch(err) { alert(err.name); // display the error name }

The alert window will display a value of "SyntaxError"

Type Error

A TypeError is thrown if an operand or argument is incompatible with the type expected by an operator or function:

try { let x = 1; x.toUpperCase(); // you cannot use this string method to a number } catch(err) { alert(err.name); // returns TypeError }

URI (Uniform Resource Identifier) Error

A URIError is thrown if you use illegal characters in a URI function:

try { decodeURI("%%%"); // You cannot URI decode percent signs } catch(err) { alert(err.name); // returns URIError }

For a complete reference of the Error object go to W3Schools Complete JavaScript Error Reference.

JavaScript Scope

Scope determines the accessibility (visibility) of variables.

JavaScript variables have 3 types of scope:

  • Block scope
  • Function scope
  • Global scope

Block Scope

Before ES6 (2015), JavaScript variables had only Global Scope and Function Scope.

ES6 introduced two important new JavaScript keywords: let and const.

These two keywords provide Block Scope in JavaScript.

Variables declared inside a { } block cannot be accessed from outside the block:

{ let x = 2; } // x can NOT be used here

Variables declared with the var keyword can NOT have block scope.

Variables declared using var inside a { } block can be accessed from outside the block:

{ var x = 2; } // x CAN be used here

Local Scope

Variables declared within a JavaScript function, are LOCAL to the function:

// code here can NOT use carName function myFunction() { let carName = "Volvo"; // code here CAN use carName } // code here can NOT use carName

Local variables have Function Scope.

They can only be accessed from within the function.

Since local variables are only recognized inside their functions, variables with the same name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is completed.

Function Scope

JavaScript has function scope: Each function creates a new scope.

Variables defined inside a function are not accessible (visible) from outside the function.

Variables declared with var, let and const are quite similar when declared inside a function.

They all have Function Scope:

function myFunction1() { var carName = "Volvo"; // Function Scope } function myFunction2() { let carName = "Volvo"; // Function Scope } function myFunction3() { const carName = "Volvo"; // Function Scope }

Global JavaScript Variables

A variable declared outside a function, becomes GLOBAL:

let carName = "Volvo"; // code here can use carName function myFunction() { // code here can also use carName }

A global variable has Global Scope:

All scripts and functions on a web page can access it.

Global Scope

Variables declared Globally (outside any function) have Global Scope.

Global variables can be accessed from anywhere in a JavaScript program.

Variables declared with var, let and const are quite similar when declared outside a block.

They all have Global Scope:

var x = 2; // Global scope let y = 2; // Global scope const z = 2; // Global scope

JavaScript Variables

In JavaScript, objects and functions are also variables.

Scope determines the accessibility of variables, objects, and functions from different parts of the code.

Automatically Global

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.

This code example will declare a global variable carName, even if the value is assigned inside a function:

myFunction(); // code here can use carName function myFunction() { carName = "Volvo"; }

Strict Mode

All modern browsers support running JavaScript in "Strict Mode".

In "Strict Mode", undeclared variables are not automatically global.

We will learn more about how to use strict mode in later topics.

Global Variables in HTML

With JavaScript, the global scope is the JavaScript environment.

In HTML, the global scope is the window object.

Global variables defined with the var keyword belong to the window object:

var carName = "Volvo"; // code here can use window.carName

Global variables defined with the let keyword do not belong to the window object:

let carName = "Volvo"; // code here can not use window.carName

Warning

Do NOT create global variables unless you intend to.

Your global variables (or functions) can overwrite window variables (or functions).

Any function, including the window object, can overwrite your global variables and functions.

The Lifetime of JavaScript Variables

The lifetime of a JavaScript variable starts when it is declared.

Function (local) variables are deleted when the function is completed.

In a web browser, global variables are deleted when you close the browser window (or tab).

Function Arguments

Function arguments (parameters) work as local variables inside functions.

JavaScript Hoisting

Hoisting is JavaScript's default behavior of moving declarations to the top.

JavaScript Declarations are Hoisted

In JavaScript, a variable can be declared after it has been used.

In other words; a variable can be used before it has been declared.

Example 1 gives the same result as Example 2:

Example 1:

x = 5; // Assign value to x alert(x); // Display x var x; // Declare x

Example 2:

var x; // Declare x x = 5; // Assign value to x alert(x); // Display x

To understand this, you have to understand the term "hoisting".

Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).

The let and const Keywords

Variables defined with let and const are hoisted to the top of the block, but not initialized.

Meaning: The block of code is aware of the variable, but it cannot be used until it has been declared.

Using a let variable before it is declared will result in a ReferenceError.

The variable is in a "temporal dead zone" from the start of the block until it is declared:

The example code below results into a ReferenceError:

try { x = 5; let x; } catch(e) { alert(e); }

The alert window will display "ReferenceError: Cannot access 'x' before initialization"

Using a const variable before it is declared, is a syntax error, so the code will simply not run:

x = 5; const x;

This code will simply throw SyntaxError.

JavaScript Initializations are Not Hoisted

JavaScript only hoists declarations, not initializations.

Example 1 does not give the same result as Example 2:

Example 1:

var x = 5; // Declare and initialize x var y = 7; // Declare and initialize y console.log(x + y); // returns 12

Example 2:

var x = 5; // Declare and initialize x console.log(x + y); // returns NaN since y is undefined var y = 7; // Declare and initialize y

Does it make sense that y is undefined in the last example?

This is because only the declaration (var y), not the initialization (=7) is hoisted to the top.

Because of hoisting, y has been declared before it is used, but because initializations are not hoisted, the value of y is undefined.

Example 2 is the same as writing:

var x = 5; // Declare and initialize x var y; // Declare y console.log(x + y); // returns NaN since y is still undefined y = 7; // Initialize y

Declare Your Variables At the Top !

Hoisting is (to many developers) an unknown or overlooked behavior of JavaScript

If a developer doesn't understand hoisting, programs may contain bugs (errors).

To avoid bugs, always declare all variables at the beginning of every scope.

Since this is how JavaScript interprets the code, it is always a good rule.

JavaScript in strict mode does not allow variables to be used if they are not declared.

JavaScript Use Strict

"use strict";

This line of code defines that JavaScript code should be executed in "strict mode".

The "use strict" Directive

The "use strict" directive was new in ECMAScript version 5.

It is not a statement, but a literal expression, ignored by earlier versions of JavaScript.

The purpose of "use strict" is to indicate that the code should be executed in "strict mode".

With strict mode, you can not, for example, use undeclared variables.

All modern browsers support "use strict" except Internet Explorer 9 and lower:

You can use strict mode in all your programs. It helps you to write cleaner code, like preventing you from using undeclared variables.

Declaring Strict Mode

Strict mode is declared by adding "use strict"; to the beginning of a script or a function.

Declared at the beginning of a script, it has global scope (all code in the script will execute in strict mode):

"use strict"; x = 3.14; // This will cause an error because x is not declared

Another one with a function:

"use strict"; myFunction(); function myFunction() { y = 3.14; // This will also cause an error because y is not declared }

Declared inside a function, it has local scope (only the code inside the function is in strict mode):

x = 3.14; // This will not cause an error. myFunction(); function myFunction() { "use strict"; y = 3.14; // This will cause an error }

The "use strict"; Syntax

The syntax, for declaring strict mode, was designed to be compatible with older versions of JavaScript.

Compiling a numeric literal (4 + 5;) or a string literal ("John Doe";) in a JavaScript program has no side effects. It simply compiles to a non existing variable and dies.

So "use strict"; only matters to new compilers that "understand" the meaning of it.

Why Strict Mode?

Strict mode makes it easier to write "secure" JavaScript.

Strict mode changes previously accepted "bad syntax" into real errors.

As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.

In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.

In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error.

Not Allowed in Strict Mode

Using a variable, without declaring it, is not allowed:

"use strict"; x = 3.14; // This will cause an error

Objects are variables too.

Using an object, without declaring it, is not allowed:

"use strict"; x = {p1:10, p2:20}; // This will cause an error

Deleting a variable (or object) is not allowed.

"use strict"; let x = 3.14; delete x; // This will cause an error

Deleting a function is not allowed.

"use strict"; function x(p1, p2) {}; delete x; // This will cause an error

Duplicating a parameter name is not allowed:

"use strict"; function x(p1, p1) {}; // This will cause an error

Octal numeric literals are not allowed:

"use strict"; let x = 010; // This will cause an error

Octal escape characters are not allowed:

"use strict"; let x = "\010"; // This will cause an error

Writing to a read-only property is not allowed:

"use strict"; const obj = {}; Object.defineProperty(obj, "x", {value:0, writable:false}); obj.x = 3.14; // This will cause an error

Writing to a get-only property is not allowed:

"use strict"; const obj = {get x() {return 0} }; obj.x = 3.14; // This will cause an error

Deleting an undeletable property is not allowed:

"use strict"; delete Object.prototype; // This will cause an error

The word eval cannot be used as a variable:

"use strict"; let eval = 3.14; // This will cause an error

The word arguments cannot be used as a variable:

"use strict"; let arguments = 3.14; // This will cause an error

The with statement is not allowed:

"use strict"; with (Math){x = cos(2)}; // This will cause an error

For security reasons, eval() is not allowed to create variables in the scope from which it was called:

"use strict"; eval ("x = 2"); alert (x); // This will cause an error

In strict mode, eval() can not declare a variable using the var keyword:

"use strict"; eval ("var x = 2"); alert (x); // This will cause an error

eval() can not declare a variable using the let keyword:

eval ("let x = 2"); alert (x); // This will cause an error

The this keyword in functions behaves differently in strict mode.

The this keyword refers to the object that called the function.

If the object is not specified, functions in strict mode will return undefined and functions in normal mode will return the global object (window):

"use strict"; function myFunction() { alert(this); // will alert "undefined" } myFunction();

Future Proof!

Keywords reserved for future JavaScript versions can NOT be used as variable names in strict mode.

These are:

  • implements
  • interface
  • let
  • package
  • private
  • protected
  • public
  • static
  • yield
"use strict"; let public = 1500; // This will cause an error

Watch Out!

The "use strict" directive is only recognized at the beginning of a script or a function.

The JavaScript this Keyword

In this example, this refers to the person object.

Because fullName is a method of the person object:

const person = { firstName: "John", lastName: "Doe", id: 5566, fullName : function() { return `${this.firstName} ${this.lastName}`; } };

What is this?

In JavaScript, the this keyword refers to an object.

The this keyword refers to different objects depending on how it is used:

  • In an object method, this refers to the object.
  • Alone, this refers to the global object.
  • In a function, this refers to the global object.
  • In a function, in strict mode, this is undefined.
  • In an event, this refers to the element that received the event.
  • Methods like call(), apply(), and bind() can refer this to any object.

Note:

this is not a variable. It is a keyword. You cannot change the value of this.

this in a Method

When used in an object method, this refers to the object.

In the example on top of this page, this refers to the person object.

Because the fullName method is a method of the person object:

fullName : function() { return `${this.firstName} ${this.lastName}`; }

this Alone

When used alone, this refers to the global object.

Because this is running in the global scope.

In a browser window the global object is [object Window]:

let x = this; alert(x); // returns [object Window]

In strict mode, when used alone, this also refers to the global object.

this in a Function (Default)

In a function, the global object is the default binding for this.

In a browser window the global object is [object Window]:

function myFunction() { return this; } alert(myFunction()); // returns [object Window]

this in a Function (Strict)

JavaScript strict mode does not allow default binding.

So, when used in a function, in strict mode, this is undefined:

function myFunction() { "use strict"; return this; } alert(myFunction()); // returns undefined

this in Event Handlers

In HTML event handlers, this refers to the HTML element that received the event:

<button onclick="this.style.display='none'"> Click to Remove Me! </button>

If this button element is clicked, its display will become none.

this refers to the button element in this example.

Object Method Binding

In this examples, this is the person object:

const person = { firstName: "John", lastName: "Doe", id: 5566, myFunction : function() { return this; } }; alert(person.myFunction()); // returns [object Object]

Explicit Function Binding

The call() and apply() methods are predefined JavaScript methods.

They can both be used to call an object method with another object as argument.

The example below calls person1.fullName with person2 as an argument, this refers to person2, even if fullName is a method of person1:

const person1 = { fullName: function() { return this.firstName + " " + this.lastName; } } const person2 = { firstName:"John", lastName: "Doe", } // Return "John Doe": person1.fullName.call(person2);

Function Borrowing

With the bind() method, an object can borrow a method from another object.

This example creates 2 objects (person and member).

The member object borrows the fullname method from the person object:

const person = { firstName:"John", lastName: "Doe", fullName: function () { return this.firstName + " " + this.lastName; } } const member = { firstName:"Hege", lastName: "Nilsen", } let fullName = person.fullName.bind(member);

This Precedence

To determine which object this refers to; use the following precedence of order.

Precedence Object
1 bind()
2 apply() and call()
3 Object method
4 Global scope

JavaScript Arrow Function

Arrow functions were introduced in ES6.

Arrow functions allow us to write shorter function syntax:

let myFunction = (a, b) => a * b;

Before Arrow:

let hello = function() { return "Hello World!"; }

With Arrow Function:

let hello = () => { return "Hello World!"; }

It gets shorter! If the function has only one statement, and the statement returns a value, you can remove the brackets and the return keyword:

let hello = () => "Hello World!";

Note: This works only if the function has only one statement.

All of these codes are the same, just different in syntax!

If you have parameters, you pass them inside the parentheses:

Arrow Function With Parameters:

let hello = (value) => `Hello ${value}`;

In fact, if you have only one parameter, you can skip the parentheses as well:

Arrow Function Without Parentheses:

let hello = value => `Hello ${value}`;

What About this?

The handling of this is also different in arrow functions compared to regular functions.

In short, with arrow functions there are no binding of this.

In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever.

With arrow functions the this keyword always represents the object that defined the arrow function .

Remember these differences when you are working with functions. Sometimes the behavior of regular functions is what you want, if not, use arrow functions.

JavaScript Classes

ECMAScript 2015, also known as ES6, introduced JavaScript Classes.

JavaScript Classes are templates for JavaScript Objects.

JavaScript Class Syntax

Use the keyword class to create a class.

Always add a method named constructor():

class ClassName { constructor() { ... } }

Below is an example usage of class:

class Car { constructor(name, year) { this.name = name; this.year = year; } } const car1 = new Car("Toyota", 1999); console.log(car1.name); // returns "Toyota"

The example above creates a class named "Car".

The class has two initial properties: "name" and "year".

A JavaScript class is not an object.

It is a template for JavaScript objects.

Using a Class

When you have a class, you can use the class to create objects:

class Car { constructor(name, year) { this.name = name; this.year = year; } } const myCar1 = new Car("Ford", 2014); const myCar2 = new Car("Audi", 2019);

The example above uses the Car class to create two Car objects.

The constructor method is called automatically when a new object is created.

The Constructor Method

The constructor method is a special method:

  • It has to have the exact name "constructor"
  • It is executed automatically when a new object is created
  • It is used to initialize object properties

If you do not define a constructor method, JavaScript will add an empty constructor method.

Class Methods

Class methods are created with the same syntax as object methods.

Use the keyword class to create a class.

Always add a constructor() method.

Then add any number of methods:

class ClassName { constructor() { ... } method_1() { ... } method_2() { ... } method_3() { ... } }

Create a Class method named "age", that returns the Car age:

class Car { constructor(name, year) { this.name = name; this.year = year; } age() { const date = new Date(); return date.getFullYear() - this.year; } } const car1 = new Car("Toyota", 1999); console.log(car1.age()); // returns 26

You can even send parameters to Class methods.

JavaScript Modules

JavaScript modules allow you to break up your code into separate files.

This makes it easier to maintain a code-base.

Modules are imported from external files with the import statement.

Modules also rely on type="module" in the <script> tag:

<script type="module"> import message from "./message.js"; </script>

Export

Modules with functions or variables can be stored in any external file.

There are two types of exports: Named Exports and Default Exports.

Named Exports

Let us create a file named person.js, and fill it with the things we want to export.

You can create named exports two ways. In-line individually, or all at once at the bottom.

In-line individually:

export const name = "Jesse"; export const name = "Jesse";

All at once at the bottom:

const name = "Jesse"; const age = 40; export {name, age};

Default Exports

Let us create another file, named message.js, and use it for demonstrating default export.

You can only have one default export in a file:

const message = () => { const name = "Jesse"; const age = 40; return name + ' is ' + age + 'years old.'; }; export default message;

Import

You can import modules into a file in two ways, based on if they are named exports or default exports .

Named exports are constructed using curly braces. Default exports are not.

Import from named exports:

import { name, age } from "./person.js";

Import from default exports:

import message from "./message.js";

Note:

Modules only work with the HTTP(s) protocol.

A web-page opened via the file:// protocol cannot use import / export.

JavaScript JSON

JSON is a format for storing and transporting data.

JSON is often used when data is sent from a server to a web page.

What is JSON?

  • JSON stands for JavaScript Object Notation
  • JSON is a lightweight data interchange format
  • JSON is language independent *
  • JSON is "self-describing" and easy to understand

* The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for reading and generating JSON data can be written in any programming language.

JSON Example

This JSON syntax defines an employees object: an array of 3 employee records (objects):

JSON Example:

{ "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] }

The JSON Format Evaluates to JavaScript Objects

The JSON format is syntactically identical to the code for creating JavaScript objects.

Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects.

JSON Syntax Rules

  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays

JSON Data - A Name and a Value

JSON data is written as name/value pairs, just like JavaScript object properties.

A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:

JSON names require double quotes. JavaScript names do not.

JSON Objects

JSON objects are written inside curly braces.

Just like in JavaScript, objects can contain multiple name/value pairs:

{"firstName":"John", "lastName":"Doe"}

JSON Arrays

JSON arrays are written inside square brackets.

Just like in JavaScript, an array can contain objects:

"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ]

In the example above, the object "employees" is an array. It contains three objects.

Each object is a record of a person (with a first name and a last name).

Converting a JSON Text to a JavaScript Object

A common use of JSON is to read data from a web server, and display the data in a web page.

For simplicity, this can be demonstrated using a string as input.

First, create a JavaScript string containing JSON syntax:

let text = '{ "employees" : [' + '{ "firstName":"John" , "lastName":"Doe" },' + '{ "firstName":"Anna" , "lastName":"Smith" },' + '{ "firstName":"Peter" , "lastName":"Jones" } ]}';

Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript object:

const obj = JSON.parse(text);

Finally, use the new JavaScript object in your page.

JavaScript Debugging

Errors can (will) happen, every time you write some new computer code.

Code Debugging

Programming code might contain syntax errors, or logical errors.

Many of these errors are difficult to diagnose.

Often, when programming code contains errors, nothing will happen. There are no error messages, and you will get no indications where to search for errors.

Searching for (and fixing) errors in programming code is called code debugging.

JavaScript Debuggers

Debugging is not easy. But fortunately, all modern browsers have a built-in JavaScript debugger.

Built-in debuggers can be turned on and off, forcing errors to be reported to the user.

With a debugger, you can also set breakpoints (places where code execution can be stopped), and examine variables while the code is executing.

Normally (otherwise follow the steps at the bottom of this page), you activate debugging in your browser with the F12 key, and select "Console" in the debugger menu.

The console.log() Method

If your browser supports debugging, you can use console.log() to display JavaScript values in the debugger window.

Read more about the console.log() method in W3Schools JavaScript Console Reference.

Setting Breakpoints

In the debugger window, you can set breakpoints in the JavaScript code.

At each breakpoint, JavaScript will stop executing, and let you examine JavaScript values.

After examining values, you can resume the execution of code (typically with a play button).

The debugger Keyword

The debugger keyword stops the execution of JavaScript, and calls (if available) the debugging function.

This has the same function as setting a breakpoint in the debugger.

If no debugging is available, the debugger statement has no effect.

With the debugger turned on, this code will stop executing before it executes the third line:

let x = 15 * 5; debugger; document.getElementById("demo").innerHTML = x;

Did You Know?

Debugging is the process of testing, finding, and reducing bugs (errors) in computer programs. The first known computer bug was a real bug (an insect) stuck in the electronics.

JavaScript Style Guide

Always use the same coding conventions for all your JavaScript projects.

JavaScript Coding Conventions

Coding conventions are style guidelines for programming. They typically cover:

  • Naming and declaration rules for variables and functions.
  • Rules for the use of white space, indentation, and comments.
  • Programming practices and principles.

Coding conventions secure quality:

  • Improve code readability
  • Make code maintenance easier

Coding conventions can be documented rules for teams to follow, or just be your individual coding practice.

Variable Names

At W3Schools, they use camelCase for identifier names (variables and functions).

All names start with a letter:

const firstName = "John"; const lastName = "Doe"; const price = 19.90; const tax = 0.20; const fullPrice = price + (price * tax);

Spaces Around Operators

Always put spaces around operators ( = + - * / ), and after commas:

let x = y + z; const myArray = ["Volvo", "Saab", "Fiat"];

Code Indentation

Always use 2 spaces for indentation of code blocks.

Note:

Do not use tabs (tabulators) for indentation. Different editors interpret tabs differently.

Statement Rules

General rules for simple statements:

  • Always end a simple statement with a semicolon.
const cars = ["Volvo", "Saab", "Fiat"]; const person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue" };

General rules for complex (compound) statements:

  • Put the opening bracket at the end of the first line.
  • Use one space before the opening bracket.
  • Put the closing bracket on a new line, without leading spaces.
  • Do not end a complex statement with a semicolon.

Functions:

function toCelsius(fahrenheit) { return (5 / 9) * (fahrenheit - 32); }

Loops:

for (let i = 0; i < 5; i++) { x += i; }

Conditionals:

if (time < 20) { greeting = "Good day"; } else { greeting = "Good evening"; }

Object Rules

General rules for object definitions:

  • Place the opening bracket on the same line as the object name.
  • Use colon plus one space between each property and its value.
  • Use quotes around string values, not around numeric values.
  • Do not add a comma after the last property-value pair.
  • Place the closing bracket on a new line, without leading spaces.
  • Always end an object definition with a semicolon.
const person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue" };

Short objects can be written compressed, on one line, using spaces only between properties, like this:

const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Line Length < 80

For readability, avoid lines longer than 80 characters.

If a JavaScript statement does not fit on one line, the best place to break it, is after an operator or a comma .

document.getElementById("demo").innerHTML = "Hello Dolly.";

Naming Conventions

Always use the same naming convention for all your code. For example:

  • Variable and function names written as camelCase
  • Global variables written in UPPERCASE (We don't, but it's quite common)
  • Constants (like PI) written in UPPERCASE

Should you use hyp-hens, camelCase, or under_scores in variable names?

This is a question programmers often discuss. The answer depends on who you ask:

Hyphens in HTML and CSS:

HTML5 attributes can start with data- (data-quantity, data-price).

CSS uses hyphens in property-names (font-size).

Note: Hyphens can be mistaken as subtraction attempts. Hyphens are not allowed in JavaScript names.

Underscores:

Many programmers prefer to use underscores (date_of_birth), especially in SQL databases.

Underscores are often used in PHP documentation.

PascalCase:

PascalCase is often preferred by C programmers.

camelCase:

camelCase is used by JavaScript itself, by jQuery, and other JavaScript libraries.

Note:

Do not start names with a $ sign. It will put you in conflict with many JavaScript library names.

Loading JavaScript in HTML

Use simple syntax for loading external scripts (the type attribute is not necessary):

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

Accessing HTML Elements

A consequence of using "untidy" HTML styles, might result in JavaScript errors.

These two JavaScript statements will produce different results:

const obj = getElementById("Demo") const obj = getElementById("demo")

If possible, use the same naming convention (as JavaScript) in HTML.

File Extensions

HTML files should have a .html extension (.htm is allowed).

CSS files should have a .css extension.

JavaScript files should have a .js extension.

Use Lower Case File Names

Most web servers (Apache, Unix) are case sensitive about file names:

london.jpg cannot be accessed as London.jpg.

Other web servers (Microsoft, IIS) are not case sensitive:

london.jpg can be accessed as London.jpg or london.jpg.

If you use a mix of upper and lower case, you have to be extremely consistent.

If you move from a case insensitive, to a case sensitive server, even small errors can break your web site.

To avoid these problems, always use lower case file names (if possible).

Performance

Coding conventions are not used by computers. Most rules have little impact on the execution of programs.

Indentation and extra spaces are not significant in small scripts.

For code in development, readability should be preferred. Larger production scripts should be minimized.

JavaScript Best Practices

Avoid global variables, avoid new, avoid ==, avoid eval()

Avoid Global Variables

Minimize the use of global variables.

This includes all data types, objects, and functions.

Global variables and functions can be overwritten by other scripts.

Use local variables instead, and learn how to use closures.

Always Declare Local Variables

All variables used in a function should be declared as local variables.

Local variables must be declared with the var, the let, or the const keyword, otherwise they will become global variables.

Strict mode does not allow undeclared variables.

Declarations on Top

It is a good coding practice to put all declarations at the top of each script or function.

This will:

  • Give cleaner code
  • Provide a single place to look for local variables
  • Make it easier to avoid unwanted (implied) global variables
  • Reduce the possibility of unwanted re-declarations
// Declare at the beginning let firstName, lastName, price, discount, fullPrice; // Use later firstName = "John"; lastName = "Doe"; price = 19.90; discount = 0.10; fullPrice = price - discount;

This also goes for loop variables:

for (let i = 0; i < 5; i++) { // your code }

Initialize Variables

It is a good coding practice to initialize variables when you declare them.

This will:

  • Give cleaner code
  • Provide a single place to initialize variables
  • Avoid undefined values

Initializing variables provides an idea of the intended use (and intended data type).

Declare Objects with const

Declaring objects with const will prevent any accidental change of type:

Example 1:

let car = {type:"Fiat", model:"500", color:"white"}; car = "Fiat"; // Accidentally changes object to string

Example 2:

let car = {type:"Fiat", model:"500", color:"white"}; car = "Fiat"; // Not possible

Declare Arrays with const

Declaring arrays with const will prevent any accidential change of type:

Example 1:

let cars = ["Saab", "Volvo", "BMW"]; cars = 3; // Accidentally changes array to number

Example 2:

const cars = ["Saab", "Volvo", "BMW"]; cars = 3; // Not possible

Don't Use new Object()

  • Use "" instead of new String()
  • Use 0 instead of new Number()
  • Use false instead of new Boolean()
  • Use {} instead of new Object()
  • Use [] instead of new Array()
  • Use /()/ instead of new RegExp()
  • Use function (){} instead of new Function()

Beware of Automatic Type Conversions

JavaScript is loosely typed.

A variable can contain all data types.

A variable can change its data type:

let x = "Hello"; // typeof x is a string x = 5; // changes typeof x to a number

Beware that numbers can accidentally be converted to strings or NaN (Not a Number).

When doing mathematical operations, JavaScript can convert numbers to strings.

Subtracting a string from a string, does not generate an error but returns NaN (Not a Number):

let x = "Hello" - "Dolly"; // returns NaN

Use === Comparison

The == comparison operator always converts (to matching types) before comparison.

The === operator forces comparison of values and type:

Examples:

0 == ""; // true 1 == "1"; // true 1 == true; // true 0 === ""; // false 1 === "1"; // false 1 === true; // false

Use Parameter Defaults

If a function is called with a missing argument, the value of the missing argument is set to undefined.

Undefined values can break your code. It is a good habit to assign default values to arguments:

function multiply(x = 0, y = 0) { return x * y; } console.log( multiply() ); // returns 0

End Your Switches with Defaults

Always end your switch statements with a default. Even if you think there is no need for it:

switch (new Date().getDay()) { case 1: case 2: case 3: case 4: case 5: console.log("Happy weekday!"); break case 6: case 7: console.log("Happy weekend!"); break default: console.log("Error. Something went wrong."); }

Avoid Number, String, and Boolean as Objects

Always treat numbers, strings, or booleans as primitive values. Not as objects.

Declaring these types as objects, slows down execution speed, and produces nasty side effects.

Avoid Using eval()

The eval() function is used to run text as code. In almost all cases, it should not be necessary to use it.

Because it allows arbitrary code to be run, it also represents a security problem.