JavaScript Tutorial by Example

By Xah Lee. Date: . Last updated: .

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

Running JavaScript

How to Run JavaScript

Printing

To print, use alert or console.log.

/* this is
multi-line
comment */

// this is single line comment

alert("hello"); // popup a dialog

console.log("hello"); // print to browser's console

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

〔➤see JavaScript: How to Use Browser's JS 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 JavaScript: Semicolon Rules.

String

Quoting String

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

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

Use \n for newline.

// use \n for newline
var 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
var s = "a
b";

// use backslash to continue a line
var 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 JavaScript: Property Overview

〔➤see JavaScript: String.prototype

Substring

string.slice(begin_index) → returns a substring from begin_index to end of string.

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

〔➤see JavaScript: String.prototype.slice

// get substring example using .slice()

var ss = "01234";

console.log(ss.slice(1));       // 1234

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

console.log(ss.slice(1,-1));    // 123

console.log(ss.slice(1,0));     // "" empty

console.log(ss.slice(-3,-1));   // 23

Join String

String join. Use the plus operator +.

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

String Methods

〔➤see JavaScript: String.prototype

Arithmetic Operators

Basic arithmetic.

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

10 % 3;     // 1 → remainder (mod)
-(3+4);     // -7 → negation

Math.pow(2,3);    // 8 → exponential
Math.pow(2,1/2);  // 1.4142135623730951 → square root

Assignment Operators

Assignment returns a value.

// assignment returns a value
var z = 5; // returns 5
console.log((z = 5)*2); // 10

JavaScript also supports x++ and others..

〔➤see JavaScript: 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

You can use {Math.ceiling(), Math.floor(), Math.round()} to get integer.

var x = 3.5847;

var f = Math.floor( x );
var 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 JavaScript: Math Object

String/Number Conversion

〔➤see JavaScript: Convert String to Number

Variables

The following are ways to declare and or assign variable.

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

〔➤see JavaScript: Variable

Data Types

Variable doesn't have type. Value has type.

JavaScript datatypes are:

〔➤see JavaScript: Data 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 JavaScript: What's True, False?

Logic Operators

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

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

!true // false. The “negation” operator

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 === instead of ==. When testing for boolean, always be as explicit as possible. Don't rely on what the language considers as true.

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.

var 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 JavaScript: Branch Control: if then else, switch

Iteration; Loop

The most useful loop syntax is “for” loop.

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

〔➤see JavaScript: for while do Loop

Array

〔➤see JavaScript: 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: JavaScript: Functional Programing

JavaScript Object

〔➤see JavaScript: Object Basics

JavaScript Basics

  1. How to Run JavaScript
  2. JavaScript: How to Use Browser's JS Console
  3. JavaScript Tutorial by Example
  4. JavaScript: Data Types
  5. JavaScript: What's True, False?
  6. JavaScript: Operators
  7. JavaScript: Variable
  8. JavaScript: Branch Control: if then else, switch
  9. JavaScript: for while do Loop
  10. JavaScript: Array Basics
  11. JavaScript: Object Basics
  12. JavaScript: RegExp Tutorial
  13. JavaScript: Throw Try Catch Finally
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.