JavaScript Basics

By Xah Lee. Date: . Last updated: .

This page teaches you the basics of JavaScript, for beginners, in 30 minutes.

This tutorial teachs the ES2015 version of JavaScript.

ES2015 is a new JavaScript spec released in 2015, and is supported by all browsers now. It adds significant features to the language.

Running JavaScript

How to Run JavaScript

Comment

All lines beginning with 2 slashs // are ignored.

And any text between /* and */ are ignored.

// this is single line comment

/* this is
multi-line
comment. */

Printing

To print, use alert or console.log.

alert("hello");
// bring up a pop-up dialog
console.log("hello");
// print to browser's console

To see the output of console.log, open your browser's JavaScript console.

[see JS: How to Use Browser Console]

Semicolon can be omitted most of the time. When to insert semicolon is complex. For now, just follow examples in this tutorial. For detail, see JS: Semicolon Rules.

String

Quoting String

Use double quote or single quote for string. There's basically no difference between the two.

let s1 = "Mary's cat";  // double quote
let s2 = 'Mary\'s cat'; // single quote, with escape

Use \n for newline.

// use \n for newline
let ss = "cat\ndog";

console.log(ss); // prints 2 lines

Literal newline in string is not allowed. Use backslash to continue a line.

// illegal syntax. Literal newline is not allowed
let s = "a
b";

// use backslash to continue a line
let s = "c\
d";

console.log(s); // prints cd

String length

"abc".length; // 3

Note: no parenthesis after “length”. (because “length” is a “property”, not “method”.)

[see JS: Property Overview]

Substring

string.slice(begin_index, end_index) → return a substring from begin_index to end_index, not including the end_index.

Index starts at 0.

[see JS: String.prototype.slice]

const ss = "01234";

console.log( ss.slice(1,3) === "12"); // true

Join String

String join. Use the plus operator +.

// string join
console.log( "tiger" + "rabbit"); // tigerrabbit

String Methods

There are many string functions. For a full list, see:

JS: String.prototype

For detail about string, see

JS: String Overview

Arithmetic Operators

Basic arithmetic.

3 + 4; // 7
3 - 4; // -1
3 * 4; // 12
3 / 4; // 0.75

// remainder (mod)
10 % 3; // 1

// negation
-(3+4); // -7

// power
2**3 // 8

// square root
console.log (
Math.sqrt(4) === 2
);
// true

// cube root
console.log (
Math.cbrt(8) === 2
);
// true

// 4th root
console.log (
Math.pow(16, 1/4) === 2
);
// true

[see JS: Math]

Assignment Operators

Assignment lets you store a value to a variable.

let z = 5; // 5
console.log ( z ); // 5

Assignment returns a value.

// assignment returns a value
let z;

console.log ( (z = 2) + 1 ); // 3
console.log ( z ); // 2

JavaScript also supports x++ and others.

[see JS: Operators]

Number

JavaScript doesn't have int/float distinction. They are just type “number”. It's similar to other language's “float”.

console.log(typeof 3); // prints "number"
console.log(typeof 3.028487); // prints "number"

Convert Decimal to Integer

Use one of

to convert a number to integer.

let x = 3.5847;

let f = Math.floor( x );
let c = Math.ceil( x );

console.log(f); // prints 3
console.log(c); // prints 4

console.log(Math.round( 3.54 )); // prints 4
console.log(Math.round( 3.55 )); // prints 4

[see JS: Math]

String/Number Conversion

String to Number

Number to String

JS: Number.prototype.toString

Variables

The following are ways to declare and or assign variable.

// declare variable
let x;
// declare multiple variables
let a, b, c;
// declare variable and assign
let x = 4;
// declare variable and assign multiple variables
let a = 1, b = 2, c = 3;
// declare multiple variables, some with value
let a, b = 2, c;

[see JS: let Declaration]

Besides let, there's also const and var. They all have the same syntax.

const is like let, except that it must be assigned a value, and once assigned, it cannot be changed.

[see JS: const Declaration]

var is like let, but has complex scoping rules and has name hoisting. var is pre-ES2015. You should never use it.

[see JS: var Declaration]

[see JS: var Declaration Order]

[see JS: var Name Scope]

Data Types

Every JavaScript value has a type.

JavaScript value types are:

[see JS: Value Types]

True and False

true and false are builtin boolean data types.

Zero, empty string, undefined, null, NaN, eval to false in a “if” statement. Everything else eval to true.

[see JS: true, false]

Logic Operators

// The “and” operator
true && true //  true

// The “or” operator
true || true //  true

// The “negation” operator
!true // false

Comparison Operators

3 < 4;         // true
3 > 4;         //  false

3 == 3;        // true.
3 == "3";      // true.  note: 「==」 does automatic type conversion
3 === "3";     // false.  True if both sides are same type and equal

3 != 4;        // true. The 「!=」 is the negation of 「==」
3 !== 4;       // true. The 「!==」 is the negation of 「===」

What is the difference between == and ===?

== does automatic type conversion. === does not.

You should always use ===.

If Then Else

Simple “if” statement.

if (3 < 4) {console.log("yes");}

“if else” statement.

if (3 <= 4) {console.log("yes");}
else {console.log("no");}

“else if” chain.

let x = 3;
if (x == 1) {console.log("is 1");}
else if (x == 2) {console.log("is 2");}
else if (x == 3) {console.log("is 3");}
else {console.log("not found");}

[see JS: Branch Control: if then else, switch]

Iteration; Loop

The most useful loop syntax is “for” loop.

for (let i=0; i < 9; i++) { console.log(i); }

[see JS: for while do Loop]

Array

JS: Array Basics

Define Function

Example of defining a function:

function ff(x, y) { return x + y;}
console.log(ff(3, 4)); // 7

If the function does not have a return statement, it returns undefined.

JavaScript is a functional language. The definition of a function returns a value of type “function” that represent the function. You can pass a function as argument into a function. Function can return a function. You can also have nested function. Understanding how functions can be passed around is essential, because it is heavily used in JavaScript code.

For detail, see: JS: Functional Programing

JavaScript Object

JS: Object Basics

JavaScript Basics

  1. JavaScript Basics
  2. Operators
  3. true, false
  4. Branch Control
  5. Loop
  6. Array Basics
  7. Object Basics

Value Types

  1. Value Types
  2. Primitive Value
  3. “typeof” Operator

Variable

  1. let
  2. const
  3. var 👎
  4. var Order 👎
  5. var Scope 👎
  6. Global Variable
  7. Destructuring Assignment

String

  1. String Overview
  2. Template String
  3. String Escape Sequence
  4. Unicode Escape Sequence
  5. Char, Code Unit, Codepoint

Function

  1. Define Function
  2. Arrow Function ⭐
  3. Function Params
  4. “arguments” Object
  5. Rest Params ⭐
  6. Arg Default Value ⭐
  7. Arg Destructure ⭐
  8. f Declaration vs Expression
  9. Closure
  10. f call apply bind
  11. Functional Programing

Object Property

  1. Property Overview
  2. Property Key
  3. Dot vs Bracket Notation
  4. Create/Delete Property
  5. Get/Set Property
  6. Property Existence
  7. Access Property
  8. List Properties
  9. Property Attributes
  10. Getter/Setter
  11. Property Descriptor
  12. Symbol

Object and Inheritance

  1. Object Overview
  2. Object Type
  3. Find Object's Type
  4. Prototype Chain
  5. Check is in Prototype Chain
  6. Get/Set Parent
  7. Show Prototype Chain
  8. Create Object
  9. Object Literal Expr
  10. Create Object with Parent X
  11. Prevent Adding Property
  12. Clone Object
  13. Test Object Equality
  14. Add Method to Prototype

Array

  1. Understand JS Array
  2. Create Array
  3. Sparse Array
  4. Array-Like Object
  5. Array How-To

Constructor/Class

  1. “this” Binding
  2. What's Constructor?
  3. Property Key "prototype"
  4. Operator “new”
  5. Operator “instanceof”
  6. Property Key “constructor”
  7. Class
  8. Keyword “extends”
  9. Keyword “super”

Iterable ⭐

  1. Interface
  2. Iterable
  3. Iterator
  4. Iterator Prototype
  5. for-of Loop
  6. Spread Operator
  7. Generator
  8. Generator Function

Regular Expression

  1. RegExp Basics
  2. RegExp Syntax
  3. Regex Find/Replace

Date

  1. Date Tutorial
  2. Compute Date Range

Set Object

  1. Set Object
  2. Union, Intersection, Diff

Map Object

  1. Map Object
  2. Iterate Over Map Object
  3. Convert Object to/from Map
  4. Map Filter
  5. Reverse Key/Value

Number

  1. String to/from Number
  2. Convert Decimal/Hexadecimal
  3. Format Number
  4. Random Number

Misc

  1. Import/Export
  2. Promise
  3. Proxy
  4. Try Catch Throw Finally
  5. ES2015 Features
  6. ES2016, 2017, 2018, 2019
  7. How to Convert ES5 to ES2015
  8. Style Guide
  9. Semicolon Rules
  10. Exclamation Before Function
  11. How to Determine Strict Mode?
  12. x.y.z Associativity
  13. Function Chain
  14. Random Number, Range, Integer, Element
  15. Timing JS Code
  16. Range Function for Array
  17. Tagged Template String
  18. Allowed Characters in Identifier
  19. Encode URL, Escape String

Object Reference

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials