JavaScript Tutorial
JavaScript Tutorial
Example
My First JavaScript
If you have a large screen, the menu will always be present on the left.
If you have a small screen, open the menu by clicking the top menu sign ☰.
Learn by Examples
Examples are better than 1000 words. Examples are often easier to understand than text
explanations.
This tutorial supplements all explanations with clarifying "Try it Yourself" examples.
If you try all the examples, you will learn a lot about JavaScript, in a very short time!
Learning Speed
In this tutorial, the learning speed is your choice.
Everything is up to you.
The only way to become a clever programmer is to: Practice. Practice. Practice. Code. Code.
Code !
JavaScript is already running in your browser on your computer, on your tablet, and on
your smart-phone.
JavaScript References
W3Schools maintains a complete JavaScript reference, including all HTML and browser objects.
The reference contains examples for all properties, methods and events, and is continuously
updated according to the latest web standards.
The example below "finds" an HTML element (with id="demo"), and changes the element
content (innerHTML) to "Hello JavaScript":
Example
Example
Example
document.getElementById("demo").style.fontSize = "35px";
Example
document.getElementById("demo").style.display = "none";
Example
document.getElementById("demo").style.display = "block";
JavaScript and Java are completely different languages, both in concept and design.
JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997.
ECMA-262 is the official name of the standard. ECMAScript is the official name of the
language.
The <script> Tag
In HTML, JavaScript code is inserted between <script> and </script> tags.
Example
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
For example, a function can be called when an event occurs, like when the user clicks a button.
You will learn much more about functions and events in later chapters.
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
JavaScript in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML page.
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
</body>
</html>
JavaScript in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML page.
Example
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
Placing scripts at the bottom of the <body> element improves the display speed, because script
interpretation slows down the display.
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.
To use an external script, put the name of the script file in the src (source) attribute of a
<script> tag:
Example
<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.
To add several script files to one page - use several script tags:
Example
<script src="myScript1.js"></script>
<script src="myScript2.js"></script>
External References
External scripts can be referenced with a full URL or with a path relative to the current web
page.
Example
<script src="https://www.w3schools.com/js/myScript.js"></script>
This example uses a script located in a specified folder on the current web site:
Example
<script src="/js/myScript.js"></script>
This example links to a script located in the same folder as the current page:
Example
<script src="myScript.js"></script>
You can read more about file paths in the chapter HTML File Paths.
JavaScript Output
Using innerHTML
To access an HTML element, JavaScript can use the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the HTML
content:
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Changing the innerHTML property of an HTML element is a common way to display data in
HTML.
Using document.write()
For testing purposes, it is convenient to use document.write():
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using document.write() after an HTML document is loaded, will delete all existing HTML:
Example
<!DOCTYPE html>
<html>
<body>
<!DOCTYPE html>
<html>
<body>
</body>
</html>
JavaScript Statements
Example
let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
JavaScript Programs
A computer program is a list of "instructions" to be "executed" by a computer.
JavaScript Statements
JavaScript statements are composed of:
This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
Example
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.
a = 5; b = 6; c = a + b;
let x = y + z;
Example
document.getElementById("demo").innerHTML =
"Hello Dolly!";
One place you will find statements grouped together in blocks, is in JavaScript functions:
Example
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}
Try yourself
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed.
Visit our Reserved Words reference to view a full list of JavaScript keywords.
Here is a list of some of the keywords you will learn about in this tutorial:
Keyword Description
debugger Stops the execution of JavaScript, and calls (if available) the debugging function
do ... while Executes a block of statements, and repeats the block, while a condition is true
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:
JavaScript Values
The JavaScript syntax defines two types of values:
• Fixed values
• Variable values
JavaScript Literals
The two most important syntax rules for fixed values are:
10.50
1001
"John Doe"
'John Doe'
JavaScript Variables
In a programming language, variables are used to store data values.
JavaScript uses the keywords var, let and const to declare variables.
let x;
x = 6;
JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:
(5 + 6) * 10
let x, y;
x = 5;
y = 6;
JavaScript Expressions
An expression is a combination of values, variables, and operators, which computes to a value.
5 * 10
x * 10
JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.
let x, y;
x = 5 + 6;
y = x * 10;
var x, y;
x = 5 + 6;
y = x * 10;
In these examples, using var or let will produce the same result.
You will learn more about var and let later in this tutorial.
JavaScript Comments
Not all JavaScript statements are "executed".
JavaScript Identifiers
Identifiers are names.
In JavaScript, identifiers are used to name variables (and keywords, and functions, and labels).
The rules for legal names are much the same in most programming languages.
In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign ($).
Hyphens:
Hyphens are not allowed in JavaScript. They are reserved for subtractions.
Underscore:
JavaScript programmers tend to use camel case that starts with a lowercase letter:
Unicode covers (almost) all the characters, punctuations, and symbols in the world.
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.
Any text between // and the end of the line will be ignored by JavaScript (will not be executed).
Example
// 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:
Example
Multi-line Comments
Multi-line comments start with /* and end with */.
This example uses a multi-line comment (a comment block) to explain the code:
Example
/*
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.";
Adding // in front of a code line changes the code lines from an executable line to a comment.
Example
Example
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/
JavaScript Variables
There are 3 ways to declare a JavaScript variable:
• Using var
• Using let
• Using const
The let and const keywords are explained in the next chapters.
Variables
Variables are containers for storing data (values).
In this example, x, y, and z, are variables, declared with the var keyword:
Example
var x = 5;
var y = 6;
var z = x + y;
Example
var price1 = 5;
var price2 = 6;
var total = price1 + price2;
In programming, just like in algebra, we use variables (like price1) to hold values.
In programming, just like in algebra, we use variables in expressions (total = price1 + price2).
From the example above, you can calculate the total to be 11.
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
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:
This is different from algebra. The following does not make sense in algebra:
x=x+5
(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)
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.
Example
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
var carName;
After the declaration, the variable has no value (technically it has the value of undefined).
carName = "Volvo";
You can also assign a value to the variable when you declare it:
In the example below, we create a variable called carName and assign the value "Volvo" to it.
Example
<p id="demo"></p>
<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
It's a good programming practice to declare all variables at the beginning of a script.
Start the statement with var and separate the variables by comma:
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.
The variable carName will have the value undefined after the execution of this statement:
Example
var carName;
The variable carName will still have the value "Volvo" after the execution of these statements:
Example
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:
Example
var x = 5 + 2 + 3;
Example
Example
var x = "5" + 2 + 3;
If you put a number in quotes, the rest of the numbers will be treated as strings, and
concatenated.
Example
var x = 2 + 3 + "5";
Since JavaScript treats a dollar sign as a letter, identifiers containing $ are valid variable names:
Example
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 $("p"); means "select all p elements".
Example
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.
Cannot be Reassigned
Example
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
Must be Assigned
JavaScript const variables must be assigned a value when they are declared:
Correct
const PI = 3.14159265359;
Incorrect
const PI;
PI = 3.14159265359;
• A new Array
• A new Object
• A new Function
• A new RegExp
Constant Objects and Arrays
The keyword const is a little misleading.
Constant Arrays
You can change the elements of a constant array:
Example
Example
Example
Example
Browser Support
The const keyword is not supported in Internet Explorer 10 or earlier.
The following table defines the first browser versions with full support for the const keyword:
Block Scope
Declaring a variable with const is similar to let when it comes to Block Scope.
The x declared in the block, in this example, is not the same as the x declared outside the block:
Example
const x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
You can learn more about block scope in the chapter JavaScript Scope.
Redeclaring
Redeclaring a JavaScript var variable is allowed anywhere in a program:
Example
var x = 2; // Allowed
var x = 3; // Allowed
x = 4; // Allowed
Redeclaring an existing var or let variable to const, in the same scope, is not allowed:
Example
var x = 2; // Allowed
const x = 2; // Not allowed
{
let x = 2; // Allowed
const x = 2; // Not allowed
}
{
const x = 2; // Allowed
const x = 2; // Not allowed
}
const x = 2; // Allowed
x = 2; // Not allowed
var x = 2; // Not allowed
let x = 2; // Not allowed
const x = 2; // Not allowed
{
const x = 2; // Allowed
x = 2; // Not allowed
var x = 2; // Not allowed
let x = 2; // Not allowed
const x = 2; // Not allowed
}
Example
const x = 2; // Allowed
{
const x = 3; // Allowed
}
{
const x = 4; // Allowed
}
Const Hoisting
Variables defined with var are hoisted to the top and can be initialized at any time.
Example
This is OK:
carName = "Volvo";
var carName;
If you want to learn more about hoisting, study the chapter JavaScript Hoisting.
Variables defined with const are also hoisted to the top, but not initialized.
Example
alert (carName);
const carName = "Volvo";
JavaScript Operators
Example
Assignment
let x = 10;
Adding
let x = 5;
let y = 2;
let z = x + y;
Multiplying
let x = 5;
let y = 2;
let z = x * y;
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
Assignment
let x = 10;
x += 5;
Example
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
John Doe
Example
Example
let x = 5 + 5;
let y = "5" + 5;
let z = "Hello" + 5;
10
55
Hello5
Any numeric operand in the operation is converted into a 32 bit number. The result is converted
back to a JavaScript number.
Operator Description Example Same as Result Decimal
& AND 5&1 0101 & 0001 0001 1
| OR 5|1 0101 | 0001 0101 5
~ NOT ~5 ~0101 1010 10
^ XOR 5^1 0101 ^ 0001 0100 4
<< Zero fill left shift 5 << 1 0101 << 1 1010 10
>> Signed right shift 5 >> 1 0101 >> 1 0010 2
>>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010 2
The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed numbers.
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.
~00000000000000000000000000000101 will return 11111111111111111111111111111010
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
% Modulus (Remainder)
++ Increment
-- Decrement
Arithmetic Operations
A typical arithmetic operation operates on two numbers.
Example
or variables:
Example
let x = a + b;
or expressions:
Example
The operation (to be performed between the two operands) is defined by an operator.
100 + 50
Adding
The addition operator (+) adds numbers:
Example
let x = 5;
let y = 2;
let z = x + y;
Subtracting
The subtraction operator (-) subtracts numbers.
Example
let x = 5;
let y = 2;
let z = x - y;
Multiplying
The multiplication operator (*) multiplies numbers.
Example
let x = 5;
let y = 2;
let z = x * y;
Dividing
The division operator (/) divides numbers.
Example
let x = 5;
let y = 2;
let z = x / y;
Remainder
The modulus operator (%) returns the division remainder.
Example
let x = 5;
let y = 2;
let z = x % y;
Incrementing
The increment operator (++) increments numbers.
Example
let x = 5;
x++;
let z = x;
Decrementing
The decrement operator (--) decrements numbers.
Example
let x = 5;
x--;
let z = x;
Exponentiation
The exponentiation operator (**) raises the first operand to the power of the second operand.
Example
let x = 5;
let z = x ** 2; // result is 25
Example
let x = 5;
let z = Math.pow(x,2); // result is 25
Operator Precedence
Operator precedence describes the order in which operations are performed in an arithmetic
expression.
Example
let x = 100 + 50 * 3;
Is the result of example above the same as 150 * 3, or is it the same as 100 + 150?
Multiplication (*) and division (/) have higher precedence than addition (+) and subtraction (-).
And (as in school mathematics) the precedence can be changed by using parentheses:
Example
When using parentheses, the operations inside the parentheses are computed first.
When many operations have the same precedence (like addition and subtraction), they are
computed from left to right:
Example
let x = 100 + 50 - 3;
21 () Expression grouping (3 + 4)
20 . Member person.name
20 [] Member person["name"]
16 ** Exponentiation (ES2016) 10 ** 2
15 * Multiplication 10 * 5
15 / Division 10 / 5
15 % Division Remainder 10 % 5
14 + Addition 10 + 5
14 - Subtraction 10 - 5
11 == Equal x == y
11 != Unequal x != y
8 | Bitwise OR x|y
6 || Logical OR x || y
5 ?? Nullish Coalescing x ?? y
3 /= Assignment x /= y
3 -= Assignment x -= y
3 *= Assignment x *= y
3 %= Assignment x %= y
3 ^= Assignment x ^= y
3 |= Assignment x |= y
1 , Comma 5,6
Expressions in parentheses are fully computed before the value is used in the rest of the
expression.
JavaScript Assignment
Assignment Examples
The = assignment operator assigns a value to a variable.
Assignment
let x = 10;
Assignment
let x = 10;
x += 5;
Assignment
let x = 10;
x -= 5;
Assignment
let x = 10;
x *= 5;
Assignment
let x = 10;
x /= 5;
let x = 10;
x %= 5;
Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it produce a
result?
When adding a number and a string, JavaScript will treat the number as a string.
Example
let x = 16 + "Volvo";
Example
JavaScript evaluates expressions from left to right. Different sequences can produce different
results:
JavaScript:
let x = 16 + 4 + "Volvo";
Result:
20Volvo
JavaScript:
let x = "Volvo" + 16 + 4;
Result:
Volvo164
In the first example, JavaScript treats 16 and 4 as numbers, until it reaches "Volvo".
In the second example, since the first operand is a string, all operands are treated as strings.
Example
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:
Example
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
Example
JavaScript Numbers
JavaScript has only one type of numbers.
Example
Extra large or extra small numbers can be written with scientific (exponential) notation:
Example
JavaScript Booleans
Booleans can only have two values: true or false.
Example
let x = 5;
let y = 5;
let z = 6;
(x == y) // Returns true
(x == z) // Returns false
You will learn more about conditional testing later in this tutorial.
JavaScript Arrays
JavaScript arrays are written with square brackets.
The following code declares (creates) an array called cars, containing three items (car names):
Example
Array indexes are zero-based, which means the first item is [0], second is [1], and so on.
Example
The object (person) in the example above has 4 properties: firstName, lastName, age, and
eyeColor.
Example
Example
Undefined
In JavaScript, a variable without a value, has the value undefined. The type is also undefined.
Example
Any variable can be emptied, by setting the value to undefined. The type will also be
undefined.
Example
Empty Values
An empty value has nothing to do with undefined.
Example
Example
Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
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:
You will learn a lot more about function invocation later in this tutorial.
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":
Example
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
The result in x will be:
12
Why Functions?
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different results.
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
Accessing a function without () will return the function object instead of the function result.
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;
Example
You will learn a lot more about functions later in this tutorial.
Local Variables
Variables declared within a JavaScript function, become LOCAL to the function.
Example
function myFunction() {
let carName = "Volvo";
// code here CAN 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
A car has properties like weight and color, and methods like start and stop:
All cars have the same methods, but the methods are performed at different times.
JavaScript Objects
You have already learned that JavaScript variables are containers for data values.
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
The values are written as name:value pairs (name and value separated by a colon).
Object Definition
You define (and create) a JavaScript object with an object literal:
Example
Spaces and line breaks are not important. An object definition can span multiple lines:
Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Object Properties
The name:values pairs in JavaScript objects are called properties:
objectName.propertyName
or
objectName["propertyName"]
Example1
person.lastName;
Example2
person["lastName"];
Object Methods
Objects can also have methods.
Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
In the example above, this is the person object that "owns" the fullName function.
objectName.methodName()
Example
name = person.fullName();
If you access a method without the () parentheses, it will return the function definition:
Example
name = person.fullName;
Avoid String, Number, and Boolean objects. They complicate your code and slow down
execution speed.
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.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
In the following example, an onclick attribute (with code), is added to a <button> element:
Example
In the example above, the JavaScript code changes the content of the element with id="demo".
In the next example, the code changes the content of its own element (using this.innerHTML):
Example
JavaScript code is often several lines long. It is more common to see event attributes calling
functions:
Example
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: W3Schools JavaScript Reference HTML DOM Events.
Many different methods can be used to let JavaScript work with events:
You will learn a lot more about events and event handlers in the HTML DOM chapters.
JavaScript Strings
JavaScript Strings
A JavaScript string is zero or more characters written inside quotes.
Example
Example
let carName1 = "Volvo XC60"; // Double quotes
let carName2 = 'Volvo XC60'; // Single quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
Example
String Length
To find the length of a string, use the built-in length property:
Example
Escape Character
Because strings must be written within quotes, JavaScript will misunderstand this string:
let text = "We are the so-called "Vikings" from the north.";
The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string characters:
Example
let text = "We are the so-called \"Vikings\" from the north.";
Example
Example
Code Result
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tabulator
\v Vertical Tabulator
The 6 escape characters above were originally designed to control typewriters, teletypes, and fax
machines. They do not make any sense in HTML.
If a JavaScript statement does not fit on one line, the best place to break it is after an operator:
Example
document.getElementById("demo").innerHTML =
"Hello Dolly!";
You can also break up a code line within a text string with a single backslash:
Example
document.getElementById("demo").innerHTML = "Hello \
Dolly!";
The \ method is not the preferred method. It might not have universal support.
Some browsers do not allow spaces behind the \ character.
Example
Example
document.getElementById("demo").innerHTML = \
"Hello Dolly!";
But strings can also be defined as objects with the keyword new:
Example
let x = "John";
let y = new String("John");
Example
let x = "John";
let y = new String("John");
When using the === operator, equal values may not be equal, because the === operator expects
equality in both data type and value.
Example
let x = "John";
let y = new String("John");
// (x === y) is false because x and y have different types (string and object)
Example
Example
But with JavaScript, methods and properties are also available to primitive values, because
JavaScript treats primitive values as objects when executing methods and properties.
String Length
The length property returns the length of a string:
Example
let txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
txt.length // Returns 26
• slice(start, end)
• substring(start, end)
• substr(start, length)
The method takes 2 parameters: the start position, and the end position (end not included).
This example slices out a portion of a string from position 7 to position 12 (13-1):
Example
If a parameter is negative, the position is counted from the end of the string.
This example slices out a portion of a string from position -12 to position -6:
Example
If you omit the second parameter, the method will slice out the rest of the string:
Example
Example
If you omit the second parameter, substring() will slice out the rest of the string.
The difference is that the second parameter specifies the length of the extracted part.
Example
Banana
If you omit the second parameter, substr() will slice out the rest of the string.
Example
If the first parameter is negative, the position counts from the end of the string.
Example
Example
The replace() method does not change the string it is called on. It returns a new string.
Example
By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-case)
will not work:
Example
Example
To replace all matches, use a regular expression with a /g flag (global match):
Example
let text = "Please visit Microsoft and Microsoft!";
let newText = text.replace(/Microsoft/g, "W3Schools");
You will learn a lot more about regular expressions in the chapter JavaScript Regular
Expressions.
Example
Example
Example
The concat() method can be used instead of the plus operator. These two lines do the same:
Example
All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.
String.trim()
The trim() method removes whitespace from both sides of a string:
Example
Example
Example
Firefox and Safari were the first browsers with support for JavaScript string padding:
• charAt(position)
• charCodeAt(position)
• Property access [ ]
Example
The method returns a UTF-16 code (an integer between 0 and 65535).
Example
text.charCodeAt(0) // Returns 72
Property Access
ECMAScript 5 (2009) allows property access [ ] on strings:
Example
Example
let text = "HELLO WORLD";
text[0] = "A" // Gives no error, but does not work
text[0] // returns H
If you want to work with a string as an array, you can convert it to an array.
Example
If the separator is omitted, the returned array will contain the whole string in index [0].
If the separator is "", the returned array will be an array of single characters:
Example
The reference contains descriptions and examples of all string properties and methods.
But with JavaScript, methods and properties are also available to primitive values, because
JavaScript treats primitive values as objects when executing methods and properties.
String Length
The length property returns the length of a string:
Example
• slice(start, end)
• substring(start, end)
• substr(start, length)
The method takes 2 parameters: the start position, and the end position (end not included).
This example slices out a portion of a string from position 7 to position 12 (13-1):
Example
If a parameter is negative, the position is counted from the end of the string.
This example slices out a portion of a string from position -12 to position -6:
Example
If you omit the second parameter, the method will slice out the rest of the string:
Example
Example
Example
let str = "Apple, Banana, Kiwi";
substring(7, 13) // Returns Banana
If you omit the second parameter, substring() will slice out the rest of the string.
The difference is that the second parameter specifies the length of the extracted part.
Example
Banana
If you omit the second parameter, substr() will slice out the rest of the string.
Example
If the first parameter is negative, the position counts from the end of the string.
Example
Example
Example
By default, the replace() method is case sensitive. Writing MICROSOFT (with upper-case)
will not work:
Example
Example
To replace all matches, use a regular expression with a /g flag (global match):
Example
You will learn a lot more about regular expressions in the chapter JavaScript Regular
Expressions.
Example
let text1 = "Hello World!"; // String
let text2 = text1.toUpperCase(); // text2 is text1 converted to upper
Example
Example
The concat() method can be used instead of the plus operator. These two lines do the same:
Example
All string methods return a new string. They don't modify the original string.
Formally said: Strings are immutable: Strings cannot be changed, only replaced.
String.trim()
The trim() method removes whitespace from both sides of a string:
Example
Example
Example
Firefox and Safari were the first browsers with support for JavaScript string padding:
• charAt(position)
• charCodeAt(position)
• Property access [ ]
Example
The method returns a UTF-16 code (an integer between 0 and 65535).
Example
text.charCodeAt(0) // Returns 72
Property Access
ECMAScript 5 (2009) allows property access [ ] on strings:
Example
Example
If you want to work with a string as an array, you can convert it to an array.
Example
text.split(",") // Split on commas
text.split(" ") // Split on spaces
text.split("|") // Split on pipe
If the separator is omitted, the returned array will contain the whole string in index [0].
If the separator is "", the returned array will be an array of single characters:
Example
The reference contains descriptions and examples of all string properties and methods.
• String.indexOf()
• String.lastindexOf()
• String.startsWith()
• String.endsWithf()
String.indexOf()
The indexOf() method returns the index of (the position of) the first occurrence of a specified
text in a string:
Example
String.lastIndexOf()
The lastIndexOf() method returns the index of the last occurrence of a specified text in a
string:
Example
Example
Both methods accept a second parameter as the starting position for the search:
Example
The lastIndexOf() methods searches backwards (from the end to the beginning), meaning: if
the second parameter is 15, the search starts at position 15, and searches to the beginning of the
string.
Example
String.search()
The search() method searches a string for a specified value and returns the position of the
match:
Example
They accept the same arguments (parameters), and return the same value?
The two methods are NOT equal. These are the differences:
String.startsWith()
The startsWith() method returns true if a string begins with a specified value, otherwise
false:
Example
Parameter Values
Parameter Description
searchvalue Required. The value to search for.
start Optional. Default 0. The position to start the search.
Examples
String.endsWith()
The endsWith() method returns true if a string ends with a specified value, otherwise false:
Example
Parameter Values
Parameter Description
searchvalue Required. The value to search for.
length Optional. The length to search.
JavaScript has only one type of number. Numbers can be written with or without decimals.
Example
Extra large or extra small numbers can be written with scientific (exponent) notation:
Example
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:
Precision
Integers (numbers without a period or exponent notation) are accurate up to 15 digits.
Example
The maximum number of decimals is 17, but floating point arithmetic is not always 100%
accurate:
Example
Example
Example
let x = 10;
let y = 20;
let z = x + y; // z will be 30 (a number)
Example
let x = "10";
let y = "20";
let z = x + y; // z will be 1020 (a string)
If you add a number and a string, the result will be a string concatenation:
Example
let x = 10;
let y = "20";
let z = x + y; // z will be 1020 (a string)
If you add a string and a number, the result will be a string concatenation:
Example
let x = "10";
let y = 20;
let z = x + y; // z will be 1020 (a string)
Example
let x = 10;
let y = 20;
let z = "The result is: " + x + y;
Example
let x = 10;
let y = 20;
let z = "30";
let result = x + y + z;
let x = "100";
let y = "10";
let z = x / y; // z will be 10
let x = "100";
let y = "10";
let z = x * y; // z will be 1000
let x = "100";
let y = "10";
let z = x - y; // z will be 90
let x = "100";
let y = "10";
let z = x + y; // z will not be 110 (It will be 10010)
In the last example JavaScript uses the + operator to concatenate the strings.
Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number):
Example
However, if the string contains a numeric value , the result will be a number:
Example
You can use the global JavaScript function isNaN() to find out if a value is a number:
Example
Watch out for NaN. If you use NaN in a mathematical operation, the result will also be NaN:
Example
let x = NaN;
let y = 5;
let z = x + y; // z will be NaN
Example
let x = NaN;
let y = "5";
let z = x + y; // z will be NaN5
Example
Infinity
Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside
the largest possible number.
Example
let myNumber = 2;
while (myNumber != Infinity) { // Execute until Infinity
myNumber = myNumber * myNumber;
}
Example
Example
Hexadecimal
JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x.
Example
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.
Example
let myNumber = 32;
myNumber.toString(10); // returns 32
myNumber.toString(32); // returns 10
myNumber.toString(16); // returns 20
myNumber.toString(8); // returns 40
myNumber.toString(2); // returns 100000
let x = 123;
But numbers can also be defined as objects with the keyword new:
Example
let x = 123;
let y = new Number(123);
Example
let x = 500;
let y = new Number(500);
When using the === operator, equal numbers are not equal, because the === operator expects
equality in both type and value.
Example
let x = 500;
let y = new Number(500);
Example
But with JavaScript, methods and properties are also available to primitive values, because
JavaScript treats primitive values as objects when executing methods and properties.
All number methods can be used on any type of numbers (literals, variables, or expressions):
Example
let x = 123;
x.toString(); // returns 123 from variable x
(123).toString(); // returns 123 from literal 123
(100 + 23).toString(); // returns 123 from expression 100 + 23
Example
let x = 9.656;
x.toExponential(2); // returns 9.66e+0
x.toExponential(4); // returns 9.6560e+0
x.toExponential(6); // returns 9.656000e+0
The parameter is optional. If you don't specify it, JavaScript will not round the number.
Example
let x = 9.656;
x.toFixed(0); // returns 10
x.toFixed(2); // returns 9.66
x.toFixed(4); // returns 9.6560
x.toFixed(6); // returns 9.656000
Example
let x = 9.656;
x.toPrecision(); // returns 9.656
x.toPrecision(2); // returns 9.7
x.toPrecision(4); // returns 9.656
x.toPrecision(6); // returns 9.65600
Example
let x = 123;
x.valueOf(); // returns 123 from variable x
(123).valueOf(); // returns 123 from literal 123
(100 + 23).valueOf(); // returns 123 from expression 100 + 23
The valueOf() method is used internally in JavaScript to convert Number objects to primitive
values.
These methods are not number methods, but global JavaScript methods.
These are the most relevant methods, when working with numbers:
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 an integer
Number(true); // returns 1
Number(false); // returns 0
Number("10"); // returns 10
Number(" 10"); // returns 10
Number("10 "); // returns 10
Number(" 10 "); // returns 10
Number("10.33"); // returns 10.33
Number("10,33"); // returns NaN
Number("10 33"); // returns NaN
Number("John"); // returns NaN
Example
The Number() method above returns the number of milliseconds since 1.1.1970.
Example
Example
parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("10 20 30"); // returns 10
parseFloat("10 years"); // returns 10
parseFloat("years 10"); // returns NaN
Number Properties
Property Description
MAX_VALUE Returns the largest number possible in JavaScript
MIN_VALUE Returns the smallest number possible in JavaScript
POSITIVE_INFINITY Represents infinity (returned on overflow)
NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
NaN Represents a "Not-a-Number" value
Example
let x = Number.MAX_VALUE;
Example
let x = Number.MIN_VALUE;
JavaScript POSITIVE_INFINITY
Example
let x = Number.POSITIVE_INFINITY;
Example
let x = 1 / 0;
JavaScript NEGATIVE_INFINITY
Example
let x = Number.NEGATIVE_INFINITY;
Example
let x = -1 / 0;
let x = Number.NaN;
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):
Example
Example
let x = 6;
x.MAX_VALUE // returns undefined
The reference contains descriptions and examples of all Number properties and methods.
JavaScript Arrays
Example
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
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:
Example
Spaces and line breaks are not important. A declaration can span multiple lines:
Example
const cars = [
"Saab",
"Volvo",
"BMW"
];
You can also create an array, and then provide the elements:
Example
cars[0] = "Opel";
Example
Example
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
Arrays use numbers to access its "elements". In this example, person[0] returns John:
Array:
Objects use names to access its "members". In this example, person.firstName returns John:
Object:
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:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
Example
The length property is always one more than the highest array index.
Example
text = "<ul>";
for (let i = 0; i < fLen; i++) {
text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";
Example
function myFunction(value) {
text += "<li>" + value + "</li>";
}
Example
New element can also be added to an array using the length property:
Example
WARNING !
Adding elements with high indexes can create undefined "holes" in an array:
Example
Arrays with named indexes are called associative arrays (or hashes).
Example
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.
Example:
Use [] instead.
These two different statements both create a new empty array named points:
These two different statements both create a new array containing 6 numbers:
The new keyword only complicates the code. It can also produce some unexpected results:
Solution 2:
let x = ;
Example
Banana,Orange,Apple,Mango
The join() method also joins all array elements into a string.
It behaves just like toString(), but in addition you can specify the separator:
Example
Result:
Popping
The pop() method removes the last element from an array:
Example
The pop() method returns the value that was "popped out":
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let x = fruits.pop(); // x = "Mango"
Pushing
The push() method adds a new element to an array (at the end):
Example
Example
Shifting Elements
Shifting is equivalent to popping, 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.
Example
The shift() method returns the value that was "shifted out":
Example
The unshift() method adds a new element to an array (at the beginning), and "unshifts" older
elements:
Example
Example
Changing Elements
Array elements are accessed using their index number:
Example
The length property provides an easy way to append a new element to an array:
Example
Deleting Elements
Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator
delete:
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0]; // Changes the first element in fruits to undefined
Using delete may leave undefined holes in the array. Use pop() or shift() instead.
Splicing an Array
The splice() method can be used to add new items to an array:
Example
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.
Example
Example
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.
The concat() method does not change the existing arrays. It always returns a new array.
Slicing an Array
The slice() method slices out a piece of an array into a new array.
This example slices out a part of an array starting from array element 1 ("Orange"):
Example
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1);
The slice() method creates a new array. It does not remove any elements from the source
array.
This example slices out a part of an array starting from array element 3 ("Apple"):
Example
The slice() 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.
Example
If the end argument is omitted, like in the first examples, the slice() method slices out the rest
of the array.
Example
Automatic toString()
JavaScript automatically converts an array to a comma separated string when a primitive value is
expected.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Example
You will learn how you solve this problem in the next chapter of this tutorial.
Sorting Arrays
Sorting arrays are covered in the next chapter of this tutorial.
The reference contains descriptions and examples of all Array properties and methods.
;
Start the Exercise
Sorting an Array
The sort() method sorts an array alphabetically:
Example
Reversing an Array
The reverse() method reverses the elements in an array.
Example
Numeric Sort
By default, the sort() function sorts values as strings.
However, 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.
Example
Example
The compare function should return a negative, zero, or positive value, depending on the
arguments:
function(a, b){return a - b}
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 0 no changes are done with the sort order of the two values.
Example:
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.
You can use this code snippet to experiment with numerically and alphabetically sorting:
<p id="demo"></p>
<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
function myFunction1() {
points.sort();
document.getElementById("demo").innerHTML = points;
}
function myFunction2() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>
The most popular correct method, is called the Fisher Yates shuffle, and was introduced in data
science as early as 1938!
In JavaScript the method can be translated to this:
Example
However, after you have sorted an array, you can use the index to obtain the highest and lowest
values.
Sorting ascending:
Example
Sorting descending:
Example
Sorting a whole array is a very inefficient method if you only want to find the highest (or lowest)
value.
Using Math.max() on an Array
You can use Math.max.apply to find the highest number in an array:
Example
function myArrayMax(arr) {
return Math.max.apply(null, arr);
}
Example
function myArrayMin(arr) {
return Math.min.apply(null, arr);
}
This function loops through an array comparing each value with the highest value found:
function myArrayMax(arr) {
let len = arr.length;
let max = -Infinity;
while (len--) {
if (arr[len] > max) {
max = arr[len];
}
}
return max;
}
This function loops through an array comparing each value with the lowest value found:
function myArrayMin(arr) {
let len = arr.length;
let min = Infinity;
while (len--) {
if (arr[len] < min) {
min = arr[len];
}
}
return min;
}
Example
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.
Example
cars.sort(function(a, b){
let x = a.type.toLowerCase();
let y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});
Array.forEach()
The forEach() method calls a function (a callback function) once for each array element.
Example
The example above uses only the value parameter. The example can be rewritten to:
Example
function myFunction(value) {
txt += value + "<br>";
}
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.
Example
When a callback function uses only the value parameter, the index and array parameters can be
omitted:
Example
function myFunction(value) {
return value * 2;
}
Array.filter()
The filter() method creates a new array with array elements that passes a test.
This example creates a new array from elements with a value larger than 18:
Example
In the example above, the callback function does not use the index and array parameters, so they
can be omitted:
Example
function myFunction(value) {
return value > 18;
}
Array.reduce()
The reduce() method runs a function on each array element to produce (reduce it to) a single
value.
The reduce() method works from left-to-right in the array. See also reduceRight().
Example
The example above does not use the index and array parameters. It can be rewritten to:
Example
Example
Array.reduceRight()
The reduceRight() method runs a function on each array element to produce (reduce it to) a
single value.
The reduceRight() works from right-to-left in the array. See also reduce().
Example
Example
Array.every()
The every() method check if all array values pass a test.
This example check if all array values are larger than 18:
Example
When a callback function uses the first parameter only (value), the other parameters can be
omitted:
Example
function myFunction(value) {
return value > 18;
}
Array.some()
The some() method check if some array values pass a test.
This example check if some array values are larger than 18:
Example
Array.indexOf()
The indexOf() method searches an array for an element value and returns its position.
Note: The first item has position 0, the second item has position 1, and so on.
Example
Syntax
array.indexOf(item, start)
item Required. The item to search for.
Optional. Where to start the search. Negative values will start at the given position counting from
start
the end, and search to the end.
If the item is present more than once, it returns the position of the first occurrence.
Array.lastIndexOf()
Array.lastIndexOf() is the same as Array.indexOf(), but returns the position of the last
occurrence of the specified element.
Example
Syntax
array.lastIndexOf(item, start)
Optional. Where to start the search. Negative values will start at the given position counting from
start
the end, and search to the beginning
Array.includes()
ECMAScript 2016 introduced Array.includes() to arrays. This allows us to check if an
element is present in an array (including NaN, unlike indexOf).
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Mango"); // is true
Syntax
array.includes(search-item)
Des 2015 Aug 2016 Des 2015 Oct 2015 Des 2015
Array.find()
The find() method returns the value of the first array element that passes a test function.
This example finds (returns the value of) the first element that is larger than 18:
Example
Sep 2015 Aug 2015 Oct 2013 Oct 2014 Sep 2015
Array.findIndex()
The findIndex() method returns the index of the first array element that passes a test function.
This example finds the index of the first element that is larger than 18:
Example
Array.findIndex() is not supported in older browsers. The first browser versions with full
support are:
Sep 2015 Aug 2015 Oct 2013 Oct 2014 Sep 2015
JavaScript Array Const
Example
Cannot be Reassigned
An array declared with const cannot be reassigned:
Example
Example
// You can create a constant array:
const cars = ["Saab", "Volvo", "BMW"];
Browser Support
The const keyword is not supported in Internet Explorer 10 or earlier.
The following table defines the first browser versions with full support for the const keyword:
Mar, 2016 Oct, 2013 Feb, 2015 Sep, 2016 Mar, 2016
If you expect that any of your users runs Internet Explorer 10 or earlier, you should avoid using
const.
It will produce a syntax error, and the code will not run.
Example
Example
This is OK:
An array declared in a block is not the same as an array declared outside the block:
Example
Example
Redeclaring Arrays
Redeclaring an array declared with var is allowed anywhere in a program:
Example
Redeclaring or reassigning an array to const, in the same scope, or in the same block, is not
allowed:
Example
Redeclaring or reassigning an existing const array, in the same scope, or in the same block, is
not allowed:
Example
{
const cars = ["Volvo", "BMW"]; // Allowed
const cars = ["Volvo", "BMW"]; // Not allowed
var cars = ["Volvo", "BMW"]; // Not allowed
cars = ["Volvo", "BMW"]; // Not allowed
}
Example
Example
You will learn much more about how to display dates, later in this tutorial.
Creating Date Objects
Date objects are created with the new Date() constructor.
new Date()
new Date(year, month, day, hours, minutes, seconds, milliseconds)
new Date(milliseconds)
new Date(date string)
new Date()
new Date() creates a new date object with the current date and time:
Example
Date objects are static. The computer time is ticking, but date objects are not.
7 numbers specify year, month, day, hour, minute, second, and millisecond (in that order):
Example
Example
Example
Example
Example
Example
You cannot omit month. If you supply only one parameter it will be treated as milliseconds.
Example
Previous Century
One and two digit years will be interpreted as 19xx:
Example
Example
Example
Now the time is: 1624599369876 milliseconds past January 01, 1970
new Date(milliseconds)
new Date(milliseconds) creates a new date object as zero time plus milliseconds:
Example
01 January 1970 plus 100 000 000 000 milliseconds is approximately 03 March 1973:
Example
January 01 1970 minus 100 000 000 000 milliseconds is approximately October 31 1966:
Example
const d = new Date(-100000000000);
Example
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 in the next chapters.
Displaying Dates
JavaScript will (by default) output dates in full text string format:
When you display a date object in HTML, it is automatically converted to a string, with the
toString() method.
Example
Same as:
The toUTCString() method converts a date to a UTC string (a date display standard).
Example
Example
The toISOString() method converts a date to a string, using the ISO standard format:
Example
Type Example
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:
The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date format:
Example
Time zones will vary the result above between February 28 and March 01.
Example
Example
If you want to modify the time relative to UTC, remove the Z and add +HH:MM or -HH:MM
instead:
Example
UTC (Universal Time Coordinated) is the same as GMT (Greenwich Mean Time).
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.
Example
WARNINGS !
In some browsers, months or days with no leading zeroes may produce an error:
Example
Example
Example
const d = new Date("January 25 2015");
Example
Example
Date.parse() returns the number of milliseconds between the date and January 1, 1970:
Example
You can then use the number of milliseconds to convert it to a date object:
Example
These methods can be used for getting information from a date object:
Method Description
Example
Example
Example
In JavaScript, the first month (January) is month number 0, so December returns month number
11.
You can use an array of names, and getMonth() to return the month as a name:
Example
Example
Example
const d = new Date();
document.getElementById("demo").innerHTML = d.getHours();
Example
Example
Example
Example
const d = new Date();
document.getElementById("demo").innerHTML = d.getDay();
In JavaScript, the first day of the week (0) means "Sunday", even if some countries in the world
consider the first day of the week to be "Monday"
You can use an array of names, and getDay() to return the weekday as a name:
Example
Method Description
month = ;
Set Date methods let you set date values (years, months, days, hours, minutes, seconds,
milliseconds) for a Date Object.
Method Description
Example
Example
Example
Example
If adding days shifts the month or year, the changes are handled automatically by the Date
object.
Example
Example
Compare Dates
Dates can easily be compared.
The following example compares today's date with January 14, 2100:
Example
The reference contains descriptions and examples of all Date properties and methods.
d. ;
Example
All methods and properties can be used without creating a Math object first.
Example
Math Methods
The syntax for Math any methods is : Math.method.(number)
Number to Integer
There are 4 common methods to round a number to an integer:
Math.round()
Math.round(x) returns the nearest integer:
Example
Math.round(4.9); // returns 5
Math.round(4.7); // returns 5
Math.round(4.4); // returns 4
Math.round(4.2); // returns 4
Math.round(-4.2); // returns -4
Math.ceil()
Math.ceil(x) returns the value of x rounded up to its nearest integer:
Example
Math.ceil(4.9); // returns 5
Math.ceil(4.7); // returns 5
Math.ceil(4.4); // returns 5
Math.ceil(4.2); // returns 5
Math.ceil(-4.2); // returns -4
Math.floor()
Math.floor(x) returns the value of x rounded down to its nearest integer:
Example
Math.floor(4.9); // returns 4
Math.floor(4.7); // returns 4
Math.floor(4.4); // returns 4
Math.floor(4.2); // returns 4
Math.floor(-4.2); // returns -5
Math.trunc()
Math.trunc(x) returns the integer part of x:
Example
Math.trunc(4.9); // returns 4
Math.trunc(4.7); // returns 4
Math.trunc(4.4); // returns 4
Math.trunc(4.2); // returns 4
Math.trunc(-4.2); // returns -4
Math.sign()
Math.sign(x) returns if x is negative, null or positive:
Example
Math.sign(-4); // returns -1
Math.sign(0); // returns 0
Math.sign(4); // returns 1
Math.pow()
Math.pow(x, y) returns the value of x to the power of y:
Example
Math.sqrt()
Math.sqrt(x) returns the square root of x:
Example
Math.sqrt(64); // returns 8
Math.abs()
Math.abs(x) returns the absolute (positive) value of x:
Example
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:
Example
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:
Example
Example
Example
Math.random()
Math.random() returns a random number between 0 (inclusive), and 1 (exclusive):
Example
You will learn more about Math.random() in the next chapter of this tutorial.
Example
Math.log(1); // returns 0
The natural logarithm returns the time needed to reach a certain level of growth.
Example
Example
Math.log2(8); // returns 3
Example
Math.log10(1000); // returns 3
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
The reference contains descriptions and examples of all Math properties and methods.
let r = ;
Math.random()
Math.random() returns a random number between 0 (inclusive), and 1 (exclusive):
Example
Example
Example
Example
Example
// Returns a random integer from 0 to 100:
Math.floor(Math.random() * 101);
Example
Example
This JavaScript function always returns a random number between min (included) and max
(excluded):
Example
This JavaScript function always returns a random number between min and max (both included):
Example
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.
Example
Or even easier:
Example
The Boolean value of an expression is the basis for all JavaScript comparisons and conditions.
100
3.14
-15
"Hello"
"false"
7 + 1 + 3.14
let x = 0;
Boolean(x); // returns false
let x = -0;
Boolean(x); // returns false
let x = "";
Boolean(x); // returns false
The Boolean value of undefined is false:
let x;
Boolean(x); // returns false
let x = null;
Boolean(x); // returns false
let x = false;
Boolean(x); // returns false
let x = 10 / "Hallo";
Boolean(x); // returns false
let x = false;
But booleans can also be defined as objects with the keyword new:
Example
let x = false;
let y = new Boolean(false);
Example
let x = false;
let y = new Boolean(false);
When using the === operator, equal booleans are not equal, because the === operator expects
equality in both type and value.
Example
let x = false;
let y = new Boolean(false);
Example
The reference contains descriptions and examples of all Boolean properties and methods.
Comparison Operators
Comparison operators are used in logical statements to determine equality or difference between
variables or values.
== equal to x == 8 false
x == 5 true
x == "5" true
x === 5 true
=== equal value and equal type
x === "5" false
x !== 5 false
!== not equal value or not equal type x !== "5" true
x !== 8 true
You will learn more about the use of conditional statements in the next chapter of this tutorial.
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:
(x
== 5
|| y
|| or
==
5) is
false
!(x
==
! not
y) is
true
Syntax
Example
let voteable = (age < 18) ? "Too young":"Old enough";
If the variable age is a value below 18, the value of the variable voteable will be "Too young",
otherwise the value of voteable will be "Old enough".
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.
2 < 12 true
2 == "John" 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:
age = Number(age);
if (isNaN(age)) {
voteable = "Input is not a number";
} else {
voteable = (age < 18) ? "Too young" : "Old enough";
}
x = 10;
y = 5;
alert(x y);
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.
The if Statement
Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.
Example
Good day
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
}
Example
If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening":
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
}
Example
If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00,
create a "Good day" greeting, otherwise a "Good evening":
More Examples
Random link
This example will write a link to either W3Schools or to the World Wildlife Foundation (WWF).
By using a random number, there is a 50% chance for each of the links.
if x > y
alert("Hello World");
The switch statement is used to perform different actions based on different conditions.
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Example
The getDay() method returns the weekday as a number between 0 and 6.
This example uses the weekday number to calculate the weekday name:
Friday
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, the next case will be executed even if the evaluation does
not match the case.
The default Keyword
The default keyword specifies the code to run if there is no case match:
Example
If today is neither Saturday (6) nor Sunday (0), write a default message:
The default case does not have to be the last case in a switch block:
Example
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:
Example
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 (===).
A strict comparison can only be true if the operands are of the same type.
Example
let x = "0";
switch (x) {
case 0:
text = "Off";
break;
case 1:
text = "On";
break;
default:
text = "No value found";
}
(fruits) {
"Banana":
alert("Hello")
break;
"Apple":
alert("Welcome")
break;
}
JavaScript Loops
Loops are handy, if you want to run the same code over and over again, each time with a
different value.
Instead of writing:
Statement 1 is executed (one time) before the execution of the code block.
Example
Statement 2 defines the condition for the loop to run (i must be less than 5).
Statement 3 increases a value (i++) each time the code block in the loop has been executed.
Statement 1
Normally you will use statement 1 to initialize the variable used in the loop (let i = 0).
This is not always the case, JavaScript doesn't care. Statement 1 is optional.
Example
And you can omit statement 1 (like when your values are set before the loop starts):
Example
let i = 2;
let len = cars.length;
let text = "";
for (; i < len; i++) {
text += cars[i] + "<br>";
}
Statement 2
Often statement 2 is used to evaluate the condition of the initial variable.
This is not always the case, JavaScript doesn't care. Statement 2 is also optional.
If statement 2 returns true, the loop will start over again, if it returns false, the loop will end.
If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will never
end. This will crash your browser. Read about breaks in a later chapter of this tutorial.
Statement 3
Often statement 3 increments the value of the initial variable.
This is not always the case, JavaScript doesn't care, and statement 3 is optional.
Statement 3 can do anything like negative increment (i--), positive increment (i = i + 15), or
anything else.
Statement 3 can also be omitted (like when you increment your values inside the loop):
Example
let i = 0;
let len = cars.length;
let text = "";
for (; i < len; ) {
text += cars[i] + "<br>";
i++;
}
Loop Scope
Using var in a loop:
Example
var i = 5;
Example
let i = 5;
// 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.
While Loops
The while loop and the do/while are explained in the next chapters.
( = ; < ; ) {
console.log(i);
}
JavaScript For In
Syntax
Example
Example Explained
• 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]
Syntax
Example
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.
Example
The example above uses only the value parameter. It can be rewritten to:
Example
function myFunction(value) {
txt += value;
}
JavaScript For Of
It lets you loop over iterable data structures such as Arrays, Strings, Maps, NodeLists, and more:
Syntax
variable - For every iteration the value of the next property is assigned to the variable. Variable
can be declared with const, let, or var.
Browser Support
For/of was added to JavaScript in 2015 (ES6)
Safari 7 was the first browser to support for of:
Oct 2014 Jul 2015 Oct 2016 Oct 2013 Oct 2014
Syntax
while (condition) {
// code block to be executed
}
Example
In the following example, the code in the loop will run, over and over again, as long as a variable
(i) is less than 10:
Example
If you forget to increase the variable used in the condition, the loop will never end. This will
crash your browser.
Syntax
do {
// code block to be executed
}
while (condition);
Example
The example below uses a do while loop. 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:
Example
do {
text += "The number is " + i;
i++;
}
while (i < 10);
Do not forget to increase the variable used in the condition, otherwise the loop will never end!
The loop in this example uses a for loop to collect the car names from the cars array:
Example
for (;cars[i];) {
text += cars[i];
i++;
}
The loop in this example uses a while loop to collect the car names from the cars array:
Example
while (cars[i]) {
text += cars[i];
i++;
}
let i = 0;
(i 10) {
console.log(i);
i++
}
Example
In the example above, the break statement ends the loop ("breaks" the loop) when the loop
counter (i) is 3.
Example
JavaScript Labels
To label JavaScript statements you precede the statements with a label name and a colon:
label:
statements
The break and the continue statements are the only JavaScript statements that can "jump out
of" a code block.
Syntax:
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:
Example
;
}
}
JavaScript typeof
In JavaScript there are 5 different data types that can contain values:
• string
• number
• boolean
• object
• function
• Object
• Date
• Array
• String
• Number
• Boolean
• null
• undefined
Please observe:
You cannot use typeof to determine if a JavaScript object is an array (or a date).
Primitive Data
A primitive data value is a single simple data value with no additional properties and methods.
• string
• number
• boolean
• undefined
Example
Complex Data
The typeof operator can return one of two complex types:
• function
• object
The typeof operator returns "object" for objects, arrays, and null.
Example
The typeof operator returns "object" for arrays because in JavaScript arrays are objects.
But, the typeof operator always returns a string (containing the type of the operand).
Example
"John".constructor // Returns function String() {[native code]}
(3.14).constructor // Returns function Number() {[native code]}
false.constructor // Returns function Boolean() {[native code]}
[1,2,3,4].constructor // Returns function Array() {[native code]}
{name:'John',age:34}.constructor // Returns function Object() {[native code]}
new Date().constructor // Returns function Date() {[native code]}
function () {}.constructor // Returns function Function(){[native code]}
You can check the constructor property to find out if an object is an Array (contains the word
"Array"):
Example
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
Example
function isArray(myArray) {
return myArray.constructor === Array;
}
You can check the constructor property to find out if an object is a Date (contains the word
"Date"):
Example
function isDate(myDate) {
return myDate.constructor.toString().indexOf("Date") > -1;
}
Example
function isDate(myDate) {
return myDate.constructor === Date;
}
Undefined
In JavaScript, a variable without a value, has the value undefined. The type is also undefined.
Example
Any variable can be emptied, by setting the value to undefined. The type will also be
undefined.
Example
Empty Values
An empty value has nothing to do with undefined.
Example
Null
In JavaScript null is "nothing". It is supposed to be something that doesn't exist.
You can consider it a bug in JavaScript that typeof null is an object. It should be null.
Example
Example
JavaScript typeof
In JavaScript there are 5 different data types that can contain values:
• string
• number
• boolean
• object
• function
• Object
• Date
• Array
• String
• Number
• Boolean
• null
• undefined
Example
Please observe:
You cannot use typeof to determine if a JavaScript object is an array (or a date).
Primitive Data
A primitive data value is a single simple data value with no additional properties and methods.
• string
• number
• boolean
• undefined
Example
Complex Data
The typeof operator can return one of two complex types:
• function
• object
The typeof operator returns "object" for objects, arrays, and null.
Example
The typeof operator returns "object" for arrays because in JavaScript arrays are objects.
But, the typeof operator always returns a string (containing the type of the operand).
The constructor Property
The constructor property returns the constructor function for all JavaScript variables.
Example
You can check the constructor property to find out if an object is an Array (contains the word
"Array"):
Example
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
Example
function isArray(myArray) {
return myArray.constructor === Array;
}
You can check the constructor property to find out if an object is a Date (contains the word
"Date"):
Example
function isDate(myDate) {
return myDate.constructor.toString().indexOf("Date") > -1;
}
Example
function isDate(myDate) {
return myDate.constructor === Date;
}
Undefined
In JavaScript, a variable without a value, has the value undefined. The type is also undefined.
Example
Any variable can be emptied, by setting the value to undefined. The type will also be
undefined.
Example
Empty Values
An empty value has nothing to do with undefined.
Example
Null
In JavaScript null is "nothing". It is supposed to be something that doesn't exist.
You can consider it a bug in JavaScript that typeof null is an object. It should be null.
Example
Number Methods
In the chapter Number Methods, you will find more methods that can be used to convert strings
to numbers:
Method Description
Number() Returns a number, converted from its argument
parseFloat() Parses a string and returns a floating point number
parseInt() Parses a string and returns an integer
Example
If the variable cannot be converted, it will still become a number, but with the value NaN (Not a
Number):
Example
Example
Example
x.toString()
(123).toString()
(100 + 23).toString()
More Methods
In the chapter Number Methods, you will find more methods that can be used to convert
numbers to strings:
Method Description
Returns a string, with a number rounded and written using exponential
toExponential()
notation.
Returns a string, with a number rounded and written with a specified
toFixed()
number of decimals.
toPrecision() Returns a string, with a number written with a specified length
d = new Date();
Number(d) // returns 1404568027739
The date method getTime() does the same.
d = new Date();
d.getTime() // returns 1404568027739
String(Date()) // returns "Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)"
Example
Date().toString() // returns "Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time)"
In the chapter Date Methods, you will find more methods that can be used to convert dates to
strings:
Method Description
getDate() Get the day as a number (1-31)
getDay() Get the weekday a number (0-6)
getFullYear() Get the four digit year (yyyy)
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
getTime() Get the time (milliseconds since January 1, 1970)
Number(false) // returns 0
Number(true) // returns 1
document.getElementById("demo").innerHTML = myVar;
Numbers and booleans are also converted, but this is not very visible:
Signed right Shifts right by pushing copies of the leftmost bit in from the left, and let the
>>
shift rightmost bits fall off
Examples
Operation Result Same as Result
~5 10 ~0101 1010
Before a bitwise operation is performed, JavaScript converts numbers to 32 bits signed integers.
After the bitwise operation is performed, the result is converted back to 64 bits JavaScript
numbers.
The examples above uses 4 bits unsigned binary numbers. Because of this ~ 5 returns 10.
Since JavaScript uses 32 bits signed integers, it will not return 10. It will return -6.
00000000000000000000000000000101 (5)
Bitwise AND
When a bitwise AND is performed on a pair of bits, it returns 1 if both bits are 1.
Operation Result
0&0 0
0&1 0
1&0 0
1&1 1
4 bits example:
Operation Result
Bitwise OR
When a bitwise OR is performed on a pair of bits, it returns 1 if one of the bits are 1:
Operation Result
0|0 0
0|1 1
1|0 1
1|1 1
4 bits example:
Operation Result
Bitwise XOR
When a bitwise XOR is performed on a pair of bits, it returns 1 if the bits are different:
0^0 0
0^1 1
1^0 1
1^1 0
4 bits example:
Operation Result
Decimal Binary
5 00000000000000000000000000000101
1 00000000000000000000000000000001
Example
let x = 5 & 1;
Decimal Binary
5 00000000000000000000000000000101
1 00000000000000000000000000000001
Example
let x = 5 | 1;
Decimal Binary
5 00000000000000000000000000000101
1 00000000000000000000000000000001
Example
let x = 5 ^ 1;
5 00000000000000000000000000000101
~5 11111111111111111111111111111010 (-6)
Example
let x = ~5;
Decimal Binary
5 00000000000000000000000000000101
Example
let x = 5 << 1;
Decimal Binary
-5 11111111111111111111111111111011
Example
let x = -5 >> 1;
Decimal Binary
5 00000000000000000000000000000101
Example
let x = 5 >>> 1;
Binary Numbers
Binary numbers with only one bit set is easy to understand:
00000000000000000000000000000001 1
00000000000000000000000000000010 2
00000000000000000000000000000100 4
00000000000000000000000000001000 8
00000000000000000000000000010000 16
00000000000000000000000000100000 32
00000000000000000000000001000000 64
00000000000000000000000000000101 5 (4 + 1)
00000000000000000000000000001101 13 (8 + 4 + 1)
00000000000000000000000000101101 45 (32 + 8 + 4 + 1)
This means that a negative number is the bitwise NOT of the number plus 1:
00000000000000000000000000000101 5
11111111111111111111111111111011 -5
00000000000000000000000000000110 6
11111111111111111111111111111010 -6
00000000000000000000000000101000 40
11111111111111111111111111011000 -40
function dec2bin(dec){
return (dec >>> 0).toString(2);
}
function bin2dec(bin){
return parseInt(bin, 2).toString(10);
}
JavaScript Regular Expressions
The search pattern can be used for text search and text replace operations.
When you search for data in a text, you can use this search pattern to describe what you are
searching for.
Regular expressions can be used to perform all types of text search and text replace operations.
Syntax
/pattern/modifiers;
Example
/w3schools/i;
Example explained:
The replace() method returns a modified string where the pattern is replaced.
Example
Use a case insensitive regular expression to replace Microsoft with W3Schools in a string:
Visit W3Schools!
g Perform a global match (find all matches rather than stopping after the first match)
[abc]
[0-
9]
(x|y
)
Metacharacters are characters with a special meaning:
Metachara Descripti
cter on
Find a
\d
digit
\s
Find a match at the beginning of a word like this: \bWORD, or at the end of a word like this:
WORD\b
\
b
\uxxxx Find the Unicode character specified by the hexadecimal number xxxx
Tr
Quantifi
Description y
er
it
n+
Matches
any string
that
contains
n*
zero or
more
occurrenc
es of n
n?
Matches
any string
that
contains
zero or
one
occurrenc
es of n
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.
Example
Since there is an "e" in the string, the output of the code above will be:
true
You don't have to put the regular expression in a variable first. The two lines above can be
shortened to one:
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.
Example
The reference contains descriptions and examples of all RegExp properties and methods.
The try statement lets you test a block of code for errors.
The finally statement lets you execute code, after try and catch, regardless of the result.
Errors can be coding errors made by the programmer, errors due to wrong input, and other
unforeseeable things.
Example
<p id="demo"></p>
<script>
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
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.
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
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 exception (err) is caught by the catch statement and a custom error message is displayed:
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
const message = document.getElementById("p01");
message.innerHTML = "";
let x = document.getElementById("demo").value;
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
</script>
</body>
</html>
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:
You can read more about forms validation in a later chapter of this tutorial.
Syntax
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
}
Example
function myFunction() {
const message = document.getElementById("p01");
message.innerHTML = "";
let x = document.getElementById("demo").value;
try {
if(x == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
x = Number(x);
if(x > 10) throw "is too high";
if(x < 5) throw "is too low";
}
catch(err) {
message.innerHTML = "Error: " + err + ".";
}
finally {
document.getElementById("demo").value = "";
}
}
The error object provides two useful properties: name and message.
Eval Error
An EvalError indicates an error in the eval() function.
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.
Example
let num = 1;
try {
num.toPrecision(500); // A number cannot have 500 significant digits
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
Reference Error
A ReferenceError is thrown if you use (reference) a variable that has not been declared:
Example
let x = 5;
try {
x = y + 1; // y cannot be used (referenced)
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
Syntax Error
A SyntaxError is thrown if you try to evaluate code with a syntax error.
Example
try {
eval("alert('Hello)"); // Missing ' will produce an error
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
Type Error
A TypeError is thrown if you use a value that is outside the range of expected types:
Example
let num = 1;
try {
num.toUpperCase(); // You cannot convert a number to upper case
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
try {
decodeURI("%%%"); // You cannot URI decode percent signs
}
catch(err) {
document.getElementById("demo").innerHTML = err.name;
}
fileName (Mozilla)
lineNumber (Mozilla)
columnNumber (Mozilla)
stack (Mozilla)
description (Microsoft)
number (Microsoft)
Do not use these properties in public web sites. They will not work in all browsers.
Error Object
The Error object provides error information when an error occurs.
Example
In this example we have written "alert" as "adddlert" to deliberately produce an error.
try {
adddlert("Welcome");
}
catch(err) {
document.getElementById("demo").innerHTML =
err.name + "<br>" + err.message;
}
For a tutorial about JavaScript Errors, read our JavaScript Error Tutorial.
fileName (Mozilla)
lineNumber (Mozilla)
columnNumber (Mozilla)
stack (Mozilla)
description (Microsoft)
number (Microsoft)
Do not use these properties in public web sites. They will not work in all browsers.
JavaScript Scope
Scope determines the accessibility (visibility) of variables.
• Block scope
• Function scope
• Global scope
Block Scope
Before ES6 (2015), JavaScript had only Global Scope and Function Scope.
ES6 introduced two important new JavaScript keywords: let and const.
Variables declared inside a { } block cannot be accessed from outside the block:
Example
{
let x = 2;
}
// x can NOT be used here
Variables declared with the var keyword can NOT have block scope.
Variables declared inside a { } block can be accessed from outside the block.
Example
{
var x = 2;
}
// x CAN be used here
Local Scope
Variables declared within a JavaScript function, become LOCAL to the function.
Example
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.
function myFunction() {
var carName = "Volvo"; // Function Scope
}
function myFunction() {
let carName = "Volvo"; // Function Scope
}
function myFunction() {
const carName = "Volvo"; // Function Scope
}
Example
let carName = "Volvo";
// code here can use carName
function myFunction() {
// code here can also use carName
}
Global Scope
Variables declared Globally (outside any function) have Global Scope.
Variables declared with var, let and const are quite similar when declared outside a block.
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.
Example
myFunction();
function myFunction() {
carName = "Volvo";
}
Strict Mode
All modern browsers support running JavaScript in "Strict Mode".
You will learn more about how to use strict mode in a later chapter of this tutorial.
Global variables defined with the var keyword belong to the window object:
Example
Global variables defined with the let keyword do not belong to the window object:
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Global Variables</h2>
<p>In HTML, global variables defined with <b>let</b>, will not become window variables.</p>
<p id="demo"></p>
<script>
let carName = "Volvo";
</body>
</html>
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.
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
Example 1
x = 5; // Assign 5 to x
var x; // Declare x
Example 2
var x; // Declare x
x = 5; // Assign 5 to x
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.
The variable is in a "temporal dead zone" from the start of the block until it is declared:
Example
carName = "Volvo";
let carName;
Using a const variable before it is declared, is a syntax errror, so the code will simply not run.
Example
carName = "Volvo";
const carName;
Example 1
var x = 5; // Initialize x
var y = 7; // Initialize y
Example 2
var x = 5; // Initialize x
var y = 7; // Initialize y
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
var x = 5; // Initialize x
var y; // Declare y
y = 7; // Assign 7 to y
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.
Study "use strict" in the next chapter.
"use strict"; Defines that JavaScript code should be executed in "strict mode".
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:
Directive
"use
13.0 10.0 4.0 6.0 12.1
strict"
The numbers in the table specify the first browser version that fully supports the directive.
You can use strict mode in all your programs. It helps you to write cleaner code, like preventing
you from using undeclared variables.
"use strict" is just a string, so IE 9 will not throw an error even if it does not understand it.
Declared at the beginning of a script, it has global scope (all code in the script will execute in
strict mode):
Example
"use strict";
x = 3.14; // This will cause an error because x is not declared
Example
"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):
function myFunction() {
"use strict";
y = 3.14; // This will cause an error
}
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.
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.
"use strict";
x = 3.14; // This will cause an error
"use strict";
x = {p1:10, p2:20}; // This will cause an error
"use strict";
let x = 3.14;
delete x; // This will cause an error
"use strict";
function x(p1, p2) {};
delete x; // This will cause an error
"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
"use strict";
let x = "\010"; // This will cause an error
"use strict";
const obj = {};
Object.defineProperty(obj, "x", {value:0, writable:false});
"use strict";
const obj = {get x() {return 0} };
"use strict";
delete Object.prototype; // This will cause an error
"use strict";
let eval = 3.14; // This will cause an error
"use strict";
let arguments = 3.14; // This will cause an error
"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 ("let x = 2");
alert (x); // This will cause an error
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
Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
What is this?
The JavaScript this keyword refers to the object it belongs to.
this in a Method
In an object method, this refers to the "owner" of the method.
In the example on the top of this page, this refers to the person object.
fullName : function() {
return this.firstName + " " + this.lastName;
}
this Alone
When used alone, the owner is the Global object, so this refers to the Global object.
Example
let x = this;
In strict mode, when used alone, this also refers to the Global object [object Window]:
Example
"use strict";
let x = this;
Example
function myFunction() {
return this;
}
Example
"use strict";
function myFunction() {
return this;
}
this in Event Handlers
In HTML event handlers, this refers to the HTML element that received the event:
Example
<button onclick="this.style.display='none'">
Click to Remove Me!
</button>
Example
const person = {
firstName : "John",
lastName : "Doe",
id : 5566,
myFunction : function() {
return this;
}
};
Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
In other words: this.firstName means the firstName property of this (person) object.
You can read more about call() and apply() later in this tutorial.
In the example below, when calling person1.fullName with person2 as argument, this will refer
to person2, even if it is a method of person1:
Example
const person1 = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person2 = {
firstName:"John",
lastName: "Doe",
}
person1.fullName.call(person2); // Will return "John Doe"
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
const person1 = {
fullName: function() {
}
}
const person2 = {
firstName:"John",
lastName: "Doe",
let x = person1.fullName.call(person2);
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
John Doe
Before:
hello = function() {
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:
Note: This works only if the function has only one statement.
In fact, if you have only one parameter, you can skip the parentheses as well:
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.
Both examples call a method twice, first when the page loads, and once again when the user
clicks a button.
The first example uses a regular function, and the second example uses an arrow function.
The result shows that the first example returns two different objects (window and button), and
the second example returns the window object twice, because the window object is the "owner"
of the function.
Example
With a regular function this represents the object that calls the function:
// Regular Function:
hello = function() {
document.getElementById("demo").innerHTML += this;
}
Example
// Arrow Function:
hello = () => {
document.getElementById("demo").innerHTML += this;
}
Remember these differences when you are working with functions. Sometimes the behavior of
regular functions is what you want, if not, use arrow functions.
Browser Support
The following table defines the first browser versions with full support for Arrow Functions in
JavaScript:
JavaScript Classes
ECMAScript 2015, also known as ES6, introduced JavaScript Classes.
Syntax
class ClassName {
constructor() { ... }
}
Example
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
Example
The example above uses the Car class to create two Car objects.
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.
Syntax
class ClassName {
constructor() { ... }
method_1() { ... }
method_2() { ... }
method_3() { ... }
}
Create a Class method named "age", that returns the Car age:
Example
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() {
let date = new Date();
return date.getFullYear() - this.year;
}
}
Example
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age(x) {
return x - this.year;
}
}
Browser Support
The following table defines the first browser version with full support for Classes in JavaScript:
You will learn a lot more about JavaScript Classes later in this tutorial.
JavaScript JSON
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"}
]
}
Because of this similarity, a JavaScript program can easily convert JSON data into native
JavaScript objects.
A name/value pair consists of a field name (in double quotes), followed by a colon, followed by
a value:
"firstName":"John"
JSON Objects
JSON objects are written inside curly braces.
JSON Arrays
JSON arrays are written inside square brackets.
"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).
Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript
object:
Example
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>
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.
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:
Example
<!DOCTYPE html>
<html>
<body>
<script>
a = 5;
b = 6;
c = a + b;
console.log(c);
</script>
</body>
</html>
Tip: Read more about the console.log() method in our 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).
With the debugger turned on, this code will stop executing before it executes the third line.
Example
let x = 15 * 5;
debugger;
document.getElementById("demo").innerHTML = x;
Chrome
• Open the browser.
• From the menu, select "More tools".
• From tools, choose "Developer tools".
• Finally, select Console.
Firefox
• Open the browser.
• From the menu, select "Web Developer".
• Finally, select "Web Console".
Edge
• Open the browser.
• From the menu, select "Developer Tools".
• Finally, select "Console".
Opera
• Open the browser.
• From the menu, select "Developer".
• From "Developer", select "Developer tools".
• Finally, select "Console".
Safari
• Go to Safari, Preferences, Advanced in the main menu.
• Check "Enable Show Develop menu in menu bar".
• When the new option "Develop" appears in the menu:
Choose "Show Error Console".
Always use the same coding conventions for all your JavaScript projects.
Coding conventions can be documented rules for teams to follow, or just be your individual
coding practice.
This page describes the general JavaScript code conventions used by W3Schools.
You should also read the next chapter "Best Practices", and learn how to avoid coding pitfalls.
Variable Names
At W3schools we use camelCase for identifier names (variables and functions).
At the bottom of this page, you will find a wider discussion about naming rules.
firstName = "John";
lastName = "Doe";
price = 19.90;
tax = 0.20;
Examples:
let x = y + z;
const myArray = ["Volvo", "Saab", "Fiat"];
Code Indentation
Always use 2 spaces for indentation of code blocks:
Functions:
function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
}
Do not use tabs (tabulators) for indentation. Different editors interpret tabs differently.
Statement Rules
General rules for simple statements:
Examples:
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
Functions:
function toCelsius(fahrenheit) {
return (5 / 9) * (fahrenheit - 32);
}
Loops:
Conditionals:
• 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.
Example
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:
If a JavaScript statement does not fit on one line, the best place to break it, is after an operator or
a comma.
Example
document.getElementById("demo").innerHTML =
"Hello Dolly.";
Naming Conventions
Always use the same naming convention for all your code. For example:
This is a question programmers often discuss. The answer depends on who you ask:
Hyphens can be mistaken as subtraction attempts. Hyphens are not allowed in JavaScript names.
Underscores:
PascalCase:
camelCase:
Do not start names with a $ sign. It will put you in conflict with many JavaScript library names.
<script src="myscript.js"></script>
File Extensions
HTML files should have a .html extension (.htm is allowed).
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.
Local variables must be declared with the var keyword or the let keyword, otherwise they will
become global variables.
Declarations on Top
It is a good coding practice to put all declarations at the top of each script or function.
This will:
// Use later
firstName = "John";
lastName = "Doe";
price = 19.90;
discount = 0.10;
Initialize Variables
It is a good coding practice to initialize variables when you declare them.
This will:
Initializing variables provides an idea of the intended use (and intended data type).
Example
Example
Example
Example
Beware that numbers can accidentally be converted to strings or NaN (Not a Number).
Example
Subtracting a string from a string, does not generate an error but returns NaN (Not a Number):
Example
Example
0 == ""; // true
1 == "1"; // true
1 == true; // true
0 === ""; // false
1 === "1"; // false
1 === true; // false
Undefined values can break your code. It is a good habit to assign default values to arguments.
Example
function myFunction(x, y) {
if (y === undefined) {
y = 0;
}
}
Example
Declaring these types as objects, slows down execution speed, and produces nasty side effects:
Example
let x = "John";
let y = new String("John");
(x === y) // is false because x is a string and y is an object.
Or even worse:
Example
This if statement returns false (as expected) because x is not equal to 10:
let x = 0;
if (x == 10)
let x = 0;
if (x = 10)
let x = 0;
if (x = 0)
let x = 10;
let y = "10";
if (x == y)
In strict comparison, data type does matter. This if statement returns false:
let x = 10;
let y = "10";
if (x === y)
let x = 10;
switch(x) {
case 10: alert("Hello");
}
let x = 10;
switch(x) {
case "10": alert("Hello");
}
Because of this, adding a number as a number will produce a different result from adding a
number as a string:
let x = 10;
x = 10 + 5; // Now x is 15
let y = 10;
y = + "5"; // Now y is "105"
let x = 10;
let y = "5";
let z = x + y; // Now z is "105"
Misunderstanding Floats
All numbers in JavaScript are stored as 64-bits Floating point numbers (Floats).
All programming languages, including JavaScript, have difficulties with precise floating point
values:
let x = 0.1;
let y = 0.2;
let z = x + y // the result in z will not be 0.3
Example
Example 1
let x =
"Hello World!";
Example 2
let x = "Hello
World!";
You must use a "backslash" if you must break a statement in a string:
Example 3
let x = "Hello \
World!";
Misplacing Semicolon
Because of a misplaced semicolon, this code block will execute regardless of the value of x:
if (x == 19);
{
// code block
}
Because of this, these two examples will return the same result:
Example 1
function myFunction(a) {
let power = 10
return a * power
}
Example 2
function myFunction(a) {
let power = 10;
return a * power;
}
JavaScript will also allow you to break a statement into two lines.
function myFunction(a) {
let
power = 10;
return a * power;
}
But, what will happen if you break the return statement in two lines like this:
Example 4
function myFunction(a) {
let
power = 10;
return
a * power;
}
Example 5
function myFunction(a) {
let
power = 10;
return;
a * power;
}
Explanation
If a statement is incomplete like:
let
JavaScript will try to complete the statement by reading the next line:
power = 10;
But since this statement is complete:
return
return;
This happens because closing (ending) statements with semicolon is optional in JavaScript.
JavaScript will close the return statement at the end of the line, because it is a complete
statement.
Arrays with named indexes are called associative arrays (or hashes).
Example
If you use a named index, when accessing an array, JavaScript will redefine the array to a
standard object.
After the automatic redefinition, array methods and properties will produce undefined or
incorrect results:
Example:
Object Example:
Array Example:
WARNING !!
JSON:
JSON:
Example:
But you cannot test if an object is null, because this will throw an error if the object is
undefined:
Incorrect:
To solve this problem, you must test if an object is not null, and not undefined.
Incorrect:
Because of this, you must test for not undefined before you can test for not null:
Correct:
JavaScript Performance
How to speed up your JavaScript code.
Each statement in a loop, including the for statement, is executed for each iteration of the loop.
Statements or assignments that can be placed outside the loop will make the loop run faster.
Bad:
Better Code:
let l = arr.length;
for (let i = 0; i < l; i++) {
The bad code accesses the length property of an array each time the loop is iterated.
The better code accesses the length property outside the loop and makes the loop run faster.
If you expect to access a DOM element several times, access it once, and use it as a local
variable:
Example
This will always improve page loading, and speed up rendering (page display), especially on
smaller devices.
Every attempt to search the DOM (like getElementsByTagName) will benefit from a smaller
DOM.
With this:
While a script is downloading, the browser will not start any other downloads. In addition all
parsing and rendering activity might be blocked.
The HTTP specification defines that browsers should not download more than two components
in parallel.
An alternative is to use defer="true" in the script tag. The defer attribute specifies that the
script should be executed after the page has finished parsing, but it only works for external
scripts.
If possible, you can add your script to the page by code, after the page has loaded:
Example
<script>
window.onload = function() {
const element = document.createElement("script");
element.src = "myScript.js";
document.body.appendChild(element);
};
</script>
In JavaScript you cannot use these reserved words as variables, labels, or function names:
You can read more about the different JavaScript versions in the chapter JS Versions.
Do not use these words as variables. ECMAScript 5/6 does not have full support in all browsers.
JavaScript Objects, Properties, and Methods
You should also avoid using the name of JavaScript built-in objects, properties, and methods:
JavaObject JavaPackage
You should also avoid using the name of HTML and Window objects and properties:
window
Examples:
JavaScript Objects
In JavaScript, objects are king. If you understand objects, you understand JavaScript.
JavaScript Primitives
A primitive value is a value that has no properties or methods.
• string
• number
• boolean
• null
• undefined
Primitive values are immutable (they are hardcoded and therefore cannot be changed).
if x = 3.14, you can change the value of x. But you cannot change the value of 3.14.
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
Example
Objects are variables too. But objects can contain many values.
Object values are written as name : value pairs (name and value separated by a colon).
Example
Example
ADVERTISEMENT
Object Properties
The named values, in JavaScript objects, are called properties.
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
Object Methods
Methods are actions that can be performed on objects.
Object properties can be both primitive values, other objects, and functions.
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function() {return this.firstName + " " + this.lastName;}
JavaScript objects are containers for named values, called properties and methods.
Using an object literal, you both define and create an object in one statement.
An object literal is a list of name:value pairs (like age:50) inside curly braces {}.
The following example creates a new JavaScript object with four properties:
Example
Spaces and line breaks are not important. An object definition can span multiple lines:
Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
This example creates an empty JavaScript object, and then adds 4 properties:
Example
Example
For readability, simplicity and execution speed, use the object literal method.
If person is an object, the following statement will not create a copy of person:
The object x is not a copy of person. It is person. Both x and person are the same object.
Any changes to x will also change person, because x and person are the same object.
Example
const person = {
firstName:"John",
lastName:"Doe",
age:50, eyeColor:"blue"
}
const x = person;
x.age = 10; // Will change both x.age and person.age
JavaScript Object Properties
JavaScript Properties
Properties are the values associated with a JavaScript object.
Properties can usually be changed, added, and deleted, but some are read only.
objectName.property // person.age
or
objectName["property"] // person["age"]
or
Example 1
Example 2
Syntax
The block of code inside of the for...in loop will be executed once for each property.
Example
const person = {
fname:" John",
lname:" Doe",
age: 25
};
Assume that the person object already exists - you can then give it new properties:
Example
person.nationality = "English";
Deleting Properties
The delete keyword deletes a property from an object:
Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
delete person.age;
or delete person["age"];
Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
delete person["age"];
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.
The delete operator is designed to be used on object properties. It has no effect on variables or
functions.
The delete operator should not be used on predefined JavaScript object properties. It can crash
your application.
Nested Objects
Values in an object can be another object:
Example
myObj = {
name:"John",
age:30,
cars: {
car1:"Ford",
car2:"BMW",
car3:"Fiat"
}
}
You can access nested objects using the dot notation or the bracket notation:
Example
myObj.cars.car2;
or:
Example
myObj.cars["car2"];
or:
Example
myObj["cars"]["car2"];
or:
Example
let p1 = "cars";
let p2 = "car2";
myObj[p1][p2];
const myObj = {
name: "John",
age: 30,
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:
Example
Property Attributes
All properties have a name. In addition they also have a value.
These attributes define how the property can be accessed (is it readable?, is it writable?)
In JavaScript, all attributes can be read, but only the value attribute can be changed (and only if
the property is writable).
( ECMAScript 5 has methods for both getting and setting all property attributes)
Prototype Properties
JavaScript objects inherit the properties of their prototype.
The delete keyword does not delete inherited properties, but if you delete a prototype property,
it will affect all objects inherited from the prototype.
Example
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
In the example above, this is the person object that "owns" the fullName function.
JavaScript Methods
JavaScript methods are actions that can be performed on objects.
firstName John
lastName Doe
age 50
eyeColor blue
objectName.methodName()
You will typically describe fullName() as a method of the person object, and fullName as a
property.
The fullName property will execute (as a function) when it is invoked with ().
Example
name = person.fullName();
If you access the fullName property, without (), it will return the function definition:
Example
name = person.fullName;
Adding a Method to an Object
Adding a new method to an object is easy:
Example
person.name = function () {
return this.firstName + " " + this.lastName;
};
HELLO WORLD!
Example
person.name = function () {
return (this.firstName + " " + this.lastName).toUpperCase();
};
Example
const person = {
name: "John",
age: 30,
city: "New York"
};
document.getElementById("demo").innerHTML = person;
Example
const person = {
name: "John",
age: 30,
city: "New York"
};
document.getElementById("demo").innerHTML =
person.name + "," + person.age + "," + person.city;
Example
const person = {
name: "John",
age: 30,
city: "New York"
};
let txt = "";
for (let x in person) {
txt += person[x] + " ";
};
document.getElementById("demo").innerHTML = txt;
Using Object.values()
Any JavaScript object can be converted to an array using Object.values():
const person = {
name: "John",
age: 30,
city: "New York"
};
Example
const person = {
name: "John",
age: 30,
city: "New York"
};
Using JSON.stringify()
Any JavaScript object can be stringified (converted to a string) with the JavaScript function
JSON.stringify():
const person = {
name: "John",
age: 30,
city: "New York"
};
Example
const person = {
name: "John",
age: 30,
city: "New York"
};
{"name":"John","age":50,"city":"New York"}
Stringify Dates
JSON.stringify converts dates into strings:
Example
const person = {
name: "John",
today: new Date()
};
Example
const person = {
name: "John",
age: function () {return 30;}
};
This can be "fixed" if you convert the functions into strings before stringifying.
Example
const person = {
name: "John",
age: function () {return 30;}
};
person.age = person.age.toString();
Stringify Arrays
It is also possible to stringify JavaScript arrays:
Example
["John","Peter","Sally","Jane"]
JavaScript Object Accessors
Getters and setters allow you to define Object Accessors (Computed Properties).
Example
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
language: "en",
get lang() {
return this.language;
}
};
Example
const person = {
firstName: "John",
lastName: "Doe",
language: "",
set lang(lang) {
this.language = lang;
}
};
Example 1
const person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
Example 2
const person = {
firstName: "John",
lastName: "Doe",
get fullName() {
return this.firstName + " " + this.lastName;
}
};
Data Quality
JavaScript can secure better data quality when using getters and setters.
Using the lang property, in this example, returns the value of the language property in upper
case:
Example
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
language: "en",
get lang() {
return this.language.toUpperCase();
}
};
Using the lang property, in this example, stores an upper case value in the language property:
Example
const person = {
firstName: "John",
lastName: "Doe",
language: "",
set lang(lang) {
this.language = lang.toUpperCase();
}
};
Object.defineProperty()
The Object.defineProperty() method can also be used to add Getters and Setters:
A Counter Example
// Define object
const obj = {counter : 0};
// Define setters
Object.defineProperty(obj, "reset", {
get : function () {this.counter = 0;}
});
Object.defineProperty(obj, "increment", {
get : function () {this.counter++;}
});
Object.defineProperty(obj, "decrement", {
get : function () {this.counter--;}
});
Object.defineProperty(obj, "add", {
set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, "subtract", {
set : function (value) {this.counter -= value;}
});
Example
It is considered good practice to name constructor functions with an upper-case first letter.
Sometimes we need a "blueprint" for creating many objects of the same "type".
Objects of the same type are created by calling the constructor function with the new keyword:
ADVERTISEMENT
Note that this is not a variable. It is a keyword. You cannot change the value of this.
Example
myFather.nationality = "English";
The property will be added to myFather. Not to myMother. (Not to any other person objects).
Example
myFather.name = function () {
return this.firstName + " " + this.lastName;
};
The method will be added to myFather. Not to myMother. (Not to any other person objects).
Example
Person.nationality = "English";
To add a new property to a constructor, you must add it to the constructor function:
Example
Example
You cannot add a new method to an object constructor the same way you add a new method to
an existing object.
Adding methods to an object constructor must be done inside the constructor function:
Example
The changeName() function assigns the value of name to the person's lastName property.
myMother.changeName("Doe");
JavaScript knows which person you are talking about by "substituting" this with myMother.
The Math() object is not in the list. Math is a global object. The new keyword cannot be used on
Math.
Example
String Objects
Normally, strings are created as primitives: firstName = "John"
But strings can also be created as objects using the new keyword:
firstName = new String("John")
Learn why strings should not be created as object in the chapter JS Strings.
Number Objects
Normally, numbers are created as primitives: x = 30
But numbers can also be created as objects using the new keyword:
x = new Number(30)
Learn why numbers should not be created as object in the chapter JS Numbers.
Boolean Objects
Normally, booleans are created as primitives: x = false
But booleans can also be created as objects using the new keyword:
x = new Boolean(false)
Learn why booleans should not be created as object in the chapter JS Booleans.
Example
We also learned that you can not add a new property to an existing object constructor:
Example
Person.nationality = "English";
To add a new property to a constructor, you must add it to the constructor function:
Example
ADVERTISEMENT
Prototype Inheritance
All JavaScript objects inherit properties and methods from a prototype:
Date objects, Array objects, and Person objects inherit from Object.prototype.
Sometimes you want to add new properties (or methods) to an object constructor.
Example
Person.prototype.nationality = "English";
The JavaScript prototype property also allows you to add new methods to objects constructors:
Example
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.
// Accessing Properties
Object.getOwnPropertyDescriptor(object, property)
Example
const person = {
firstName: "John",
lastName : "Doe",
language : "EN"
};
// Change a property
Object.defineProperty(person, "language", {value : "NO"});
// Defining a getter
get: function() { return language }
// Defining a setter
set: function(value) { language = value }
Example
const person = {
firstName: "John",
lastName : "Doe",
language : "EN"
};
Example
const person = {
firstName: "John",
lastName : "Doe",
language : "EN"
};
Adding a Property
This example adds a new property to an object:
Example
// Create an object:
const person = {
firstName: "John",
lastName : "Doe",
language : "EN"
};
// Add a property
Object.defineProperty(person, "year", {value:"2008"});
Example
//Create an object
const person = {firstName:"John", lastName:"Doe"};
// Define a getter
Object.defineProperty(person, "fullName", {
get: function () {return this.firstName + " " + this.lastName;}
});
A Counter Example
Example
// Define object
const obj = {counter:0};
// Define setters
Object.defineProperty(obj, "reset", {
get : function () {this.counter = 0;}
});
Object.defineProperty(obj, "increment", {
get : function () {this.counter++;}
});
Object.defineProperty(obj, "decrement", {
get : function () {this.counter--;}
});
Object.defineProperty(obj, "add", {
set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, "subtract", {
set : function (i) {this.counter -= i;}
});
A Map object has a property that represents the size of the map.
Map() Properties
Property Description
Example
// Create Objects
const apples = {name: 'Apples'};
const bananas = {name: 'Bananas'};
const oranges = {name: 'Oranges'};
Example
Example
// Create Objects
const apples = {name: 'Apples'};
const bananas = {name: 'Bananas'};
const oranges = {name: 'Oranges'};
Example
// Create a Set
const letters = new Set();
Example
// Create a Set
const letters = new Set();
Example
letters.add("d");
letters.add("e");
Example
letters.add("a");
letters.add("b");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");
letters.add("c");
ADVERTISEMENT
Set Object Methods and Properties
new Set() Creates a new Set object
Function Declarations
Earlier in this tutorial, you learned that functions are declared with the following syntax:
function functionName(parameters) {
// code to be executed
}
Declared functions are not executed immediately. They are "saved for later use", and will be
executed later, when they are invoked (called upon).
Example
function myFunction(a, b) {
return a * b;
}
Function Expressions
A JavaScript function can also be defined using an expression.
Example
const x = function (a, b) {return a * b};
After a function expression has been stored in a variable, the variable can be used as a function:
Example
Functions stored in variables do not need function names. They are always invoked (called)
using the variable name.
The function above ends with a semicolon because it is a part of an executable statement.
ADVERTISEMENT
Functions can also be defined with a built-in JavaScript function constructor called Function().
Example
You actually don't have to use the function constructor. The example above is the same as
writing:
Example
Most of the time, you can avoid using the new keyword in JavaScript.
Function Hoisting
Earlier in this tutorial, you learned about "hoisting" (JavaScript Hoisting).
Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope.
Because of this, JavaScript functions can be called before they are declared:
myFunction(5);
function myFunction(y) {
return y * y;
}
Self-Invoking Functions
Function expressions can be made "self-invoking".
You have to add parentheses around the function to indicate that it is a function expression:
Example
(function () {
let x = "Hello!!"; // I will invoke myself
})();
The function above is actually an anonymous self-invoking function (function without name).
Functions Can Be Used as Values
JavaScript functions can be used as values:
Example
function myFunction(a, b) {
return a * b;
}
Example
function myFunction(a, b) {
return a * b;
}
let x = myFunction(4, 3) * 2;
The arguments.length property returns the number of arguments received when the function
was invoked:
Example
function myFunction(a, b) {
return arguments.length;
}
function myFunction(a, b) {
return a * b;
}
Arrow Functions
Arrow functions allows a short syntax for writing function expressions.
You don't need the function keyword, the return keyword, and the curly brackets.
Example
// ES5
var x = function(x, y) {
return x * y;
}
// ES6
const x = (x, y) => x * y;
Arrow functions do not have their own this. They are not well suited for defining object
methods.
Arrow functions are not hoisted. They must be defined before they are used.
Using const is safer than using var, because a function expression is always constant value.
You can only omit the return keyword and the curly brackets if the function is a single
statement. Because of this, it might be a good habit to always keep them:
Example
A JavaScript function does not perform any checking on parameter values (arguments).
Function arguments are the real values passed to (and received by) the function.
Parameter Rules
JavaScript function definitions do not specify data types for parameters.
Default Parameters
If a function is called with missing arguments (less than declared), the missing values are set to
undefined.
Sometimes this is acceptable, but sometimes it is better to assign a default value to the
parameter:
Example
function myFunction(x, y) {
if (y === undefined) {
y = 2;
}
}
function (x, y = 2) {
// function code
}
The argument object contains an array of the arguments used when the function was called
(invoked).
This way you can simply use a function to find (for instance) the highest value in a list of
numbers:
Example
function findMax() {
let max = -Infinity;
for (let i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
Example
x = sumAll(1, 123, 500, 115, 44, 88);
function sumAll() {
let sum = 0;
for (let i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
If a function is called with too many arguments (more than declared), these arguments can be
reached using the arguments object.
JavaScript arguments are passed by value: The function only gets to know the values, not the
argument's locations.
If a function changes an argument's value, it does not change the parameter's original value.
Because of this, objects will behave like they are passed by reference:
It is also common to say "call upon a function", "start a function", or "execute a function".
In this tutorial, we will use invoke, because a JavaScript function can be invoked without being
called.
function myFunction(a, b) {
return a * b;
}
myFunction(10, 2); // Will return 20
The function above does not belong to any object. But in JavaScript there is always a default
global object.
In HTML the default global object is the HTML page itself, so the function above "belongs" to
the HTML page.
In a browser the page object is the browser window. The function above automatically becomes
a window function.
Example
function myFunction(a, b) {
return a * b;
}
window.myFunction(10, 2); // Will also return 20
This is a common way to invoke a JavaScript function, but not a very good practice.
Global variables, methods, or functions can easily create name conflicts and bugs in the global
object.
The value of this, when used in a function, is the object that "owns" the function.
Note that this is not a variable. It is a keyword. You cannot change the value of this.
Example
function myFunction() {
return this;
}
Invoking a function as a global function, causes the value of this to be the global object.
Using the window object as a variable can easily crash your program.
Invoking a Function as a Method
In JavaScript you can define functions as object methods.
The following example creates an object (myObject), with two properties (firstName and
lastName), and a method (fullName):
Example
const myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
myObject.fullName(); // Will return "John Doe"
The fullName method is a function. The function belongs to the object. myObject is the owner
of the function.
The thing called this, is the object that "owns" the JavaScript code. In this case the value of
this is myObject.
Test it! Change the fullName method to return the value of this:
Example
const myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this;
}
}
Invoking a function as an object method, causes the value of this to be the object itself.
Invoking a Function with a Function Constructor
If a function invocation is preceded with the new keyword, it is a constructor invocation.
It looks like you create a new function, but since JavaScript functions are objects you actually
create a new object:
Example
A constructor invocation creates a new object. The new object inherits the properties and
methods from its constructor.
Method Reuse
With the call() method, you can write a method that can be used on different objects.
The example below creates an object with 3 properties, firstName, lastName, fullName.
Example
const myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
In the example above, this is the person object that "owns" the fullName function.
ADVERTISEMENT
It can be used to invoke (call) a method with an owner object as an argument (parameter).
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
const person2 = {
firstName:"Mary",
lastName: "Doe"
}
Example
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
const person2 = {
firstName:"Mary",
lastName: "Doe"
}
Example
const person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
Method Reuse
With the apply() method, you can write a method that can be used on different objects.
Example
const person = {
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
const person1 = {
firstName: "Mary",
lastName: "Doe"
}
The apply() method is very handy if you want to use an array instead of an argument list.
Example
const person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
Example
const person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
ADVERTISEMENT
Example
Since JavaScript arrays do not have a max() method, you can apply the Math.max() method
instead.
Example
The first argument (null) does not matter. It is not used in this example.
Example
Example
JavaScript Closures
Global Variables
A function can access all variables defined inside the function, like this:
Example
function myFunction() {
let a = 4;
return a * a;
}
But a function can also access variables defined outside the function, like this:
Example
let a = 4;
function myFunction() {
return a * a;
}
Global variables can be used (and changed) by all scripts in the page (and in the window).
A local variable can only be used inside the function where it is defined. It is hidden from other
functions and other scripting code.
Global and local variables with the same name are different variables. Modifying one, does not
modify the other.
Variables created without a declaration keyword (var, let, or const) are always global, even if
they are created inside a function.
Example
function myFunction() {
a = 4;
}
ADVERTISEMENT
Variable Lifetime
Global variables live until the page is discarded, like when you navigate to another page or close
the window.
Local variables have short lives. They are created when the function is invoked, and deleted
when the function is finished.
A Counter Dilemma
Suppose you want to use a variable for counting something, and you want this counter to be
available to all functions.
You could use a global variable, and a function to increase the counter:
Example
// Initiate counter
let counter = 0;
There is a problem with the solution above: Any code on the page can change the counter,
without calling add().
The counter should be local to the add() function, to prevent other code from changing it:
Example
// Initiate counter
let counter = 0;
It did not work because we display the global counter instead of the local counter.
We can remove the global counter and access the local counter by letting the function return it:
Example
It did not work because we reset the local counter every time we call the function.
In fact, in JavaScript, all functions have access to the scope "above" them.
JavaScript supports nested functions. Nested functions have access to the scope "above" them.
In this example, the inner function plus() has access to the counter variable in the parent
function:
Example
function add() {
let counter = 0;
function plus() {counter += 1;}
plus();
return counter;
}
This could have solved the counter dilemma, if we could reach the plus() function from the
outside.
We need a closure.
JavaScript Closures
Remember self-invoking functions? What does this function do?
Example
add();
add();
add();
Example Explained
The variable add is assigned to the return value of a self-invoking function.
The self-invoking function only runs once. It sets the counter to zero (0), and returns a function
expression.
This way add becomes a function. The "wonderful" part is that it can access the counter in the
parent scope.
This is called a JavaScript closure. It makes it possible for a function to have "private"
variables.
The counter is protected by the scope of the anonymous function, and can only be changed using
the add function.
A closure is a function having access to the parent scope, even after the parent function has
closed.
JS Classes
JavaScript Classes
ECMAScript 2015, also known as ES6, introduced JavaScript Classes.
Syntax
class ClassName {
constructor() { ... }
}
Example
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
Using a Class
When you have a class, you can use the class to create objects:
Example
The example above uses the Car class to create two Car objects.
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.
Syntax
class ClassName {
constructor() { ... }
method_1() { ... }
method_2() { ... }
method_3() { ... }
}
Create a Class method named "age", that returns the Car age:
Example
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() {
let date = new Date();
return date.getFullYear() - this.year;
}
}
Example
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age(x) {
return x - this.year;
}
}
Browser Support
The following table defines the first browser version with full support for Classes in JavaScript:
"use strict"
The syntax in classes must be written in "strict mode".
You will get an error if you do not follow the "strict mode" rules.
Example
In "strict mode" you will get an error if you use a variable without declaring it:
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() {
// date = new Date(); // This will not work
let date = new Date(); // This will work
return date.getFullYear() - this.year;
}
}
Class Inheritance
To create a class inheritance, use the extends keyword.
A class created with a class inheritance inherits all the methods from another class:
Example
Create a class named "Model" which will inherit the methods from the "Car" class:
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}
By calling the super() method in the constructor method, we call the parent's constructor
method and gets access to the parent's properties and methods.
Inheritance is useful for code reusability: reuse properties and methods of an existing class when
you create a new class.
It can be smart to use getters and setters for your properties, especially if you want to do
something special with the value before returning them, or before you set them.
To add getters and setters in the class, use the get and set keywords.
Example
Create a getter and a setter for the "carname" property:
class Car {
constructor(brand) {
this.carname = brand;
}
get cnam() {
return this.carname;
}
set cnam(x) {
this.carname = x;
}
}
document.getElementById("demo").innerHTML = myCar.cnam;
Note: even if the getter is a method, you do not use parentheses when you want to get the
property value.
The name of the getter/setter method cannot be the same as the name of the property, in this case
carname.
Many programmers use an underscore character _ before the property name to separate the
getter/setter from the actual property:
Example
You can use the underscore character to separate the getter/setter from the actual property:
class Car {
constructor(brand) {
this._carname = brand;
}
get carname() {
return this._carname;
}
set carname(x) {
this._carname = x;
}
}
let myCar = new Car("Ford");
document.getElementById("demo").innerHTML = myCar.carname;
To use a setter, use the same syntax as when you set a property value, without parentheses:
Example
class Car {
constructor(brand) {
this._carname = brand;
}
get carname() {
return this._carname;
}
set carname(x) {
this._carname = x;
}
}
Hoisting
Unlike functions, and other JavaScript declarations, class declarations are not hoisted.
That means that you must declare a class before you can use it:
Example
class Car {
constructor(brand) {
this.carname = brand;
}
}
Note: For other declarations, like functions, you will NOT get an error when you try to use it
before it is declared, because the default behavior of JavaScript declarations are hoisting (moving
the declaration to the top).
Example
class Car {
constructor(name) {
this.name = name;
}
static hello() {
return "Hello!!";
}
}
If you want to use the myCar object inside the static method, you can send it as a parameter:
Example
class Car {
constructor(name) {
this.name = name;
}
static hello(x) {
return "Hello " + x.name;
}
}
let myCar = new Car("Ford");
document.getElementById("demo").innerHTML = Car.hello(myCar);